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
8a4f02eac988774c9f96a74da861aacfe82f4e00
KnowledgeZooClient: Constructing Knowledge Graph for Android Li Li Faculty of Information Technology, Monash University Melbourne, Australia Jun Gao, Pingfan Kong SnT, University of Luxembourg Luxembourg Haoyu Wang Beijing University of Posts and Telecommunications Beijing, China Mengyu Huang Hong Kong University of Science and Technology Hong Kong, China Yuan-Fang Li Faculty of Information Technology, Monash University Melbourne, Australia Tegawendé F. Bissyandé SnT, University of Luxembourg Luxembourg ABSTRACT In this work, we describe the design and implementation of a reusable tool named KnowledgeZooClient targeting the construction, as a crowd-sourced effort, of a knowledge graph for Android apps. KnowledgeZooClient is made up of two modules: (1) the Metadata Extraction Module (MEM), which aims at extracting metadata from Android apps and (2) the Metadata Integration Module (MIM) for importing and integrating extracted metadata into a graph database. The usefulness of KnowledgeZooClient is demonstrated via an exclusive knowledge graph called KnowledgeZoo, which contains information on over 500,000 apps already and still keeps growing. Interested users can already benefit from KnowledgeZoo by writing advanced search queries so as to collect targeted app samples. 1 INTRODUCTION Google’s Android mobile operating system, has steadily increased its market share since 2011 and is now leading the global market, occupying over 85% of market share. One reason contributing to this success could be the continuous and rapid growth of Android apps. Indeed, as of June 2018, the number of Android apps on Google Play, the official Android app market, has exceeded 3.3 million, with only 14% of them considered as low-quality apps 1. The success of Android, on the one hand, brings several benefits to app developers and users, while on the other hand, it makes Android the target of choice to attackers and opportunistic developers. As demonstrated in the recent Symantec Internet Security Threat Report [1], threats in the mobile space continue to grow year on year. In 2017, the number of new malware variants has increased 54%. To cope with this, researchers have introduced various approaches (e.g., privacy leaks identification [2], ad fraud detection, etc.) to secure Android apps so as to keep users from being infected [3]. All of the above approaches require a reliable benchmark dataset to evaluate their performance. Unfortunately, it is not easy to build such a targeted dataset from scratch. As a result, researchers often apply their approaches to randomly selected apps, including both relevant and irrelevant samples. Many efforts are hence wasted to analyse the irrelevant ones. As an example, many researchers now rely on AndroZoo [4], which provides over 5.8 million Android apps for the community, to obtain experimental samples. If a researcher is only interested in apps that are obfuscated and have used reflection in their code, she still has to download all the apps and then filter the interested ones. To tackle this problem, Li et al. [5] attempt to facilitate the access of AndroZoo by providing to the research community sufficient metadata associated with the AndroZoo apps. Users of AndroZoo can therefore pre-select a set of apps that are all relevant to their research. Unfortunately, the metadata is shared via plain text, which is difficult to leverage for complicated cases (e.g., when many conditions are applied). Therefore, to supplement this work, we plan to represent the app metadata via a knowledge graph and share it with the community for our fellow researchers to quickly search for interested apps. Knowledge graphs, closely related to ontology, encompass a structured and semantic representation of entities, their properties and relationships in a domain (e.g., Android). It provides an entity-centric view of the linked data that users can leverage to understand how the different artefacts are connected. For instance, the signature used to sign app 𝑎, which is flagged by VirusTotal as malware, is also used to sign app 𝑏. In other words, such a knowledge graph naturally facilitates the traversal via entities as well as their relationships [6]. Moreover, knowledge graphs do not require a predefined schema. As a result, they allow a more flexible update mechanism than traditional relational databases. To benefit from knowledge graph, we provide to the community a prototype research tool, namely KnowledgeZooClient, aiming to Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. Copyrights for components of this work owned by others than the author(s) must be honored. Abstracting with credit is permitted. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. Request permissions from permissions@acm.org. ASEW '20, September 21–25, 2020, Virtual Event, Australia © 2020 Copyright held by the owner/author(s). Publication rights licensed to ACM. ACM ISBN 978-1-4503-8128-4/20/09 . $15.00 https://doi.org/10.1145/3417113.3422187 extract metadata from Android apps and integrate them into a graph database (i.e., knowledge graph). To demonstrate the usefulness of KnowledgeZooClient, we have applied it on 500,000 Android apps selected from AndroZoo. It takes roughly one day (in parallel with 24 instances) for KnowledgeZooClient to extract the metadata from all the apps and takes several minutes to integrate the metadata into a graph database, which then can be leveraged to support advanced search queries, e.g., to find apps that are released between 2016 and 2017, have used dynamic code loading and reflection features, have accessed the Apache Commons library and have shared the same capability of handling incoming broadcasts. In addition to KnowledgeZooClient, which has been made available on Github, we aim at also building an exclusive knowledge graph (namely KnowledgeZoo) of Android apps integrating as many Android apps as possible. The 500,000 apps are our first attempt towards constructing such a graph. We also encourage crowd-sourced efforts, by running KnowledgeZooClient, to enrich KnowledgeZoo with more app metadata. 2 KNOWLEDGEZOOCLIENT The external goal of this work is to provide a knowledge graph of Android apps for our fellow researchers working in the field of mobile app analysis to quickly search for relevant artefacts so as to facilitate their research in various means, e.g., to search for app samples exactly suitable for their experiments. To this end, we introduce a prototype tool called KnowledgeZoo, for which we share with the community to encourage crowd-sourced efforts to fulfill the aforementioned goal. Figure 1 outlines the overview of the working process of KnowledgeZooClient, where the knowledge graph construction process is made up of two modules. In the first module, namely MEM, KnowledgeZooClient attempts to extract app metadata from Android apps. After app metadata is collected, in the second module, namely MIM, KnowledgeZooClient integrates the harvested app metadata into a growing graph database. We now detail these two modules in Section 2.1 and Section 2.2, respectively. 2.1 Metadata Extraction The metadata extraction module takes as input an Android app and outputs its metadata information in json format, which can then be integrated into a graph database, via the KnowledgeZooClient’s MIM. Table 1 enumerates the metadata types so far KnowledgeZooClient harvests. 2.1.1 APK. Android apps are released and distributed through APK files. For each Android APK file, KnowledgeZooClient collects six artefacts for our fellow researchers. - SHA256/SHA1/MD5: The hash values are provided to uniquely identify an Android app. - APK Size: We provide the APK size information (in byte) of a given app aiming at providing a quick means for researchers to calculate how much space they may need in order to download the actual app to their local disk. - Market: For each APK, when crawling from a market, we also record from which market it is downloaded. Since we do not have a good means to check if a given APK has already been downloaded from other markets, the same APK could be downloaded from several markets. This market artefact represents the market where the app is downloaded from. If the app appears in multiple markets, the market artefact correspondingly shows all the available markets with each separated by a vertical virgule (e.g., play.google.com|anzhi indicates that the app is downloaded from both Google Play and the Anzhi market). - Certificate: We provide the certificate signature of a given app, which is usually used to represent the signature of its developers. Literature works recurrently leverage this metadata to pinpoint repackaged (or piggybacked) Android apps, which usually involve a change of app signatures (i.e., developers) [7]. 2.1.2 Manifest. Every Android app is assembled with a global configuration file called AndroidManifest.xml (henceforth referred as manifest), which plays an important role for configuring app’s permissions, components, etc. In this work, we provide five artefacts that are directly extracted from the manifest file of a given app. Those five artefacts are as follows: - Package Name: Package name, also known as application ID, is used to uniquely identify an app on a device and in Google Play. For example, two apps with the same application ID cannot be installed concurrently on the same device. It is also disallowed to update an app in Google Play with a different application ID. - Version Code/Name: Version code/name is provided by app developers to track and name the different versions of their developed apps. Theoretically, version code increases as the app updates. Literature work leverage these information to build app lineages (i.e., sorted app versions of the same app) for supporting the investigation of app evolution. - Sdk Version: Sdk version specifies the API level that the app is targeted. Since different API levels may provide different features, users of KnowledgeZoo could thus leverage this information to conduct evolution-based investigations, especially in coupled with the evolution investigation of the Android operating system. As an example, Li et al. [8] have leveraged this information to investigate the evolution of inaccessible Android APIs (i.e., internal and hidden APIs) of the framework code. - Permission List: Permissions, declared by app developers, are used by Android system to grant the access of protected parts and controls the interaction with other apps. Listing 1 illustrates an example of permission list. Many state-of-the-art works have leveraged permissions to perform specific analyses [9, 10]. In this work, we provide directly the used Figure 1: Knowledge Graph Construction Overview. permissions to the research community for boosting the research of permission-based investigations. Uses of KnowledgeZoo now can collect the declared permissions of a given app without actually downloading the app. - **Component List**: Component is the basic unit constituting an Android app. In Android, there are four types of components: (1) Activity represents user interfaces, the GUI part of an app (2) Service executes compute-intensive tasks in the background, (3) Broadcast Receiver waits to receive event messages and (4) Content Provider provides a means to share structured data within an app or between different apps. In this work, not only the component names and types are collected, KnowledgeZooClient also records the capability of every component declared in the manifest, which can then be leveraged to support advanced inter-component communication analysis. 2.1.3 **DEX**. DEX is the file format of the so-called Dalvik Executable format, which stores the actual code of Android apps. Every Android app should have a DEX file called classes.dex in the top direct of a given APK file, which is also the target where all the metadata in this group collected from. - **Dex Size**: Similar to APK size, Dex size provides another means for users of KnowledgeZoo to pre-select their favoured apps, e.g., apps with their Dex size smaller than 1 megabyte. - **Dex Date**: Dex (assembly) date is extracted based on the last modified time of the Dex file. It can be used to represent the assembling time of a given app and thereby to support all the time-relevant investigations. \begin{table} \centering \begin{tabular}{|c|c|} \hline \textbf{Type} & \textbf{Example} \\ \hline APK & SHA256 DFFCF9ACC7E4AC23895BF8B4AC4F12A450B68R... \\ & SHA1 338A00E4A27C20B139ECD751CC46614711220643 \\ & MD5 920FE692FA1405573BF81FE7F3B84C51 \\ & Apk Size 5461580 \\ & Market play.google.com \\ & Certificate (fingerprint) EC:05:3F:94:81:E8:29:36:3D:A2:3D:5E:0C:BA:A3... \\ & Certificate (owner) CN=AndroidRCert, OU=Android, O=LGEMC, L=Seoul, ST=Seoul, C=KR \\ \hline Manifest & Package Name com.lge.friendsmanager \\ & Main Activity com.lge.friendsmanager.FriendsManagerMainActivity \\ & Version Code 5000019 \\ & Version Name 5.0.19 \\ & Sdk Version (Targeted) 23 \\ & Permission List cf. Listing 1 \\ & Component List cf. Listing 2 \\ \hline DEX & Dex Size 5489904 \\ & Dex Date 01/01/2009 00:00:00 \\ & Native Code true \\ & Dynamic Code false \\ & Reflection true \\ & Obfuscation false \\ & Package List cf. Listing 3 \\ \hline \end{tabular} \caption{Metadata Overview.} \end{table} \begin{verbatim} 1 android.permissionINTERNET 2 com.lge.permissionMANAGE_PERMISSIONS 3 android.permissionACCESS_NETWORK_STATE 4 android.permissionBLUETOOTH 5 android.permissionBLUETOOTH_ADMIN 6 android.permissionACCESS_FINE_LOCATION Listing 1: Permission List Example. \end{verbatim} - **Native Code**: Native code, if true, shows that the app has accessed native code, which is usually written in C or C++. - **Dynamic Code**: Dynamic code, if true, indicates that the app has loaded additional code at runtime. - **Reflection**: Reflection, if true, demonstrates that the app has accessed reflective code. Usually, if the dynamic code item is true, reflection item should be also true, as the additionally loaded code should normally be accessed through reflection. - **Obfuscation**: Obfuscation, if true, indicates that the app has been obfuscated. Researchers such as the authors of [11] could benefit from this artefact to only collect (e.g., download from AndroZoo) obfuscated Android apps, avoiding the download of irrelevant apps and also the analysis of those potential irrelevant apps. - **Package List**: Package list enumerates all the package names of an app (cf. Listing 3). We expect this information to be used by researchers for selecting apps with accessing specific packages. For example, researchers could leverage this information to select a set of apps with which all of them have integrated with ad library com.wandoujia.ads. 2.2 MIM: Metadata Integration Metadata Integration module runs on the server side aiming at importing and integrating the outputs of MEM (i.e., metadata of Android apps) into the current graph database. At the moment, KnowledgeZooClient supports two types of integration: (1) CSV files with pre-defined and well-structured headers and (2) Cypher scripts, a declarative, SQL-inspired language for describing patterns in graphs visually using an ASCII-art syntax. Both types are supported by modern graph databases such as neo4j, the one used in this work. MIM takes into account all the extracted metadata of a given Android app and groups them into eight types. As shown in Figure 2, the schema of our graph database, each type is represented by a knowledge graph node with some properties, e.g., node MARKET has no property, node COMP has one property named compType, while node APK has 12 properties. In knowledge graphs, an edge between two nodes can be associated with some terms specifying the relationships between them. As illustrated in Figure 2, three basic relationships (i.e., “Has”, “From” and “SignedBy”) have been defined. Based on these relationships, one can clearly understand, from the schema of the graph database, the relationships between different nodes, e.g., a market (MARKET node) can have (i.e., via “From” relationship) Android apps (APK node) while an app can have permissions (PERM node). It is worth mentioning that, in addition to existing edge types, which reflect direct relationship between nodes, one can introduce additional relationships to enhance the knowledge graph. Some of these relationships could be derived from existing ones through graph mining. For example, based on the java packages and the signing certificate, we can introduce “similar” or “repackaging” relationships to APK nodes. 3 KNOWLEDGEZOO To demonstrate the usefulness of KnowledgeZooClient and show the advantages of having a knowledge graph of Android apps, we apply KnowledgeZooClient on 578,580 Android apps, which represent all the malicious apps available in AndroZoo, to construct a preliminary knowledge graph (hereafter referred to as KnowledgeZoo). With a modern server (24 cores), it takes roughly one days for KnowledgeZooClient to extract metadata from the half million Android apps and about two minutes to import the metadata into the graph database. Among the 578,580 Android malware considered, KnowledgeZoo contains 5,035,760 distinct nodes and 39,997,923 relationships. We believe the KnowledgeZoo knowledge graph has great potential to support various applications. The most basic application would be to search for app samples under specific conditions. For example, suppose that a researcher wants to apply her/his approach on a set of Android apps that are released between 2016 and 2017 on Google Play, have leveraged the Apache http library and listens to the BOOT_COMPLETED system event. Instead of downloading... MATCH (n: APK)-[:Has]->(p: PACKAGE), (n)-[:From]->(m: MARKET), (n)-[:Has]->(a: ACTION) where n.dexDateInMillis > 1451602800000 and n.dexDateInMillis < 1483225200000 and p.name contains "org.apache.http" and m.name starts with "play.google.com" and a.name ends with "BOOT_COMPLETED" return n; Listing 4: A query example written in the Cypher language, which is supported by our graph database. all the apps from an app repository like AndroZoo to search for such apps, which is time-consuming, one can leverage Knowledge- Zoo to quickly achieve that, e.g., by sending the query shown in Listing 4. Indeed, KnowledgeZoo is capable of understanding the query and outputs the results (i.e., 312 out of 578,580 apps match the aforementioned conditions) in a short time. Moreover, as demonstrated in Figure 3, in addition to the con- textual results, KnowledgeZoo can also visually and interactively present the results in a graph, for which analytics can interact with so as to have a better understanding of the results. Recall that with KnowledgeZooClient, our external goal is to provide a comprehensive and growing knowledge graph of Android apps for our research community. Hence, in our future work, we will continuously integrate more apps into the KnowledgeZoo knowl- dge graph. We also encourage crowd-sourced efforts, by running KnowledgeZooClient, to enrich KnowledgeZoo with more apps. We plan to also extend the ability of KnowledgeZooClient to include more artifacts of Android apps so as to enhance KnowledgeZoo with more types of nodes and relationships. 4 RELATED WORK Since 2018, the first time when Android releases, Android has be- come the most successful mobile system in the industry and one of the most popular research targets in the research community. Researchers have spent tremendous efforts in analyzing and improv- ing Android apps and their running framework systems, as well as the overall Android ecosystem [3, 12, 13]. They have attempted to detect security issues of Android apps [14–16], dissect malicious behaviors of Android malware [7, 17], characterize compatibility issues of Android apps [18–21], improve code qualities of Android apps [22, 23], mitigate energy concerns of Android apps [24, 25], etc. The aforementioned research studies have involved large sets of Android apps, either benign or malicious apps. To prepare the app sets, the authors of these studies either crawl directly from app markets or reuse existing ones that are carefully crafted for supporting Android-based researches. Our community has actually proposed various app datasets [4, 5, 26–29]. The most representative one would be the AndroZoo dataset [4], which has collected over 10 million Android apps and is no doubt the largest dataset of close- sourced Android apps. In line with AndroZoo, Liu et al. [30] have recently proposed another dataset called AndroZooOpen, which contains over 70,000 open-sourced Android apps. In addition to providing the artifacts of Android apps, our com- community starts to offer easily accessible fine-grained app datasets. These datasets, often provided as knowledge graphs, include not only the apps’ metadata (including basic metadata such as the apps’ attributes and advanced metadata such as experimental re- results returned by static/dynamic analysis approaches) but also pre-computed relationships of those apps, aiming at facilitating researchers to conduct automated Android app analyses. For example, Meng et al. [31] have presented to the community a knowledge graph called AndroVault and demonstrated that their knowledge graph helps to promote productive research studies such as malware detection and malware generation [32]. Our approach, although targeting different types of metadata, could be supplementary to theirs, and the knowledge graph constructed in this work should also be capable of facilitating Android-based research. 5 CONCLUSION In this work, we present a research prototype tool called KnowledgeZooClient, which extracts metadata (over 20 types of attributes) from Android apps and integrates them into a graph database. We have applied KnowledgeZoo to more than 500,000 apps, resulting in a knowledge graph, for which we call it as KnowledgeZoo, containing 5,035,760 nodes and 39,997,923 relationships. So far, we demonstrate the usefulness of KnowledgeZoo with a simple example. We believe that the KnowledgeZoo knowledge graph will have great potential to support various applications. In our future work, while enlarging the knowledge graph in terms of the number of apps, we will also introduce more applications (such as revealing repackaged apps) on top of KnowledgeZoo. We also encourage our fellow researchers to leverage KnowledgeZoo to provide creative applications. ACKNOWLEDGMENT This work was supported by the Australian Research Council (ARC) under projects DE200100016 and DP200100020, by the National Natural Science Foundation of China (No. 61702045), and by the National Research Foundation of Singapore. We thank the anonymous reviewers for their valuable suggestions. We also thank our colleagues at the University of Melbourne for their help and support. REFERENCES
{"Source-Url": "https://lilicoding.github.io/papers/li2020knowledgezooclient.pdf", "len_cl100k_base": 5041, "olmocr-version": "0.1.48", "pdf-total-pages": 6, "total-fallback-pages": 0, "total-input-tokens": 19535, "total-output-tokens": 7748, "length": "2e12", "weborganizer": {"__label__adult": 0.0003380775451660156, "__label__art_design": 0.0003101825714111328, "__label__crime_law": 0.0009021759033203124, "__label__education_jobs": 0.0007314682006835938, "__label__entertainment": 7.838010787963867e-05, "__label__fashion_beauty": 0.0001443624496459961, "__label__finance_business": 0.00020754337310791016, "__label__food_dining": 0.0001938343048095703, "__label__games": 0.00075531005859375, "__label__hardware": 0.0013275146484375, "__label__health": 0.00028443336486816406, "__label__history": 0.00024628639221191406, "__label__home_hobbies": 7.623434066772461e-05, "__label__industrial": 0.0002315044403076172, "__label__literature": 0.0002505779266357422, "__label__politics": 0.0002453327178955078, "__label__religion": 0.00030732154846191406, "__label__science_tech": 0.036163330078125, "__label__social_life": 0.00011795759201049803, "__label__software": 0.05621337890625, "__label__software_dev": 0.900390625, "__label__sports_fitness": 0.00017023086547851562, "__label__transportation": 0.00024628639221191406, "__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, 30224, 0.04182]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 30224, 0.16801]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 30224, 0.87713]], "google_gemma-3-12b-it_contains_pii": [[0, 5325, false], [5325, 11091, null], [11091, 15135, null], [15135, 18092, null], [18092, 21496, null], [21496, 30224, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5325, true], [5325, 11091, null], [11091, 15135, null], [15135, 18092, null], [18092, 21496, null], [21496, 30224, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 30224, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 30224, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 30224, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 30224, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 30224, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 30224, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 30224, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 30224, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 30224, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 30224, null]], "pdf_page_numbers": [[0, 5325, 1], [5325, 11091, 2], [11091, 15135, 3], [15135, 18092, 4], [18092, 21496, 5], [21496, 30224, 6]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 30224, 0.0]]}
olmocr_science_pdfs
2024-11-24
2024-11-24
c2aa9678ae1646898e2e0a9fe3ccf14bcefbdc90
Taxonomy of Cross-Platform Mobile Applications Development Tools Amarbir Singh* *(Department of Computer Science, Guru Nanak DevUniversity, Amritsar) Abstract: Most of the developers use the cross-platform mobile development solutions to develop the mobile application once and run it on many platforms. Many of these cross-platform solutions are still under research and development. Also, these solutions are based on different approaches such as Cross-Compilation approach, Virtual Machine approach, and Web-Based approach. There are many survey papers about the cross-platform mobile development solutions but they do not include the most recent tools, including Component-Based approach, Cloud-Based approach, and Merged approach. The main aim of this paper is helping the researchers to know the most recent approaches and the open research issues. This paper surveys the existing cross platform mobile development tools, introduces a comprehensive categorization to the cross-platform tools, defines the pros and cons of each approach and compares the cross-platform mobile development solutions. Keywords —Android, PhoneGap, Rhodes, Appcelerator, Xamarin I. INTRODUCTION One of the joys and pains of being a software developer is choosing the right tools for the job. Technology moves so fast and everyday there are new frameworks and libraries being shared with the world in order to do the job more efficiently. Most people think this would always be a good thing, but choices can be hard. The best one can do is make the best choice with the information you have, and that information is always changing. We are going to take a look at some of the leading frameworks that might be able to help you create your mobile applications a little more efficiently. Before we look at some of the frameworks, we have to set the stage for why there are options. When the latest mobile movement emerged during the release of the first iPhone there were limited choices on how you could produce your applications. Your only real option was Objective C; that was what Apple was pushing and all their software development kit documentation and examples revolved around that. Then Google got involved in the game and after that everything their team produced and documented for doing development was with Java. Of course some people were still dabbling with their Palm and Blackberry at this time, which would have their own set of tools and learning curve. As time progressed, developers started getting a little tired of having to learn a new language and a new way of doing everything on each mobile platform. Frameworks started emerging claiming to be able to develop once and distribute to multiple platforms, allowing developers to focus on getting good at one thing and leveraging that knowledge across mobile devices [1]. The promise was that it was going to allow developers to focus on learning one thing well. II. GOAL AND BENEFITS OF USING CROSS-PLATFORM DEVELOPMENT TOOLS There are number of reasons due to which need for cross platform development tools arisen. The primary goal was to create code once and then distribute it to all the leading mobile devices having different operating systems. Another reason is that, if we use cross platform development tool then we can focus on one or our favourite programming to develop applications otherwise there is a need of expertise in the language supported by the mobile device. By using different Cross platform development tools quality code can be created faster which helps in getting the products to market faster and such code is also supported by current as well as future devices [3]. Various benefits of using cross platform development tools are listed below. A. Code Is Reusable Rather than having to write the specific action or sequence for each platform, a developer can just write the code once and then reuse those bits in later projects or on other platforms. B. Plugins Major frameworks, including Appcelerator and PhoneGap offer easy access to plugins and modules that can easily plug into other services or tools. C. Easy for Web Developers Because most frameworks are dynamic or scripting languages, they are easy for web developers to jump in and use. Moreover, most frameworks have the facility to manage and support HTML5 and CSS3 alongside the calls to more native functions. D. Reduced Development Costs This is perhaps the biggest advantage because it allows companies or brands to get an app onto other platforms without having to invest in a team or developer specific to that ecosystem. E. Support for Enterprise and Cloud Services In addition to plugins and modules for specific functions, most frameworks also have the option to directly integrate with cloud services, including Salesforce.com, AWS, Box.net and others. F. Easy Deployment Deploying and compiling apps is much faster in a cross-platform scenario. This is especially true with many of the new cloud-based build tools that various frameworks are starting to push out. III. VARIOUS CROSS-PLATFORM APPLICATIONS DEVELOPMENT TOOLS A. PhoneGap In PhoneGap all of the front-end is actually delivered as HTML and JavaScript, but the experience is packaged and surrounded with the Cordova magic. What this gives developers the ability to do is use their past web experience and create apps like they would create websites and then use specialized markup to access specific device features. This would include gaining access to the camera, triggering a vibration and getting input back from the accelerometer. You can accomplish a lot, very easily by going this direction with your mobile development. It’s easy because you can leverage your teams experience with web development and put that to work for you with mobile applications. However, I feel this route is the most limiting to the developer and the future of the mobile product. You can really get boxed in by the types of features you can ultimately deliver since you are so abstracted from the core device APIs [4]. This route is going to be good if you have a very sound understanding of the application you are creating and all of it’s current and expected future features. If you can with 100% confidence determine everything you need is do-able with this route, then go for it. I, however, often have a fear that 6, 12, 24 months down the road I’ll get a feature request from a client that will seem like a common mobile feature or no big deal and get completely stone-walled by this approach to mobile development. For that reason I’m pretty hesitant to do anything terribly complex with these technologies. However, they are awesome for mimicking a set of website features on mobile or enabling a website to work offline via a mobile app. ![Interfacing layers of PhoneGap architecture](image-url) PhoneGap holds the top slot in developer mindshare. Cordova/PhoneGap developers write their mobile applications using HTML, JavaScript and CSS. These assets run in a “WebView” inside a native application container on the target platform as shown in Fig 1. The various advantages and disadvantages for PhoneGap are discussed below. Pros 1) Regardless of server side platform & language experience, a significant number of developers have experience with HTML, JavaScript and CSS. Apache Cordova or PhoneGap allows developers to immediately leverage these existing skills. The value of this can’t be overstated – as it reduces training and can enable a quick-to-market stance in companies ready to adopt it. 2) PhoneGap apps install just like a native application, and are able to leverage app store discoverability. 3) PhoneGap follows a plugin architecture, which means that access to native device APIs can be extended in a modular way. There are a lot of PhoneGap plugins to choose from – enabling developers to focus on the web-based skills they already have. Cordova is open source and free, so there are no licensing costs. Cons 1) The strength of being open source and leveraging the talents of a wide array of contributors is both a blessing and curse. If you need to extend your app with a custom Cordova/PhoneGap plugin, odds are you will find one. Yet it may be out of date and not support the target platforms you need. 2) The performance of PhoneGap apps has often been criticized. Native UI will always outperform a hybrid solution, but improvements in device hardware and WebView implementations have narrowed the gap. Your web developers will need to pay close attention to performance, which means their knowledge of profiling tools as well as which web UI frameworks are mobile-friendly is essential. B. Rhodes Rhodes is a cross-platform mobile application tool developed by Motorola Solutions Inc. under Massachusetts Institute of Technology (MIT). It is developed to rapidly build native applications for all major mobile OS’s (iOS, Android, BlackBerry, Windows Mobile/Phone and Symbian). The main goal of Rhodes is to provide a high level of productivity and portability in programming. It is an open source Ruby-based mobile development environment. Thanks to this environment, developers can create and maintain enterprise applications and data based on single source code across different mobile OS’s [6]. RhoMobile suite provides an IDE called RhoStudio which is an innovative solution dedicated to users that want to develop applications through a hosted IDE. This solution can be used across Linux, Mac, and Microsoft Windows OS’s. Alternatively, RhoMobile offers the possibility to write applications with any other editor or IDE which supports HTML, HTML5, CSS, JavaScript and Ruby. The most popular editors are Eclipse, Visual Studio, Netbeans, IntelliJ and TextMate [7]. Rhodes provides native device applications to improve the end-user experience, which work with synchronized local data and take advantage of device capabilities, such as Barcode, Bluetooth, Calendar, Camera, Contacts, GPS, Menu, Near Field Communication (NFC) and Screen Rotation. Rhodes is the only framework that uses Model View Controller (MVC) pattern to develop mobile applications. The MVC pattern creates applications that separate data definitions (models) from business logic and (controllers) from interfaces (views), providing at the same time a point of connection between these elements. Languages used in the view element are HTML, CSS and JavaScript to make mobile applications, whereas in the controller element is Ruby to make the backend support. Moreover, with MVC approach is also possible to write applications that use only the view element. Obviously, it is realizable for applications or sites that require a low level of complexity [8]. Rhodes provides mainly three possibilities to add extendibility in its framework, first can be done by adding external Ruby library to Rhodes, second by creating native extensions for specific Software Development Kit (SDK) of each OS and last by extending the already existing views available in Rhodes. In Fig. 2 Rhodes architecture is shown. Controller, HTML templates and source adapter components are the parts which developers have to implement for the creation of applications, whereas other components are provided by Rhodes such as Rhodes App Generator which is an IDE than can be RhoStudio or another editor, Ruby Executor is the executor of the Ruby code, Device Capabilities are the API’s, Rhom is a mini database ORM (object relational mapper) which provides a high level interface to make it quickly and easily (i.e. the database is SQLite for all mobile OS’s except BlackBerry that is HSQLDB), RhoSync Client is a library to add sync data capability to your applications, and RhoSync simplifies the development of connectivity to enterprise backend applications. Moreover, performing the backend application integration between RhoSync Client and RhoSync Server is reduced by 50-80% the development effort [7]. Various advantages and disadvantages of using Rhodes are given below. Pros 1) Rhodes development files are compiled into native applications that can be executed on real or a virtual devices, indeed, this tool offers a desktop simulator where is possible to run applications. 2) Provides high level of productivity and portability in programming. Cons 1) The plugin architecture works well if you can find the plugins you need or if your web developers are capable of changing gears to write their own custom plugin(s) as needed. C. DragonRad DragonRad 5.0 is a cross-platform mobile ADT developed by Seregon Solutions Inc. DragonRad has Drag and Drop (D&D) features, which requires reduced programming talent to develop applications. It allows developers to design, manage and deploy mobile applications with ease. These deployed mobile applications can be used across iOS, Android, BlackBerry and Windows Mobile. This tool concentrates on database driven mobile enterprise applications with easy and wide range of databases support. DragonRad facilitates integration and synchronization of database system with native functions such as Contacts, Calendar, Geolocation, Menu and Storage. Fig 3 shows the detailed architecture of DragonRad for Android. Various advantages and disadvantages of using DragonRad are given below. Pros 1) This tool is pretty easy to use and has seamless integration to MySQL database. 2) It is very intuitive and application development is extremely fast. Cons 1) DragonRad is a Proprietary platform having a small user community. 2) Documentation is not really good and examples are tough to understand. 3) DragonRad is not suited for building games, it is useful for building data-driven enterprise applications only. --- **Fig 3 Architecture of DragonRAD for Android [5].** D. Appcelerator Appcelerator has been in the cross-platform space since 2006. They originally had an application that was targeted towards making it easy to write desktop apps for both Windows and Apple. They then changed their focus to work on building a tool that made it easier to program cross-platform mobile applications. Titanium is their open source IDE/compiler, allowing you to write your mobile application using JavaScript syntax and tap into the necessary core libraries to create native mobile experiences. With Titanium we have found that it’s not really a one-and-done workflow. There are still differences that need to be accounted for when developing cross-platform applications. For example, an iPhone really only has a home button. All app interactions must be programmed within the application. However, with Android there is a physical back button and other buttons on the keyboard that might interact with your application. Specific situations still need to be accounted for when developing for both of these platforms. Appcelerator also claims that their framework is supporting Windows and Blackberry, but from what I’ve read, it’s been mixed results and certainly isn’t a one click process to get your application running on those platforms. Appcelerator has paid subscription options, but they still have a free, open-source version that has majority of what you need to succeed. The biggest downside to Titanium is that you can’t access everything in the core frameworks. Titanium tries to model and make methods available to you for the most popular device features, but unlike other options, everything is not available out of the box. The good news is that you can always create a custom Titanium module that calls a core feature you need and include that in your project. Appcelerator’s Titanium provides a unified (across devices) JavaScript API, coupled with native-platform-specific features. Developers write JavaScript and utilize a UI abstraction (the Alloy MVC framework) that results in the use of native UI components, greatly aiding UI performance compared to other hybrid options. The various advantages and disadvantages for Appcelerator are discussed below. Pros 1) The use of native UI components is a performance win, and the Alloy framework attempts to normalize UI across platforms. 2) The use of JavaScript to normalize code across platforms enables you to leverage existing skills on multiple target platforms. 3) Appcelerator provides value-adds such as a Backend-as-a-Service (BaaS), app analytics and a marketplace for 3rd party components. Cons 1) Developers are required to manage target platform SDKs locally. It’s highly recommended for your team to establish a controlled build environment/CI process if you choose to manage SDKs locally, especially if you target multiple platforms. SDK version & build-related issues can be a horrific time sink, when you really need your team delivering features. 2) Normalizing the UI across platforms, while arguably a “pro”, is also a “con” in that your team will need to train on a proprietary technology to gain skills that are not directly transferrable outside Titanium. E. Xamarin “Xamarin” has only been around for a couple years, however the team and technology behind it has been in the cross-platform industry for many years. Before developers were concerned about cross-platform mobile apps they were concerned about cross-platform desktop applications. Members of the Xamarin team were behind the very popular Mono project and later the MonoTouch project, which was acquired, spun off, and things happened… then poof: Xamarin. If you are a Microsoft .Net developer, then you’ll know that Mono was the rogue project that worked tirelessly to keep the C# language running and available on Linux. They know a thing or two about working with cross-platform technologies, and they are huge C# fans. Therefore, the programming language preferred for Xamarin is C#. If you are a .NET developer this will probably be your favorite. Xamarin has been excelling at building really cool cloud-testing tools as well. This makes it easier for developers to test their applications across a variety of different devices [13]. Pros 1) Compiles into a truenative APP or APK, uses native UI tools and has cross platform benefits as well as stability. 2) Favourite tool for the .NET developers. Cons 1) Does not provide build once experience, so little more work has to be done if code has to be reused. IV. COMPARISON The Comparison of the five popular cross platform applications development tools is given in Table 1 and Table 2. Table 1 contains the comparison different general features of tools and Table 2 contains the comparison of various development features of tools. <table> <thead> <tr> <th>Name</th> <th>Platforms</th> <th>OS Support</th> <th>Open Source</th> <th>MVC</th> </tr> </thead> <tbody> <tr> <td>PhoneGap</td> <td>iOS, Android, Windows, Blackberry, Symbian</td> <td>Linux, Mac, Windows</td> <td>Yes</td> <td>No</td> </tr> <tr> <td>Rhodes</td> <td>iOS, Android, Windows, Blackberry, Symbian</td> <td>Linux, Mac, Windows</td> <td>Yes</td> <td>Yes</td> </tr> <tr> <td>DragonRad</td> <td>iOS, Android, Windows, Blackberry</td> <td>Linux, Mac, Windows</td> <td>No</td> <td>No</td> </tr> <tr> <td>Appcelerator</td> <td>iOS, Android, Windows, Blackberry</td> <td>Linux, Mac, Windows</td> <td>Yes</td> <td>Yes</td> </tr> <tr> <td>Xamarin</td> <td>iOS, Android, Windows</td> <td>Linux, Mac, Windows</td> <td>Yes</td> <td>No</td> </tr> </tbody> </table> Table 1 General Features <table> <thead> <tr> <th>Name</th> <th>Language</th> <th>IDE</th> <th>Acessibility To Native API</th> </tr> </thead> <tbody> <tr> <td>PhoneGap</td> <td>HTML5, HTML5, CSS3, Java Script</td> <td>Eclipse, XCode</td> <td>Java Script</td> </tr> <tr> <td>Rhodes</td> <td>HTML, RhoStudio</td> <td>Java Script</td> <td></td> </tr> </tbody> </table> V. CONCLUSION There is never a winner when it comes to programming languages and frameworks. The winner is the option you think will be best for you and your product now and into the future. It very well might be that the best option is to write Objective C or Swift for iOS and Java for Android, just because you're awesome at those. Then you can learn C# if needed for Windows later. The choice is yours, and that’s the beauty of it. Our paper is an attempt to make this task of choosing an appropriate tool easier. REFERENCES of Mobile Application for Android Platform”, International Journal of Multimedia and Ubiquitous Engineering, Vol. 9, Tools for Patient Self-Reporting on Mobile Devices”, Proceedings of the 8th Australasian Workshop on Health Informatics and Knowledge Management, Sydney, Australia, pp. 27 – 30. 2015. Techniques for Cross Platform Mobile Application Development”, International Journal of Advanced Research in Computer Engineering & Technology, Vol. 3, Issue 10, on Eclipse”, International Journal of Scientific and Research Platform Mobile Development Tools”, 16th International Conference on Intelligence in Next Generation Networks, Business+Product+and+Services/Software+and+Applications/
{"Source-Url": "http://www.ijctjournal.org/Volume3/Issue2/IJCT-V3I2P36.pdf", "len_cl100k_base": 4287, "olmocr-version": "0.1.53", "pdf-total-pages": 7, "total-fallback-pages": 0, "total-input-tokens": 18754, "total-output-tokens": 5052, "length": "2e12", "weborganizer": {"__label__adult": 0.0003862380981445313, "__label__art_design": 0.0002090930938720703, "__label__crime_law": 0.0002275705337524414, "__label__education_jobs": 0.00041365623474121094, "__label__entertainment": 4.649162292480469e-05, "__label__fashion_beauty": 0.00014913082122802734, "__label__finance_business": 0.00017535686492919922, "__label__food_dining": 0.00026702880859375, "__label__games": 0.0004329681396484375, "__label__hardware": 0.000988006591796875, "__label__health": 0.0002105236053466797, "__label__history": 0.00012755393981933594, "__label__home_hobbies": 4.9233436584472656e-05, "__label__industrial": 0.00019633769989013672, "__label__literature": 0.00012540817260742188, "__label__politics": 0.00016319751739501953, "__label__religion": 0.00028634071350097656, "__label__science_tech": 0.001094818115234375, "__label__social_life": 5.2928924560546875e-05, "__label__software": 0.0038604736328125, "__label__software_dev": 0.98974609375, "__label__sports_fitness": 0.0002334117889404297, "__label__transportation": 0.0003170967102050781, "__label__travel": 0.00015604496002197266}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 22343, 0.02343]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 22343, 0.08606]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 22343, 0.92232]], "google_gemma-3-12b-it_contains_pii": [[0, 3182, false], [3182, 6844, null], [6844, 10455, null], [10455, 13751, null], [13751, 17923, null], [17923, 21415, null], [21415, 22343, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3182, true], [3182, 6844, null], [6844, 10455, null], [10455, 13751, null], [13751, 17923, null], [17923, 21415, null], [21415, 22343, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 22343, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 22343, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 22343, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 22343, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 22343, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 22343, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 22343, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 22343, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 22343, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 22343, null]], "pdf_page_numbers": [[0, 3182, 1], [3182, 6844, 2], [6844, 10455, 3], [10455, 13751, 4], [13751, 17923, 5], [17923, 21415, 6], [21415, 22343, 7]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 22343, 0.07483]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
7b221ce040d40b7ce733dec4e0dd6a5ebcb8b318
Exam directives. In order to pass the exam, the following requirements have to be met: - Clear your desk (no cell phones, cameras, etc.): on your desk you should only have your Legi, your pen and your notes. We provide you with the necessary paper and exam sheets. - Carefully read the first pages of the exam. Write your name and student ID where requested. Before handing in the exam, SIGN ON THE FIRST PAGE. - Your notes (personal summary) should consist of no more than four A4 sheets (eight pages). The personal summary must be handwritten. You are not allowed to bring a copy of somebody else’s summary. - Your answers should be handwritten in blue or black pen (no pencils), clearly readable and in English. Only one answer per question is accepted. Invalid answers should be clearly crossed out. - To answer new questions (e.g. Question 1, not sub-questions!), always use a new page. On the top-right corner of every page write your complete name and Legi-ID. Unless otherwise noted in the question, you should always hand-in your answers on paper! - You must hand in: the exam cover, any extra notes provided by us, the sheets with the exam questions and your solutions. The exam will not be accepted if any of these items are missing. - If something is disturbing you during the exam or preventing you from peacefully solving the exam, please report it immediately to an assistant. Later complaints will not be accepted. Question 1: Bayesian Inference (15 points) Let $X$ be a random variable that depends on a parameter $\vartheta$. The conditional probability density function is given by $$p(x \mid \vartheta) = \begin{cases} \frac{2x}{\vartheta^2}, & 0 < x < \vartheta \\ 0, & \text{otherwise} \end{cases}.$$ Assume that you have observed one realization of the random variable $X = x_1$. a) First, verify that $p(x \mid \vartheta)$ is a proper density function. b) Write the likelihood function $p(x_1 \mid \vartheta)$ as a function of $\vartheta$. You may want to use indicator functions: $\chi_{[a,b]}(x)$ is equal to 1 if $x \in [a,b]$ and 0 otherwise. c) Find the posterior distribution $p(\vartheta \mid x_1)$ for a uniform prior in $[0, 1]$. d) Estimate the uncertainty in the random variable $X$ after observing $x_1$ by calculating the conditional distribution of $X$ on $x_1$. Question 2: Applied Optimization & UQ (20 points) Rumours spread that you are amongst the most notorious programmers and statisticians in the region of Appenzell. The hedge fund Appenance LTD approaches you and wants you to have a look at their price prediction model $M_1$ for cattle trading. They say that their strategy is presumably predicting wrong confidence intervals and hence is heavily underperforming. This particular cattle breed is traded over the counter only during weekends at the local markets in Herisau and for that reason trades data $d = \{d_i\}_{i=1}^N$ is very limited and difficult to collect. Without blinking an eye, you accept their offer and you search for the parameters $\hat{\theta} = (\hat{x}_0, \hat{\sigma}^2)$ that maximize the likelihood of the model, i.e., $$\hat{\theta} = \arg \max_{\theta \in \Theta} \mathcal{L}(\theta; d).$$ For obvious reasons the model can not be disclosed here, but we can tell that $x_0$ is a computational parameter and $\sigma^2$ describes the variance of the model error. You use Korali’s optimizer (CMA-ES) to find the parameters that maximize the loglikelihood. After 4 consecutive runs you observe the following outputs on the screen: --- **Listing 1: Run 1** 1. [Korali] CMA-ES Finished 2. [Korali] Optimum LogLikelihood (Maximize) found: $-8.49194e-01$ 3. [Korali] Optimum LogLikelihood (Maximize) found at: 4. $X0 = +1.503e+00$ 5. $\Sigma2 = +3.501e+00$ 6. [Korali] Stopping Criterium: Function value differences < $(1.00e-12)$ **Listing 2: Run 2** 1. [Korali] CMA-ES Finished 2. [Korali] Optimum LogLikelihood (Maximize) found: $-8.49193e-01$ 3. [Korali] Optimum LogLikelihood (Maximize) found at: 4. $X0 = +3.004e+00$ 5. $\Sigma2 = +0.998e+00$ 6. [Korali] Stopping Criterium: Function value differences < $(1.00e-12)$ **Listing 3: Run 3** 1. [Korali] CMA-ES Finished 2. [Korali] Optimum LogLikelihood (Maximize) found: $-8.49192e-01$ 3. [Korali] Optimum LogLikelihood (Maximize) found at: 4. $X0 = +3.002e+00$ 5. $\Sigma2 = +0.999e+00$ 6. [Korali] Stopping Criterium: Function value differences < $(1.00e-12)$ --- a) You observe that CMA-ES converges to different optima although the parameter of CMA-ES are kept the same in each run (except for the seed). Answer the following questions: - Provide an explanation of the fact CMA-ES returns different results given the same objective function and configuration. - What can you conclude about the problem regarding these results? - Why does this pose a problem in predicting the price of cattle? b) Assume that we know that the likelihood function is a multivariate gaussian mixture with local covariance $\Sigma$, i.e $$\mathcal{L}(\theta; d) = \sum_{i=1}^{2} \omega_i \mathcal{N}(\theta|\mu_i, \Sigma),$$ with $\omega_1 + \omega_2 = 1$ and $$\Sigma = \begin{bmatrix} 1.0 & 0.5 \\ 0.5 & 1.0 \end{bmatrix}.$$ In order to further analyze the model at hand, you want to sample the posterior distribution of the parameters $\theta = (x_0, \sigma^2)$ given the data $d$, $$p(\theta|d) = \frac{p(d|\theta)p(\theta)}{p(d)}.$$ Since we know nothing about the parameters we choose a non informative prior distribution $p(\theta)$. What output do you expect from your sampling algorithm? Please provide 3 qualitative sketches and answer the questions: - Define a prior distribution $p(\theta)$ for $x_0$ and $\sigma^2$. - Specify the weights $\omega_i$ considering the output of CMA-ES from the previous subquestion. • Sketch the sampling, i.e. draw a possible outcome of the samples in a scatter plot $x_0$ vs. $\sigma^2$. Include some contour lines of $p(\theta|d)$ if it supports the interpretability of your figure. Hint: the eigenvalue decomposition of $\Sigma$ is given by $$\Sigma = \frac{1}{\sqrt{2}} \begin{bmatrix} -1 & 1 \\ 1 & 1 \end{bmatrix} \cdot \begin{bmatrix} 0.5 & 0 \\ 0 & 1.5 \end{bmatrix} \cdot \frac{1}{\sqrt{2}} \begin{bmatrix} -1 & 1 \\ 1 & 1 \end{bmatrix}^T.$$ • Sketch the marginal distribution $p(\sigma^2|d) = \int_{-\infty}^{+\infty} p(\theta|d) \, dx_0$. • Sketch the marginal distribution $p(x_0|d) = \int_{-\infty}^{+\infty} p(\theta|d) \, d\sigma^2$. ![Contour plot of sampling distribution](image-url) c) In the meantime the research department of Appenance LTD came up with a more sophisticated pricing model $M_2$, taking into account the PH-value of the grass the cows eat and the amount of days they graze in rain. You discuss this model with your friend Reto Küehli who is a cow specialist and he assures that these parameter have no influence on the development of the cows. Nevertheless the researchers find that the maximal likelihood for the new model $M_2$ is larger than the maximal likelihood for $M_1$ (on data set $d$). Answer the following questions in 3-5 sentences each: - How can you explain that model $M_2$ achieves a “better” likelihood although it includes irrelevant factors. - What other measures do you know from this course that allow you to select between $M_1$ and $M_2$? Also argue why comparing the likelihoods of $M_1$ and $M_2$ is not best practice and why you would choose a different measure. **Note:** 3 sketches are required, 1 graph is spare. Don’t forget to label the axes, and add ticks to the axes where possible (vertically and horizontally) in order to localize your graphs. If you make assumptions, please document it. Please make sure that your plots are consistent throughout. Question 3: Parallel Tasking Theory (20 points) You work at a newly instituted supercomputing center and every morning you receive a queue of 12 jobs that need to be executed. Each job can be executed independently and cannot be parallelized. The computational cost of each job is given in the following in terms of a reference computational load $C$, but you do not know this load a-priori to design an optimal parallel tasking strategy. Communication costs are ignored in this exercise. \[ \begin{array}{cccccccccccc} \text{Job order:} & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 \\ \text{Comp. load:} & 12 & 1 & 1 & 12 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\ \end{array} \] We assume for simplicity that this load can be directly translated to a fixed reference computational time, e.g. that a job of load $C = 7$ can be executed by a single rank in $T = 7$ time units. Time measurements in the following need to be provided in terms of these time units. You are provided with a small compute node with 4 cores, each capable of running a single job at a time, and you are asked to propose algorithms taking advantage of various parallel tasking strategies. a) In the classical divide-and-conquer method the tasks are divided to the available processors. You cannot affect the ordering of the jobs. This leads to the following partition: \[ \begin{array}{cccccccccccc} \text{Job order:} & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 \\ \text{Comp. load:} & 12 & 1 & 1 & 12 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\ \text{Exec. by rank:} & 1 & 1 & 1 & 2 & 2 & 2 & 3 & 3 & 3 & 4 & 4 & 4 \\ \end{array} \] Compute: 1. the total runtime $T_{\text{total}}$ 2. the average rank run-time $T_{\text{avg}}$ 3. the load imbalance ratio $I$ 4. the average rank idle time $W_{\text{avg}}$. b) Now you are asked to apply the producer-consumer strategy. Note that you cannot affect the ordering of the jobs assigned to the ranks. Which rank will execute each job? Please fill in the following array and answer the questions that follow: 1. What is the total runtime $T_{total}$ in this case? 2. What is the average rank run-time $T_{avg}$? 3. What is the load imbalance ratio $I$? 4. What is the average rank idle time $W_{avg}$? 5. What is the disadvantage of the producer-consumer strategy in general? Is the extra effort to implement this strategy worth it in this case? c) The problem with the jobs is that the computational load is not balanced and we do not know the load a-priori to design an optimal tasking strategy. A different ordering of the same jobs might cause the worst case scenario (in terms of run-time) for a divide-and-conquer tasking strategy. 1. What is an example of an ordering that causes this worst case scenario? To which rank is each job assigned in your example? 2. Assuming that the jobs are assigned a random uniform ordering by an external client, what is the probability of a worst case scenario ordering occurring? 3. How much faster is the producer-consumer strategy in this case? Report the speed-up compared to the divide-and-conquer method. Question 4: Parallelizing the Quadratic Form (20 points) In this exercise, you are asked to parallelize a quadratic form with UPC++. The quadratic form is given by \[ Q = v^T \cdot A \cdot w = \sum_{ij} v_i A_{ij} w_j \] where the matrix \( A \in \mathbb{R}^{n \times n} \) and \( v, w \in \mathbb{R}^n \). The entries of \( A, w, \) and \( v \) are given by: \[ A_{ij} = \frac{i + 2j}{n}, \quad v_i = 1 + \frac{2}{i + 0.5}, \quad w_i = 1 - \frac{i}{3} \] In the following you are provided with the serial program. ```c #include <stdio.h> #include <vector> #include "matrix.hpp" int main(int argc, char** argv) { int n = 1024; hpcse::matrix<double, hpcse::row_major> A(n, n); std::vector<double> v(n), w(n); for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) A(i, j) = (i + 2. * j) / n / n; for (int i=0; i<n; ++i) v[i] = 1. + 2. / (i + 0.5); for (int i=0; i<n; ++i) w[i] = 1. - i / 3. / n; double result = 0.; for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) result += v[i] * A(i, j) * w[j]; if(rankId==0) printf("Rank 0 - Total result \%lf.\n", result); upcxx::finalize(); } ``` a) Fill in the 20 missing gaps after the TODO: comments in the following parallel implementation. ```c++ #include <stdio.h> #include <vector> #include "matrix.hpp" #include <upcxx/upcxx.hpp> int main(int argc, char** argv) { upcxx::init(); int rankId = upcxx::rank_me(), rankCount = upcxx::rank_n(); int n = 1024, chunk = n / rankCount; // TODO: Initialize a global pointer with name globalResults _______________ globalResults; if(rankId==0) globalResults = ________________<double>( _______________); // TODO: Broadcast the adress of the global pointer to all ranks _______________ (_______________, 1, 0).wait(); hpcse::matrix<double, hpcse::row_major> local_A(chunk,n); // TODO: Define local_v and w as vectors of doubles of the correct size std::vector<double> local_v(____________), w(____________); for (int i=0; i<chunk; ++i) for (int j=0; j<n; ++j) local_A(i,j) = ((rankId * chunk + i) + 2.*j) / n / n; for (int i=0; i<chunk; ++i) // TODO: Fill in the entries of the local v vector local_v[i]=1.+2./( (________ * _______+ i ) +______); for (int i=0; i<n; ++i) w[i]=1.-i/3./n; double local_result = 0.; for (int i=0; i<chunk; ++i) for (int j=0; j<n; ++j) // TODO: Add the result to the local result __________ += __________ * local_A(i,j) * __________; // TODO: Update the globalResults pointer with the local result ______________(____________,globalResults + ____________, 1).wait(); upcxx::barrier(); if (rankId == 0){ double global_result = 0.; // TODO: Enable access of the global results pointer locally double* ______________ = globalResults.____________; for (int i = 0; i < rankCount; i++){ ``` b) What is the parallel tasking strategy used to parallelize the quadratic form? c) Comment on the load balance of each rank. Do you think the strategy employed is reasonable, or another strategy might be much more efficient for this task? d) The parallel implementation contains a barrier in line 43. Do you think this barrier is needed? Why? Question 5: GEMV on GPUs (20 points) The code below computes a matrix-vector product (GEMV) using an $N \times N$ matrix $$a = M b, \quad \text{where} \quad a_i = \sum_{j=0}^{N-1} M_{i,j} b_j. \quad (3)$$ ```cpp #include <vector> #define VECSIZE 512 void random_init(std::vector<float> & v, std::vector<float> & m) { // Some random initialization -- this could be anything for(std::size_t i = 0; i < v.size(); ++i) v[i] = i; for(std::size_t i = 0; i < m.size(); ++i) m[i] = i; } void gemv_cpu(float * a, float * m, float * b, unsigned int N) { for(unsigned int i = 0; i < N; ++i) for(unsigned int j = 0; j < N; ++j) a[i] += m[N*j+i] * b[j]; } int main() { unsigned int const N = VECSIZE; std::vector<float> a(N); std::vector<float> b(N); std::vector<float> matrix(N*N); random_init(b, matrix); // TODO replace gemv_cpu. // The code should perform the matrix-vector multiplication // on the GPU and store the result in the CPU vector 'a'. gemv_cpu(&a[0], &matrix[0], &b[0], N); return 0; } ``` a) Modify the host code such that the matrix-vector product is computed on the GPU. The final result should be available on the CPU. Write and call a CUDA kernel (gemv_gpu) for square matrices of arbitrary dimension $N$. Notes: - Show how the kernel is called in the `main()` function. - Checking CUDA for errors is not mandatory. Question 6: Advanced MPI: Communicators (30 points) The $N \times N$ Lehmer matrix $A$ is defined as $A_{i,j} = \min(i,j)/\max(i,j)$, where $i,j = 1,2,\ldots,N$. In this task you will compute the $L_\infty$ norm $$L_\infty = \max_i \left\{ \sum_j |A_{ij}| \right\}$$ (4) of this matrix distributed across a two dimensional grid of MPI processes. a) In the first part of this task you have to complete the following code snippet to initialize the matrix. You have 16 available MPI processes, and should divide the matrix in a $4 \times 4$ grid. You can assume that the size of the matrix $N$ is always divisible by 4. Modify the code between TODO_START and TODO_END in order to initialize the matrix using an MPI cartesian grid topology. ```c int size, rank, size_x, size_y; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); // TODO_START // assume that we have size = 16 ranks in total // then size_y = size_x = 4 size_x = 4; size_y = size / size_x; assert(N % size_x == 0 && N % size_y == 0); // local matrix size const int Nx_loc = N / size_x; const int Ny_loc = N / size_y; const int chunk_size = Nx_loc * Ny_loc; // compute coordinates (i,j) of rank int coord_x = rank / size_x; int coord_y = rank % size_x; // TODO_END double* matrix_loc = new double[chunk_size]; // initialize local matrix for (int i = 0; i < Ny_loc; ++i) for (int j = 0; j < Nx_loc; ++j) { // compute global indices int i_glo = coord_y * Ny_loc + i; int j_glo = coord_x * Nx_loc + j; matrix_loc[i* Nx_loc + j] = ``` ```c ``` b) A code snippet used for the computation of the infinity norm $L_\infty$ is provided below. Complete the code between the two TODO / END_TODO “brackets” in order to perform the reductions using row and column communicators. ```c++ // compute $L_\infty = \max_{col} (\sum_{row} (a_{ij}))$ double sums_loc[Ny_loc]; // local sum for(int i = 0; i < Ny_loc; ++i){ double sum = 0.0; for(int j = 0; j < Nx_loc; ++j) sum += std::abs( matrix_loc[i*Nx_loc + j] ); sums_loc[i] = sum; } double sums_row[Ny_loc]; // overall sums of rows // TODO: create row communicator and perform sum reduction // END_TODO double max_strip = 0.0; // local max of every sums_row for(int i = 0; i < Ny_loc; ++i) max_strip = std::max(max_strip, sums_row[i]); double L_inf = 0.0; // overall max // TODO: column communicator and max reduction with it // END_TODO if(rank == 0) std::cout << "L_inf norm: " << L_inf << std::endl; ```
{"Source-Url": "https://www.cse-lab.ethz.ch/wp-content/uploads/2019/05/practice_exam_2019_hpcse2.pdf", "len_cl100k_base": 5284, "olmocr-version": "0.1.50", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 37485, "total-output-tokens": 6246, "length": "2e12", "weborganizer": {"__label__adult": 0.0005660057067871094, "__label__art_design": 0.0007791519165039062, "__label__crime_law": 0.0007138252258300781, "__label__education_jobs": 0.03387451171875, "__label__entertainment": 0.0001964569091796875, "__label__fashion_beauty": 0.0002956390380859375, "__label__finance_business": 0.0008707046508789062, "__label__food_dining": 0.000965118408203125, "__label__games": 0.001946449279785156, "__label__hardware": 0.002597808837890625, "__label__health": 0.0008544921875, "__label__history": 0.0007638931274414062, "__label__home_hobbies": 0.0004401206970214844, "__label__industrial": 0.0013952255249023438, "__label__literature": 0.0006551742553710938, "__label__politics": 0.00051116943359375, "__label__religion": 0.0007462501525878906, "__label__science_tech": 0.1497802734375, "__label__social_life": 0.0004992485046386719, "__label__software": 0.01175689697265625, "__label__software_dev": 0.7880859375, "__label__sports_fitness": 0.0006098747253417969, "__label__transportation": 0.0009751319885253906, "__label__travel": 0.00034499168395996094}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 18123, 0.02926]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 18123, 0.26831]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 18123, 0.73839]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 1438, false], [1438, 2317, null], [2317, 4424, null], [4424, 5777, null], [5777, 6501, null], [6501, 6501, null], [6501, 7723, null], [7723, 9756, null], [9756, 10801, null], [10801, 11998, null], [11998, 13806, null], [13806, 14152, null], [14152, 15470, null], [15470, 15581, null], [15581, 17184, null], [17184, 18123, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 1438, true], [1438, 2317, null], [2317, 4424, null], [4424, 5777, null], [5777, 6501, null], [6501, 6501, null], [6501, 7723, null], [7723, 9756, null], [9756, 10801, null], [10801, 11998, null], [11998, 13806, null], [13806, 14152, null], [14152, 15470, null], [15470, 15581, null], [15581, 17184, null], [17184, 18123, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 18123, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 18123, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 18123, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 18123, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 18123, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 18123, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 18123, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 18123, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, true], [5000, 18123, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 18123, null]], "pdf_page_numbers": [[0, 0, 1], [0, 1438, 2], [1438, 2317, 3], [2317, 4424, 4], [4424, 5777, 5], [5777, 6501, 6], [6501, 6501, 7], [6501, 7723, 8], [7723, 9756, 9], [9756, 10801, 10], [10801, 11998, 11], [11998, 13806, 12], [13806, 14152, 13], [14152, 15470, 14], [15470, 15581, 15], [15581, 17184, 16], [17184, 18123, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 18123, 0.0]]}
olmocr_science_pdfs
2024-11-30
2024-11-30
f3e9c92fe5f0f7e83f48fabfaf8be505fb4e4009
[REMOVED]
{"Source-Url": "https://inria.hal.science/inria-00075678/document", "len_cl100k_base": 7144, "olmocr-version": "0.1.50", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 71867, "total-output-tokens": 8991, "length": "2e12", "weborganizer": {"__label__adult": 0.00040030479431152344, "__label__art_design": 0.0006818771362304688, "__label__crime_law": 0.0005621910095214844, "__label__education_jobs": 0.001941680908203125, "__label__entertainment": 0.000179290771484375, "__label__fashion_beauty": 0.00023281574249267575, "__label__finance_business": 0.0003955364227294922, "__label__food_dining": 0.0006170272827148438, "__label__games": 0.0007691383361816406, "__label__hardware": 0.0012035369873046875, "__label__health": 0.0014858245849609375, "__label__history": 0.0005340576171875, "__label__home_hobbies": 0.0002321004867553711, "__label__industrial": 0.0008587837219238281, "__label__literature": 0.000873565673828125, "__label__politics": 0.000514984130859375, "__label__religion": 0.000903606414794922, "__label__science_tech": 0.457275390625, "__label__social_life": 0.0002267360687255859, "__label__software": 0.0084075927734375, "__label__software_dev": 0.52001953125, "__label__sports_fitness": 0.0004684925079345703, "__label__transportation": 0.0008478164672851562, "__label__travel": 0.0002359151840209961}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 29628, 0.03412]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 29628, 0.60693]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 29628, 0.82845]], "google_gemma-3-12b-it_contains_pii": [[0, 920, false], [920, 3513, null], [3513, 7006, null], [7006, 10346, null], [10346, 10443, null], [10443, 13542, null], [13542, 16601, null], [16601, 18953, null], [18953, 21877, null], [21877, 24306, null], [24306, 26368, null], [26368, 29219, null], [29219, 29628, null]], "google_gemma-3-12b-it_is_public_document": [[0, 920, true], [920, 3513, null], [3513, 7006, null], [7006, 10346, null], [10346, 10443, null], [10443, 13542, null], [13542, 16601, null], [16601, 18953, null], [18953, 21877, null], [21877, 24306, null], [24306, 26368, null], [26368, 29219, null], [29219, 29628, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 29628, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 29628, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 29628, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 29628, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 29628, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 29628, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 29628, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 29628, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 29628, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 29628, null]], "pdf_page_numbers": [[0, 920, 1], [920, 3513, 2], [3513, 7006, 3], [7006, 10346, 4], [10346, 10443, 5], [10443, 13542, 6], [13542, 16601, 7], [16601, 18953, 8], [18953, 21877, 9], [21877, 24306, 10], [24306, 26368, 11], [26368, 29219, 12], [29219, 29628, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 29628, 0.0155]]}
olmocr_science_pdfs
2024-11-30
2024-11-30
51cf1449e94b233ed942203e40b0c792e0a0caf4
Design of Embedded Real-time Systems: Developing a Method for Practical Software Engineering Løvengreen, Hans Henrik; Ravn, Anders P.; Rischel, Hans Published in: IEEE International Conference on Computer Systems and Software Engineering Link to article, DOI: 10.1109/CMPEUR.1990.113649 Publication date: 1990 Document Version Publisher's PDF, also known as Version of record Link back to DTU Orbit Citation (APA): Design of embedded, real-time systems: Developing a method for practical software engineering Hans Henrik Løvengreen, Anders P. Ravn and Hans Rischel Department of Computer Science, Technical University of Denmark, DK-2800 Lyngby, Denmark Abstract The methodological issues and practical problems in development and industrial use of a theory-based design method for embedded, real-time systems are discussed. The method has been used for several years in a number of smaller industries, which develop both electronics and software for a professional market. The design is expressed in a notation for communicating sequential processes; while data types and operations are expressed in a notation built on mathematical set theory. Our main contribution has been to delineate an order in which to use the notations, a technique for deriving states and operations, and systematic checks of a design with respect to system requirements. 1 Introduction During the last decade theories of communicating processes have matured [6,13], and in the same period mathematically based notations for describing data and operations on data [2,10,19] have been used, though not widely accepted in software development. As researchers at a technical university we believe that use of these and presumably other theories is an important factor in making software creation a professional engineering discipline. Our beliefs were put to the test, when we in 1984 were asked by a company manufacturing high-quality electronic instruments whether we had any good ideas about "design tools" for embedded software systems. Their development teams were worried because 70% of their development costs went to software development, an area without professional standards. Given this challenge, we produced a one week course for engineers. The course was developed for an independent institution - the Danish Institute of Technology and we benefited from their experience with the field. The course was tuned over a period of one year by giving it to development engineers, and then turned over to the staff of the Institute of Technology. The material [18] is used in our own teaching. Although it is not a standard in any company we know of, it is used by a growing number of development teams. In early 1988 it was proposed to build a tool to support the method, and 8 companies agreed to make an initial payment without any guarantee for delivery. This tool is now developed by a consortium, and is to be completed this year. *This work has been partially supported by the Danish National Agency of Technology. Some of the results were published in [16]. 2 Methodology During a design activity a number of decisions are made and written down. The design is the produced document(s). The design method we want should provide: - A defined sequence of stages. In each stage the designer decides on a solution to a limited aspect of the problem or evaluate a solution. - Notations to write down decisions. - Checks, i.e. means of checking functionality and performance of a design against requirements. 2.1 Stages What to consider important aspects at a certain point of the design activity is not a question of notation or theory. Our delimitation of stages is based on pragmatics - good practice - within the application area. Fortunately we had a well-defined application area and could build on traditions, parts of which have been formulated in [5] and more specifically for the particular application area in [3]. The outcome was the following sequence of stages: 1. Interface Definition defining the events which form the interface to the system. 2. Event Structuring defining the events which form the interface to the system in terms of a partial, temporal ordering of events. 3. Program Structuring defining the relationship of output values to input values. 4. Functionality Check check of interface to entities. The main part of this paper concerns methodology, i.e. the issues in making a method, and our solutions to the problems of integrating functional and temporal constraints in a design, and how a design can be checked against requirements. These are contained in a section which outlines our methodological decisions and our theory base, and a section with a simplified case study to illustrate the techniques of the method. A final section discusses methodology, techniques and theory in a closer comparison with Jackson System Development (JSD) [8], which was an initial inspiration for us. The selected sequence of stages represent three major decisions: 1. To assume that the requirements are known by the designer. At the time we found no satisfactory theory on which to base an analysis of the requirements in order to produce a rigorous specification. The solution we offer is to proceed with the design and then check it against the requirements at later stages. 2. To suppress knowledge of functional relationships between event values until the (temporal) behaviour has been defined. This reflects that in the application domain, synchronization of events is a more intricate problem than design of the sequential operations on state variables. 3. To postpone performance considerations till the functionality is believed to be correct. Furthermore only to add input-output buffers or parallel algorithms if analysis indicates that it is required. By this line of action a considerable amount of unnecessary, complex mechanisms in the resulting design is avoided. ### 2.2 Notation Notation is needed to write down the design. Our main criteria for the syntax of the notation is brevity. This made us choose linear, textual notations as the designers main working tool. Diagrams to summarize a design can be derived from the text. The rationale for brevity is that a design document has to be rewritten many times and is read many more times. In order to make the method useful for real problems our goal was that the method should produce documents which are an order of magnitude smaller than the resulting high level programs. From completed projects we can estimate that we have achieved a factor of 6 – which we find acceptable. Another concern is that a notation should have a clear meaning in order to understand the design and its consequences, and be able to manipulate the design when checking it. We have tried to insist that the semantics of our notations should be rooted in accepted computer science theory. Thus we rely on the work of [11,4]. In analysis of time performance of concurrent processes, we did not find a satisfactory solution in the available theory. Here we had to rely on informal definitions. One point worth noticing is that the method as presented to the user does not include formal semantics for the notations. It is a responsibility of the producers of notations and not a concern of the users. ### 2.3 Checking functionality and performance A good design team is very intent on getting things right; but in a larger design misconceptions of informal requirements do occur. In the absence of a formal specification, we decided that checks on a design should be based on systematic manipulation of the formulae of the design document. The idea being that a software engineer, like any other engineer, checks a design by computing certain consequences of the design. ### 3 Application of the method In the following we describe the method in more detail to illustrate techniques for resolving design decisions within each stage. The description is based on a small, simplified case. The requirements for the case system are: - An embedded system used in an aviation control center (ACC) should have the following functions: - A radar is connected to the computer system. - The radar produces coordinates for observed objects (OO-coordinates), which are collected by the system and classified as positions for new or already known flying objects (FOs). The FOs together with identifying codes (FODs) are shown on a graphic display. The operator may enter informations for FOs and the information is then shown on the display alongside the FOs. The system should handle up to 500 FOs at the same time, refreshing the display two times a second. #### 3.1 Interface Definition The interface of the computer system to its environment, in which it is embedded, is characterized by the smallest units of atomic interaction, called events. Events are described by named event (classes), and are classified as input or output according to the flow of data. The domain (i.e. contents or abstract structure) of the data of each event is defined by a formula. Events define the observable interface to named entities in the environment. There is no concept of internal events. Internal events are avoided because they would reflect a premature functional decomposition. Premature, because the need for certain functions is only known when input-output relations are examined in the Program Structuring stage. For the ACC-system we arrive at the list shown on figure 1. Domains are defined by formulas using basic predefined domains (BOOLEAN, TOKEN, NUMBER, VOID) and rules for building composite domains (cartesian product, sequences, sets, etc.). Notations and concepts are borrowed from VDM [2], [10]. #### 3.2 Event Structuring The temporal behaviour of the system is described by the partial ordering of events. Ordered events or (event alternatives) constitute event sequences. Each event sequence is described by an event expression, using a regular-expression-like notation (sequencing '|', choice '[', repetition '*'). The maximum event sequences are written down and given names. For the ACC-system, we may arrive at the event sequences: - collection = O0* - displaying = ( Halfsec ; FOut * ) * - operation = F0info * In the check stage we shall discuss whether these in fact reflect the requirements. In the next stage (Program Structuring) each event sequence determines a sequential process. We use a set of maximal sequences in order to minimise dynamic synchronization among the resulting set of parallel processes. Minimal synchronization is attractive because it reduces the potential for deadlock, and makes analysis of timing less dependent on the scheduler. Besides, it is also most efficient for a multiprogramming implementation. The set of parallel processes reflect requirements for independent execution of event sequences – a parallelism which is better kept, because it can only be eliminated by use of interweaving choices, which usually leads to a combinatorial explosion of the control structure of the program. The notation does not contain a parallel operator, because nested parallelism would hinder the checks of functionality employed. This does, however, not seem to be any practical restriction on describing the required behaviour for embedded systems. 3.3 Program Structuring Event expressions are translated to an abstract program for a process following the well-known construction of a recognizing state machine for a regular grammar (or the JSP/JSD translation from syntactical structure to program structure, cf. [7], [8]). Given the control structure and the input-output operations, the required computations and internal states are derived and added to the abstract program by the following technique: Each output value and internal choice in the program is defined as the result of a named function. The input parameters to this function can be: The latest input value for an event – or a state, representing accumulated input values (when required by the computation). If a state is introduced, functions to accumulate input values are named and introduced in the abstract program immediately after the input operation. The domain of the function is the cartesian product of the state type and the event type, and the range is the state type. When the functions operating on a given state are defined on events of a single process, the state is local, otherise it is shared. Each shared state is placed in a state handler which is independent of the processes. The state handlers make the internal synchronization and the use of shared data among the processes explicit. The abstract program is completed by introducing device handlers for each entity. In the ACC-system there is only one output event FOout in the displaying process. It requires data from processes collection and operation. Consequently, a state handler FOTable is introduced and the abstract programs are extended with proper communication with the state handler (Device handlers have been left out, they are similar in structure to a state handler, but have no state). ``` PROCESS collection; LOOP radar ? oo; FOTable ! newobs(oo) END LOOP END PROCESS; PROCESS operation; LOOP operator ? foinfo; FOTable ! newinfo(foinfo) END LOOP END PROCESS; PROCESS displaying; LOOP clock ? Halfsec; FOTable ! initscan; LOOP WHEN FOTable ? done EXIT; FOTable ? getfo(fodsp); display ! FOout(fodsp); FOTable ! nextfo END LOOP END LOOP END PROCESS; ``` 3.4 Functionality Check We focus on interfaces to entities in the environment, which will allow us to check: 1. The protocol used for this entity, 2. Sets of events triggering outputs to the entity, and 3. Events used in deriving an output value For each entity a restricted event sequence is derived by removing (hiding) events from other entities. This is the protocol from the system to the entity. For the ACC, we would have, e.g. \[(\text{FOout}^*)\]^* for the display – which is the correct protocol (= \(\text{FOout}^*\)). For each output event the set of event sequences containing this event is considered, and all prefixes to the event are calculated. The set of input events in any prefix is called a trigger set of events for the output event. For the ACC we have \[ \text{Halfsec, FOout | FOout; FOout} \] i.e. FOout has the trigger set [Halfsec], which can be compared with the set of events used in deriving a value: \{00, FOinfo\} The operator might find it annoying that FOinfo does not imply FOout. If this is required, the design would have to be changed, e.g. the sequences displaying and operation merged to: \[(\text{Halfsec | FOinfo; FOout}^*)\]^* If a design contains more than one event that occur in different event sequences the design may contain a potential deadlock. We recommend that a proof of absence of deadlocks uses an ordering of such events as a basis. This can possibly lead to design changes. 3.5 Timing Analysis Real time constraints are found in most embedded systems. They are checked by estimating the time taken by certain sequences ("cycles") of the abstract programs. The calculations are illustrated in the following. These estimates are calculated under the assumption that events occur periodically. The execution time for an input operation, e.g. the 00-event is then estimated by: \[2 + V(00),\] where the 2 time-units is an estimate of internal processing time and \(V(00)\) is the \((\text{external})\) waiting time. For access to a handler, the delay caused by other processes has to be considered. Assuming queue discipline for accesses, we can estimate the time for e.g. access to FOtable as: \[2 + N,\] where \(N = 3\) is the number of processes having access. Calculation would then give a cycle time for the collector of: \(2 + V(00) + 6\). The requirements state 500/10 OOs per second. Which (assuming a time unit of 1 millisecond) would leave 50 - 8 time units. The collector is safe, provided that the interarrival time is greater than 8. If this cannot be guaranteed an input buffer would alleviate the problem. A similar calculation for displaying would (using 500 as an upper limit for the number of FOout's) give a cycle time \(V(\text{Halfsec}) + 500 + V(\text{FOout}) + 500 + 2 + 8\). Even if \(V(\text{FOout}) = 0\) this figure exceeds by far 500, so the cycle would not be completed before the next Halfsec event arrives. We conclude that the displaying process is going to be too slow because of an excessive number of FOout operations. These calculations are engineering calculations, and are not supported by theory. Some initial investigations suggest, however, that they can be supported by the model of timed CSP developed by Reed and Roscoe [17]. 3.6 Functional Decomposition This stage uses well-known, informal techniques for functional and modular decomposition (cf. [15]) to refine operations and states of the abstract program. 4 Discussion Those experiences with the method which we consider of general interest for developers of methods and theory, and for software developers in general are summarized in the following. In order to make certain points, we shall compare certain stages and techniques with similar stages in JSD, which we consider to be one of the better of the widely used commercial methods. 4.1 Notations A positive reaction from the users of the method has been that the documentation is concise. To quantify that statement, we give the following figures for the documentation of the software for an instrumentation system that monitors and analyses vibrations in large machinery: <table> <thead> <tr> <th>Stage</th> <th>Pages</th> </tr> </thead> <tbody> <tr> <td>Interface definition</td> <td>9</td> </tr> <tr> <td>Event sequences</td> <td>7</td> </tr> <tr> <td>Abstract programs</td> <td>38</td> </tr> <tr> <td>Total</td> <td>56</td> </tr> </tbody> </table> The program source texts are approximately 350 pages. The manager of the team had previously completed a project of similar size. In that project they used diagrams to document their data and function design. This design document amounted to well over 400 pages, and of course it was not maintained during development (The method used was not JSD). Our conclusion is that graphical notations might be easy to learn, but their use places a superfluous burden on a professional development team. 4.2 Theory Apart from our belief that an engineering discipline should be based on suitable mathematical theories, a theory base have practical implications: - Use of data types for events and in signatures for operations eliminate introduction of vaguely defined 'actions'. In JSD and similar methods 'actions' and 'operations' are uninterpreted symbols – inexperienced or overworked developers may be tempted to hide problems in perhaps uninterpretable symbols. - Use of process algebra allows systematic checks of a design by calculations. There are two points where further development of theory is urgently needed: - Real time models. There is considerable activity in this area, but the models and theories have to be based on realistic assumptions about the problem domain. We can recommend the discussion in section III of [14]. - A basis for specification that integrates behavioural specification, state value specification of operations, and timing specifications. A formal specification language would allow the checks on requirements to be formalized. 4.3 Interface definition JSD has starting point in real-world entities and analyzes and model their relevant actions, while we start the design process from the interface to the system and defines it in terms of events and data-domains. We certainly agree on the relevance of modelling in requirements engineering, but we do not believe that it is possible to obtain useful generality for a design by modelling "the world" – at least not in the considered problem area. The modelling gives the conceptual framework, but the functional requirements defines the part thereof to be implemented in the program. A remark which we have heard from several users, is that it is hard to get started. It is a nontrivial task to select events at the proper level of abstraction. In one case, which lead to some dismay, the designers started out very systematically with wire-level signals, and they were unable to get meaningful event sequences out of that. Our diagnosis was that the group had started from the wrong documents. They had used the specification of prototype hardware in place of the functional specification (the requirements) for the product. 4.4 Event sequences The technique of using maximal event sequences leads to robust and efficient implementations of a design. Getting nice event sequences takes some time; but there has not been complaints about that. Most engineers like to discuss the architecture of a system in terms of its event structures. In contrast JSD first derives a set of processes for the behaviour of real-world entities – in a later step transformations are performed in order to get a sequential program. The behaviour of the developed system versus the requirements plays a secondary role in the JSD development process. 4.5 Derivation of computations Deriving computations from the requirements for output values (and for internal choices) is also accepted as a sound practice by most designers. Some, however, had to unlearn approaches learnt in database design, where the aim is to provide "useful" general functions. We take the stand that any wanted generality is part of the requirements. The design is a place to introduce unstated requirements. 4.6 Shared states A common problem in existing real-time software is missing discipline in the access to shared data. The symptoms are lack of data integrity (no control of critical regions) or deadlock (caused by waits for access). State handlers are a clean way of obtaining integrity of shared data and at the same time identifying the entire inter-process communication. 5 Future developments We are presently advising a consortium which produces a CASE-tool for the method. In order to have a general framework in which to define notations both syntactically and semantically, we have advised them to use the LOTOS [12] notation with two exceptions: 1. Iteration ("*" ) is used instead of tail recursion. This leads to introduction of notation for a state of a process. These changes make the notation considerable more compact. Furthermore we believe, though the details have not yet been worked out, that these constructs can be expanded into proper LOTOS. The motives for using LOTOS as a base line are: 1. It assures us that we have consistent syntax and semantics 2. It allows this CASE-tool to use LOTOS-tools, e.g. simulators. We are also enganged in the ProCoS project (Provably Correct Systems, Esprit BRA project 3104, cf. [1]). The aim of ProCoS is to contribute to the science and engineering of constructing mathematically provably correct systems—in particular for safety critical applications. The current activities in ProCoS form in several ways a continuation (on a firm theory basis) of the work reported in this paper. References
{"Source-Url": "http://orbit.dtu.dk/files/4493085/L%C3%B8vengren.pdf", "len_cl100k_base": 4768, "olmocr-version": "0.1.53", "pdf-total-pages": 7, "total-fallback-pages": 0, "total-input-tokens": 22966, "total-output-tokens": 6116, "length": "2e12", "weborganizer": {"__label__adult": 0.000507354736328125, "__label__art_design": 0.0006985664367675781, "__label__crime_law": 0.0004546642303466797, "__label__education_jobs": 0.0007624626159667969, "__label__entertainment": 8.171796798706055e-05, "__label__fashion_beauty": 0.00022101402282714844, "__label__finance_business": 0.00030303001403808594, "__label__food_dining": 0.0004887580871582031, "__label__games": 0.0006899833679199219, "__label__hardware": 0.004150390625, "__label__health": 0.0007424354553222656, "__label__history": 0.0003936290740966797, "__label__home_hobbies": 0.00016570091247558594, "__label__industrial": 0.0010251998901367188, "__label__literature": 0.0002722740173339844, "__label__politics": 0.00035572052001953125, "__label__religion": 0.0007753372192382812, "__label__science_tech": 0.07281494140625, "__label__social_life": 8.398294448852539e-05, "__label__software": 0.00443267822265625, "__label__software_dev": 0.908203125, "__label__sports_fitness": 0.0004730224609375, "__label__transportation": 0.0013990402221679688, "__label__travel": 0.0002770423889160156}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 25800, 0.03531]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 25800, 0.43437]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 25800, 0.92659]], "google_gemma-3-12b-it_contains_pii": [[0, 701, false], [701, 5248, null], [5248, 10621, null], [10621, 13829, null], [13829, 18432, null], [18432, 23302, null], [23302, 25800, null]], "google_gemma-3-12b-it_is_public_document": [[0, 701, true], [701, 5248, null], [5248, 10621, null], [10621, 13829, null], [13829, 18432, null], [18432, 23302, null], [23302, 25800, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 25800, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 25800, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 25800, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 25800, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 25800, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 25800, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 25800, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 25800, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 25800, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 25800, null]], "pdf_page_numbers": [[0, 701, 1], [701, 5248, 2], [5248, 10621, 3], [10621, 13829, 4], [13829, 18432, 5], [18432, 23302, 6], [23302, 25800, 7]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 25800, 0.03261]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
f04b8cd3f68bea116dcb33b9c4fec34253a58927
Abstract Enterprises express the concepts of their electronic business-to-business (B2B) communication in individual ontology-like schemas. Collaborations require merging schemas’ common concepts into Business Entities (BEs) in a Canonical Data Model (CDM). Although consistent, automatic schema merging is state of the art, the task of labeling the BEs with descriptive, yet short and unique names, remains. Our approach first derives a heuristically ranked list of candidate labels for each BE locally from the names and descriptions of the underlying concepts. Second, we use constraint satisfaction to assign a semantically unique name to each BE that optimally distinguishes it from the other BEs. Our system’s labels outperform previous work in their description of BE content and in their discrimination between similar BEs. In a task-based evaluation, business experts estimate that our approach can save about 12% of B2B integration effort compared to previous work and about 49% in total. 1 Introduction Businesses often exchange electronic messages like Purchase Orders, which contain compatible concepts (e.g., shipment dates and delivery address) that are however arranged and named differently in each company’s ontology-like messaging standards (schemas). For instance, the two exemplary schemas shown on the left-hand side of Fig. 1 both speak about the delivery date, but use different phrases – “Current Scheduled Delivery” (node 10) and “Delivery Date/Time, estimated” (node 16). Misinterpretation is likely and may lead to delays and other financial losses. The solution is to align the participating enterprises’ schemas and find new, unique and appropriate (natural-language) names for the contained concepts, for all participants to use. A solution for the alignment task has been proposed in Lemcke et al. (2012): They create a CDM made up of BEs which can be visualised as clusters of equivalent nodes of the original schemas as visualized on the right-hand side of Fig. 1. This is similar to Ontology Merging (Shvaiko and Euzenat, 2013) except that the relation between the nodes is “part-of” and has to be maintained consistently. As described in Lemcke et al. (2012), the only reliable source for correspondences between the schema nodes are the mappings business experts create when integrating two systems. Analysing the mappings shows that, for example, the delivery date is expressed in schema 1 by the value of node 8 in the “Date time” structure, together with the “Current scheduled delivery” qualifier (node 10). In schema 2, this corresponds to the combination of nodes 16 and 17. Therefore, BE 1 containing nodes 8, 10, 16 and 17 is created. In this paper, we tackle the problem of automatically finding short, descriptive and unique natural-language labels for each of the BEs to replace the symbolic names F or I, based on the names and descriptions provided for each of the original nodes (see Table 1). The desired result are labels like **Shipment Date and Delivery Date.** The labelling task is complicated by the limited vocabulary of the description data, since controlled terms from a strictly defined domain are used. For example, both BE description sets in Table 1 contain the words *date*, *shipment* or *scheduled*. Since we see fewer distinct content words than BEs, labels must be phrases. Also, we have to balance the need for short labels with specificity and discrimination amongst semantically similar BEs. Further, reusing the same node defined by some schema template in different contexts is very common in B2B integration. For example, the date and time structures of node 4 and 8 in Table 1 can be interpreted either as a shipment or a delivery date, depending on whether they appear in conjunction with the qualifier node 6 (in BE F) or 10 (in BE I). This means that words and concepts introduced by different usage contexts of nodes are commonly used in BE descriptions. Also, free text nodes like node 13 are commonly misused to store e.g. the shipment date. Both factors result in noise in the form of misleading words in the accumulated descriptions of a BE. We clarify our assumptions about what defines a good label in Section 2. Based on these rules, our approach for labelling the CDM is described in Section 3. Note that the approach is completely domain- and mostly task-agnostic and could be used in other settings where short texts are involved. We present evaluation results with respect to label quality and time saved in Section 4. ### 2 Desiderata for Labels An optimal labelling is reached when the following assumptions are true: Labels are natural language words or phrases that are: **Descriptive** The label should state the concept of the BEs. Therefore, the concepts which are most frequently present in the names and descriptions of a BE are good label candidates. **Discriminative** The label should state the distinguishing property of the BE. Therefore, the best candidates for labelling a BE are concepts which are frequently present in its names and descriptions, but not in the overall CDM. **Short** The label should balance shortness (by Occam’s razor) and specificity (to achieve uniqueness and discriminate between BEs). Semantically Unique Two BEs must have non- synonymous labels. As the CDM has reference character for business experts, it is necessary to assign unique labels for unique BEs. 3 Labelling Business Entities We use the approach developed in-house by (Diet- rich et al., 2010). They introduce the tool pipeline shown in Fig. 2 to solve the labelling problem for the CDM. The Dietrich et al. approach generates label candidates from the node names and descrip- tions for each BE and validates them against a domain lexicon and search results in three search engines. However, due to data sparseness in both types of resources, correct label candidates are of- ten erroneously rejected. Further, the approach conflates different senses of the same word. We address both of these issues below. We also use a new strategy for labelling the CDM: First, we generate plausible label candidates for each BE and rank them heuristically. Second, we optimize globally, picking the set of labels for the CDM with the best overall ranks. This is simi- lar to the global inference strategy, which recently has become increasingly popular (cf. work starting with Roth and Yih (2004)). We now describe how we use and extend the tools from Fig. 2 to create labels with the proper- ties defined in Section 2. Note that for both BE names and (possibly noisy) descriptions, process- ing is the same. We do, however, give more weight to the candidates extracted from the (cleaner) BE names. From here on, we use \(d_x\) as a placeholder to refer interchangeably to the names or the de- scriptions of the specific BE \(be_x\). Descriptive labels For descriptive labels, we need to find the most representative concept in a BE \(be_x\). One strategy could be to look for domain terms which can be assumed to be rel- evant, but the Dietrich et al. results indicate that existing resources are too sparse for this. There- dfore, we consider every term in the BE names and descriptions. To be agnostic of synonyms, our adapted synonym finder first extracts all possible meanings of each term \(t\) by retrieving the synsets \(S_t = \{s_1, s_2, \ldots, s_n\}\) from WordNet (Fellbaum, 1998). Further, \(S_t\) is extended by the synsets of derivationally related forms of \(t\) as returned by WordNet. To increases the possibility of overlaps of the synsets of different, related terms, es- cially when used as different POS. The frequency of the synset \(s\) among the synsets of all terms of the names and descriptions \(d_x\) of the BE \(be_x\), de- noted as \(f(s, d_x)\), indicates the relevance of \(s\) for describing \(be_x\). We normalize the frequency over all \(be_x\’s\) synsets \(S_{d_x} = \bigcup_{t \in d_x} S_t\) as in the term frequency (TF) approach by \[ \text{tf}(s, d_x) = \frac{f(s, d_x)}{\max \{f(s, d_x) : s \in S_{d_x}\}}. \] In contrast to solely TF, the full TF/IDF ap- proach did not yield satisfactory results: We found that since a BE’s core concept may frequently ap- pear in other BEs’ descriptions due to re-use of nodes in different contexts and the misuse of free- text nodes, the IDF term was commonly very small and erroneously filtered out the true core concept. For the final creation of labels, we express a synset \(s\) by the most frequent term \(t\) from \(d_x\) with \(s \in S_t\) to adapt to the common technical terms of the domain. Discriminative labels As there are fewer inter- esting words than BEs, word selection by TF does not produce unique labels, and phrases are needed. We use the description \textit{The field represents the contract date representing the current scheduled delivery} to demonstrate how these are generated. First, nouns, verbs, adjectives and adverbs are iden- tified as interesting words to build phrases. As an alternative design decision, each interesting term is then represented by its most frequent WordNet synset as described before and illustrated in Tab- le 2. However, another alternative could be for example representing each interesting term by its first common hyperonym. Second, our adapted phrase generator passes a sliding window over the text and considers all synset sequences in the window as possible can- dates. With this window which was chosen heuris- tically, we both ensure some local coherence be- tween the candidates and limit the numbers of possible combinations. For our running exam- ple we use a sliding window of size 4. We compute the relative distance of the synsets based on their position in the sentence. (E.g., \textit{delivery} at position 11 and \textit{current} at position 9 are two units apart.) Figure 2: Tool pipeline for generating BE label candidates <table> <thead> <tr> <th>Token</th> <th>field</th> <th>represents</th> <th>contract</th> <th>date</th> <th>representing</th> <th>current</th> <th>scheduled</th> <th>delivery</th> </tr> </thead> <tbody> <tr> <td>Position</td> <td>2</td> <td>3</td> <td>5</td> <td>6</td> <td>7</td> <td>9</td> <td>10</td> <td>11</td> </tr> </tbody> </table> POS N V N N V A A N Synset S1 S2 S3 S4 S2 S5 S6 S7 Table 2: Representation of each term as position in sentence, POS, and most frequent synset Tag Pattern | Example ---|--- AN | Scheduled Delivery NN | Reference Shipment AAN | Current Scheduled Delivery ANN | Added Tax Delivery NAN | Reference Scheduled Delivery NNN | Date Time Shipment NPN | Reference for Shipment Table 3: Justeson and Katz (1995) phrase patterns The lower the relative distance, the more likely the phrase is to be useful, because it is present (almost) verbatim in the input. Third, for avoiding redundancy, we filter out synset sequences that contain duplicate synsets. Fourth, our adapted formatter chooses the most relevant word from the input sequences for each combination of synset and POS tag. The resulting phrase has to correspond to the POS tag sequences proposed in Justeson and Katz (1995) shown in Table 3. The input sequence in Table 2 yields phrases like field representation, contract date representation, scheduled delivery, current scheduled delivery and current scheduled. Current scheduled matches no pattern in Table 3, so it is changed to current schedule. We estimate the quality of the phrases heuristically instead of checking against lexical resources. We use the length \( le = |p| \) of the phrase \( p \) to rank more specific phrases higher. We also consider the average frequency \[ \frac{1}{wf} = \frac{1}{\sum_{t \in p} \frac{tf(t, d_x)}{le}} \] of the words of the phrase \( p \) in the names or descriptions of the BE \( b_{e_x} \), favouring labels with more descriptive terms. Short labels The previous step prefers relevant, but longer labels. We balance this preference with two measures that discourage long phrases: We consider the reciprocal of the average distance \( di^T = \frac{le - 1}{di} \) of the words in a phrase, where \( di \) is the distance between the first and the last word of the compound in the original text, favouring short phrases taken literally from the text. The frequency \( pf = \frac{tf(p, d_x)}{le} \) of the phrase in the names or descriptions of \( b_{e_x} \) has a similar effect because longer phrases tend to be less frequent. The final ranking of label candidates uses all four measures (length, average word frequency, inverse average word distance, and phrase frequency), each normalized over all candidates. All weights are equal, except that we weight the measures for extracting phrases from the BE names twice as high as the measures for extracting from BE descriptions, since the names are defined by experts and contain less noise than was observed in the BE descriptions. This decision was supported by our analysis of results on the development set. Semantically unique labels. Finally, one of the locally generated phrases needs to be assigned to each BE, but not two BEs can get synonym labels. To solve this problem in a globally optimal way, we formulate the constraints and variables of a Constraint Satisfaction Problem (CSP). The CSP is solved by Choco 2.1.3 (choco Team, 2010), a very general constraint satisfaction framework. Each BE be\(_x\) is represented by the variables label (candidate phrases), synsets (synset sequence for each phrase) and rank (rank in terms of our heuristics). A set of feasible tuples constraints ensures that label, synsets and rank are internally consistent for each BE be\(_x\). Another two sets of all-different constraints ensure uniqueness among the values assigned to the label and respectively to the synsets variables, i.e., labels have to be unique both in terms of tokens and of concept. The system maximizes the formula \(\sum x \text{rank}_x\). The complexity of the CSP depends most strongly on the size of the CDM, i.e., number \(b\) of BEs, and the window size \(w\) when generating phrases. The number of phrases, which make up the domains of the label variables, depends exponentially on the window size and linearly on the length of names and descriptions. The CSP itself has exponentially many solutions depending on the number of BEs. So, the total worst-case complexity is \(O(2^{wb})\). In our case, with a \(w = 5\) and \(b = 25\) the computational time is approximately 3 hours and with the same \(w\) but \(b = 38\) it is approximately 6.45 hours. 4 Evaluation For evaluation, we compare to the baseline approach by Dietrich et al. (2010). We use 38 BEs that were unseen during the development of the tool pipeline. This data has the disadvantage of being proprietary, but there is not, to our knowledge, a comparable freely-available data set. Our first objective is to establish the need for enforcing unique labels. Recall that our approach is designed to never assign the same label to different BEs. We automatically analysed the names proposed by the baseline approach, which assigns non-unique labels to 21% of the BEs. This is not acceptable in practice, since the point of the CDM is to allow unambiguous communication. ### Table 4: Descriptive and discriminative labels: Percentage of correct label-description pairings for our and the Baseline (BL) approach <table> <thead> <tr> <th></th> <th>Our Correct</th> <th>BL Correct</th> </tr> </thead> <tbody> <tr> <td>Incorrect</td> <td>29.7%</td> <td>39.8%</td> </tr> </tbody> </table> The second part of our evaluation focuses on the descriptive and discriminative properties of our labels. This evaluation was done by ten novice users (due to the limited availability of experts). They assessed whether the label assigned to a BE correctly reflects its distinguishing features. In the survey, the participants answered 20 questions (ten for each approach). The participants saw the top-ranked BE label as generated by one of the systems, as well as the description of the input BE and the descriptions of semantically similar distractor BEs. If the participant chose the input description as best matching the label, we took that to mean that the label correctly distinguishes the semantics of the BE from the others. The results of this survey are shown in Table 4. For the baseline approach, the participants chose the correct description for the label in 60.2% of the time, as opposed to 70.3% of the time for our approach. A \(X^2\)-test with a null hypothesis of chance assignment of correct and incorrect labels is significant at the 0.05 level; we conclude that our labels are more discriminative among BEs and describe BE content better than the labels returned by the baseline approach. Finally, we present a task-based evaluation that was carried out with the help of B2B experts. Our objective here is to show that our system is useful in a real-world setting to the very group of people who are its intended users. Nine B2B experts estimated how much time and effort they would have saved creating the labels with the help of the output data of the approaches. The survey used five BEs and had three kinds of questions: First, the participants were asked to create a label for a BE by hand, based on the names and descriptions available for it. These names and descriptions were also input to the systems. Second, based on their manually created label, the participants estimated how much effort they could have saved in step 1 if they had had available Table 5: Task-based evaluation of label usefulness to experts: Result for evaluating effort saved (left) and label rank according to usefulness (right) of our and the baseline (BL) approach <table> <thead> <tr> <th>Effort Saved</th> <th>Rank</th> <th>Our</th> <th>BL</th> </tr> </thead> <tbody> <tr> <td>≥ 90%</td> <td>1</td> <td>36</td> <td>9</td> </tr> <tr> <td>90-75%</td> <td>2</td> <td>26</td> <td>19</td> </tr> <tr> <td>75-50%</td> <td>3</td> <td>21</td> <td>24</td> </tr> <tr> <td>50-30%</td> <td>4</td> <td>18</td> <td>27</td> </tr> <tr> <td>≤ 30%</td> <td>5</td> <td>19</td> <td>26</td> </tr> <tr> <td>Avg (%)</td> <td>6</td> <td>15</td> <td>31</td> </tr> </tbody> </table> The participants chose one of five levels: more than 90% (when the label in step 1 is almost equal to the proposed candidates), between 90 and 75%, between 75 and 50%, between 50 and 30% and less than 30% (when the label is completely different). Third, six model labels, three from each approach, had to be ranked in order of their usefulness for creating their label. Table 5 shows the result for the effort-saved estimation on the left-hand side. We computed the average amount of effort saved by using the mid-point for each of the categories, e.g. 82.5 for the 90-75% category. Our approach saved 12.1 percentage points more expert effort than the baseline, and 49.2% of total effort. This corresponds to about four working hours (out of an eight-hour day). The baseline approach would allow the experts to save about three working hours, so using our approach saves an additional hour of (highly-qualified and highly-compensated) expert times. The right-hand side of Table 5 shows the summarized results from the ranking task. Numerically, the experts ranked our proposals on average one rank higher than the baseline proposals. \(X^2\)-tests with the null hypothesis of an equal number of total observations in each rank found that the numerical differences for rank 1 and 6 are statistically significant at the 0.05 level. Overall, these results again illustrate that proposals given by our approach will be more useful for the experts in label creation than the baseline system. 5 Related Work This paper is concerned with labelling a merged ontology in an unsupervised way given the node names and descriptions from the source ontologies. To our knowledge, this task is not commonly treated in the ontology merging literature. In computational linguistics, our task is most comparable to the problem of assigning keywords or index terms that best describe a document’s content (see, e.g., Kim et al. (2010)). However, our data is shorter, more repetitive and more ambiguous than running text from scientific publications or newspapers, and we have to obey the additional constraint of finding unique labels. The labelling task is also somewhat reminiscent of the task of finding appropriate names for FrameNet framesets in the SemFinder system (Green and Dorr, 2004). Green and Dorr use WordNet synsets and glosses as their input data and rely heavily on WordNet’s tree structure. This strategy is however infeasible for highly domain-specific texts like ours. 6 Conclusions This paper proposed a method for labelling the BEs of a CDM by analysing the aggregated names and descriptions underlying the BEs, assuming that appropriate labels should be descriptive, discriminative, short and semantically unique. Our strategy is very general and can be applied to other tasks inside and outside the ontology labelling domain. Several properties of the B2B domain challenged our implementation: Re-use and misuse of structural elements caused notable noise in the input data and the limited vocabulary of controlled terms means that the same relevant terms and concepts appear in multiple BEs. We therefore applied the strategy of generating phrases as label candidates locally and then picking globally optimal label candidates. This strategy ensures unique labels, which are a core requirement in our domain. Our evaluation showed that our labels are more descriptive of BE content and discriminate better among similar BEs than the baseline. A task-based evaluation with B2B experts, who are the intended users of the system, suggests potential effort savings in this crucial task of B2B integration of almost 50%, corresponding to four working hours out of an eight-hour work day. References
{"Source-Url": "https://nlpado.de/~ulrike/papers/OrtizLemckePado14.pdf", "len_cl100k_base": 5066, "olmocr-version": "0.1.50", "pdf-total-pages": 7, "total-fallback-pages": 0, "total-input-tokens": 21272, "total-output-tokens": 5819, "length": "2e12", "weborganizer": {"__label__adult": 0.0004124641418457031, "__label__art_design": 0.0010423660278320312, "__label__crime_law": 0.0009317398071289062, "__label__education_jobs": 0.004638671875, "__label__entertainment": 0.0003514289855957031, "__label__fashion_beauty": 0.0003418922424316406, "__label__finance_business": 0.00829315185546875, "__label__food_dining": 0.0004854202270507813, "__label__games": 0.001056671142578125, "__label__hardware": 0.000988006591796875, "__label__health": 0.0008130073547363281, "__label__history": 0.0005846023559570312, "__label__home_hobbies": 0.0001996755599975586, "__label__industrial": 0.0010271072387695312, "__label__literature": 0.0024394989013671875, "__label__politics": 0.0007982254028320312, "__label__religion": 0.0005898475646972656, "__label__science_tech": 0.398681640625, "__label__social_life": 0.00031304359436035156, "__label__software": 0.1156005859375, "__label__software_dev": 0.458984375, "__label__sports_fitness": 0.0002524852752685547, "__label__transportation": 0.0009160041809082032, "__label__travel": 0.0002856254577636719}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 23221, 0.02056]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 23221, 0.35243]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 23221, 0.90849]], "google_gemma-3-12b-it_contains_pii": [[0, 2987, false], [2987, 5237, null], [5237, 9837, null], [9837, 12913, null], [12913, 17429, null], [17429, 21602, null], [21602, 23221, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2987, true], [2987, 5237, null], [5237, 9837, null], [9837, 12913, null], [12913, 17429, null], [17429, 21602, null], [21602, 23221, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 23221, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 23221, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 23221, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 23221, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 23221, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 23221, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 23221, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 23221, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 23221, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 23221, null]], "pdf_page_numbers": [[0, 2987, 1], [2987, 5237, 2], [5237, 9837, 3], [9837, 12913, 4], [12913, 17429, 5], [17429, 21602, 6], [21602, 23221, 7]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 23221, 0.07527]]}
olmocr_science_pdfs
2024-11-28
2024-11-28
e677ab034c9cb7e484cd7cedeeaaa4641f339b3b
Distributed Interactive Applications Diego Montenegro Andrew Park Bobby Vellanki What is a Distributed Interactive Application (DIA)? “A DIA allows a group of users connected via a network to interact synchronously with a shared application state.” “DIS is the name of a family of protocols used to exchange information about a virtual environment among hosts in a distributed system that are simulating the behavior of objects in that environment. It was developed by the US department of defense to implement systems for military training, rehearsal, and other purposes.” Properties of the Black Box Consistent Scalable Secure Robust Available Real-Time Consistency Every entity must have the same view of the global state as every other entity in the entire network Scalability An increase in users does not affect the efficiency of the network Security No node can have advantage over another node Robustness A failure of any participant has no effect on any other participant Availability The network is perpetually accessible Real-Time Processes are delivered no later than the time needed for effective control Properties of the Black Box Consistent Scalable Secure Robust Available Real-Time Consistency - Bucket Synchronization - Dead Reckoning - Algorithms Bucket Synchronization Mechanism - All calculations are delayed until the end of each cycle - The bucket cycles are typically 100ms (bucket frequency) - Bucket frequency is set as a constant value which is equal to the rate that a human vision perceives smooth motion. Consistency • Bucket Synchronization ➢ Dead Reckoning • Algorithms Dead Reckoning What is Dead Reckoning? • If a packet is lost or received too late, dead reckoning is used to estimate the “most probable” state or position of the object. • The success of Dead Reckoning is based on the intelligence of the algorithm design • There is inconsistency between the actual and expected states. Dead Reckoning Why is Dead reckoning needed? Example for Delay-Induced Inconsistency Dead Reckoning Immediate Convergence vs Time-Phased Convergence ``` Convergence with Updated Location ``` Dead Reckoning Linear Convergence vs Curve-Fitting Convergence Convergence with Predicted Location Consistency • Bucket Synchronization • Dead Reckoning ➢ Algorithms Dead Reckoning Algorithms 1. Simple scheme - Use previous packet 2. Function of the previous packet’s position, velocity of the object, and the elapsed time. 3. Extrapolation 4. Pre-Reckoning - Compatibility with Bucket Synchronization Properties of the Black Box - Consistent - Scalable - Secure - Robust - Available - Real-Time Scalability Centralized vs. Distributed Centralized Pros: • Simplified administration • Ease of maintenance • Ease of locating resources Cons: • Difficult to scale • High cost of ownership • Little or no redundancy • Single point of failure Distributed Pros: • Highly extensible and scalable • Highly fault tolerant • Dynamic addition of new resources Cons: • Difficulty in synchronizing data and state • Scalability overhead can be large • Extremely difficult to manage all resources Properties of the Black Box - Consistent - Scalable - Secure - Robust - Available - Real-Time Security • Distributed applications are more prone to cheating than centralized due to the fact that there is no authority supervising the actions of the users • Security bears a trade-off of efficiency vs. fairness Cheating - Suppress-correct cheat: Host gains advantage by purposefully dropping update messages. - Look ahead cheat: Players make decisions after receiving all updates from participating players. Cheating Solutions A) Lockstep Protocol: No host receives the state of another host before the game rules permit 1. Player decides but does not announce its turn \( t + 1 \) 2. Each player announces a Cryptographically secure one-way hash of its decision as a commitment. 3. After all players have announced their commitments, players reveal their decisions. 4. Each host can verify revealed decisions by comparing hashes. Cheating Solutions B) Asynchronous Synchronization: Relaxes the requirements of lockstep synchronization by decentralizing the game clock 1. Player determines its decision for the turn and announces the commitment of the decision to all players. 2. Commitments that are one frame past the last revealed frame of a remote player are accepted. 3. Before revealing its commitment, the local player must determine which remote players it is waiting for. Cheating Solutions B) Asynchronous Synchronization Continued: 4. A remote player is not in the wait state only if there is no intersection with the SOI dilated from the last revealed frame of the remote player. 5. The SOI is calculated using the base radius of the last known position plus a delta radius. B) Asynchronous Synchronization Continued: 6. Finally, if no remote hosts are in the wait state, the local host reveals its state turn for turn $t$, updates its local entity model of each other player with their last known state, including the remote hosts last known time frame and advances to the next turn. Cheating Solutions C) AS with Packet Loss: players can skip missing packets and accept new, out-of-order packets from other players when the missing packets represent state outside a SOI intersection. Missing packets that represent intersection of SOI cannot be dropped or skipped. AS represents a performance advantage over lockstep, rather than contact every player every turn, players need only contact players that have SOI intersection. Downside of all previous protocols: - Performance Penalty: All nodes must slow down to the speed of the slowest user. Properties of the Black Box Consistent Scalable Secure Robust Available Real-Time Robustness - Users can join or leave the network at any time, without having any negative effects on other nodes. - A failure of any participant has no affect on any other participant. - Participants joining an ongoing session have missed the data that has previously been exchanged by the other session member. What to do? Late Join Algorithms Late Join Algorithms • Necessary algorithms to distribute the current state of the session to new users. • Two Approaches: Transport protocol. Application based Transport Protocol: Request *ALL* previous session information (rollback) Pros: • Robust • Application Independent Cons: • Inefficient • The state of some applications can’t be reconstructed. (Networked action games) Late Join (cont.) Application based: The late join algorithm varies by the type of application. (e.g.- networked games vs. whiteboard) • Efficient – Only need the current state of the session • Lack of reusability Setup for Late Join: 1. New node must determine the priority of the subcomponents of the state (e.g. – You want to transfer the most recent page for a whiteboard) 2. New node (client) needs to select one or more of the existing nodes as a server. 3. Information must be transmitted to the new node. Late Join (cont.) - Late join policy differs based on the application - Different proposed policies: 1. No late join 2. Immediate late join 3. Event-triggered late join 4. Network-capacity-oriented Late Join (cont.) Distribution of Data: 1. **One network group** (base group) – Broadcast the state to the whole group. Unnecessary packets get sent to existing nodes. (Beneficial if the ratio of late joins to the existing users is very high) 2. **Two network groups** – All late join clients join the client group. 3. **Three network groups** – In addition to the two network groups, the late join servers form an additional multicast group. Problems: Who should be selected to act as a server?? Properties of the Black Box - Consistent - Scalable - Secure - Robust - Available - Real-Time Availability - Like robustness, no single point of failure will affect the entire network. - This is one of the major advantages over centralized networks, where the failure of the server causes the entire network to fail. - If a node fails, it gets disconnected from the network, but game/session continues with remaining nodes. - After N packets of a failed node are not received, other nodes determine that this node got disconnected, and stops using dead reckoning on its messages. Properties of the Black Box Consistent Scalable Secure Robust Available Real-Time Real-Time Age of Empire study: • 250 milliseconds of command latency was not noticeable • Between 250 to 500 msec was playable • People develop a 'game pace' or mental expectation. Users would rather have a constant 500msec command delay rather than one that alternates between fast and slow. • In excited moments users would repeat commands which would cause huge spikes in the network demand so a simple filter was placed to prevent reissuing of commands Multicast - Multicast is a flooding algorithm - Distributed applications use multicast to propagate a message to all nodes in the network - Multicast was only used in a low percentage of the routers - Manufactures were reluctant to change to multicast enabled equipment because it is rarely used but it maximizes utilization of bandwidth. - Applications: Video/audio transmission, whiteboard Multicast can happen in many ways 1-many - multicast file transport - delivery of lecture Many-many - teleconference - distributed game Interactive gaming **applications:** - distributed interactive simulation - virtual reality - distributed multi-player games **common requirements:** - low latency (200 ms end-to-end) - loss tolerant - potentially large scale - many-many, most "players both send and receive" - group structure (e.g., locality in communication) among players MBONE ♦ Immediate solution to Multicasting ♦ Loose confederation of sites that currently implement IP multicast. ♦ Allows multiple packets to travel through routers that are setup to handle only unicast traffic. ♦ Will be obsolete when all routers implement multicasting MiMaze - MiMaze is a distributed 3-D Pacman game that uses an unreliable communication system which is based on RTP over UDP/IP multicast. - Not fully distributed, since a server is used to get the state of the game when new players join ongoing sessions and to do session management in general. MiMaze DIS Characteristics that apply to MiMaze: - Interaction delay: any action issued by any participant must reach, be processed and be displayed to any other participant within the shortest possible delay. - Participants can join and leave a MiMaze session dynamically. - The system architecture is distributed. MiMaze General Characteristics of MiMaze: - To minimize network traffic, MiMaze uses only one type of packet, which is called ADU (Application Data Unit). - ADU’s are similar to DIS’s ESPDU (Entity State PDU). They are 52 bytes long, 8 bytes for RTP header, 8 bytes for UDP header, 20 bytes for the IP header and 16 bytes for MiMaze application payload. - ADU’s contain a description of the local state of an Avatar (game objects), consisting of the local position in the game and the displacement vector of the avatar and of the projectile emitted by the avatar. MiMaze - ADU transmission frequency is 25 times per second, enough to obtain real-time visualization. - Consistency is assured using Bucket Synchronization: • Time is divided into fixed length periods and a bucket is associated with each of period. • All ADU’s received by a player that were issued by senders during a given period are stored by the receiver in the bucket corresponding to that interval. • At the end of every interval, all ADUs in that bucket are used by the entity to compute its local view of the global state. • Buckets are computed 100 ms after the end of the sampling period during which ADUs have been issued. MiMaze - When an ADU is received with a transmission delay which is more than 100 ms, its destination bucket has already been computed. But the late ADU is still stored in this bucket. It will be used by the Dead Reckoning algorithm to eventually replace a missing ADU. - Dead Reckoning Algorithm used is the simplest one: Use the previous ADU received from the missing source. - Not very efficient, but studies show that this does not affect the view of the game dramatically. - Better algorithms can be implemented, but the authors were not concerned about this issue. - Global clock mechanism: Bucket synchronization uses a global clock system to evaluate the delay between participating entities. - NTP (Network Time Protocol) was chosen, but it has 3 difficulties: - There are 3 levels of NTP servers and it is very difficult to maintain good synchronization among participants when level 3 servers are involved. - NTP encodes clock information in 64 bits, while RTP uses a 32-bit clock. MiMaze has to manipulate both representations. - NTP does not provide a reference clock signal and each participant has to compute an offset for every other participant in a game session. MiMaze -Future Work: - Better dead reckoning algorithm should be implemented to improve calculation of missing packets. - Some work has to be done to prevent cheating, since this system can be easily fooled. - Purpose of this design is not to fulfill every question in the field, but to show that with a multicast communication architecture and with a simple synchronization mechanism, a “fully” distributed interactive application can provide an acceptable level of consistency to DIAs on the internet. - Play MiMaze: http://www.inria.fr/rodeo/MiMaze Age of Empires Early Goal (1996): - 8 players in multi-player mode with 16Mb Pentium 90 at approximately 15fps - Story consisted of devastating a Greek city with catapults, archers, and warriors on one side while it was being besieged from the sea on the other Early Attempt: - Pass small sets of data about the units - This attempt limited actions to only 250 moving units at a time Age of Empires • Simultaneous Simulations: Rather than passing the status of each unit in the game, run the exact same simulation on each machine, passing each an identical set of commands that were issued by the users at the same time. • Problems still exist with network delay: 1. Sending out the player commands 2. Acknowledging all messages 3. Processing them before going on to the next turn Age of Empires • Turn Processing: A scheme designed to continue processing the game while waiting for communications to happen in the background • Commands issued during turn 1000 would be scheduled for execution during turn 1002. So on turn 1003, commands that were issued on turn 1001 would be executed. Age of Empires • Speed Control: Since the simulation must always have the exact same input, the game can only run as fast as the slowest machine can process the communications, render the turn and send out new commands which would cause “lag” to all the other computers. Two reasons for “lag”: 1. Low machine performance 2. High internet latency Age of Empires • Each client calculated: 1. Frame rate that could be maintained consistently 2. Round-trip ping time from itself to the other clients and an on-going average ping time • At the end of each turn, the host would send out a new frame rate and communications turn length to be used Age of Empires High internet latency with normal machine performance | Communications turn (1000 msec) - scaled to 'round-trip ping' time estimates | |-----------------------------------|-------------------| | Process all messages | Frame | Frame | Frame | Frame | Frame | Frame | Frame | | 50 msec | 20 frames, 50 msec each | Poor machine performance with normal internet latency | Communications turn (200 msec) - scaled to 'round-trip ping' time estimates | |-----------------------------------|-------------------| | Process all messages | Frame - scaled to rendering speed | | 100 msec | 100 msec | 20 fps 10 fps Age of Empires - Complete turn process - Security benefit: All users run exact same simulation so cheating is difficult. If any simulation ran differently then it was tagged as “out of sync” and the users game stopped - Hidden problem: It was difficult to detect when things were “out-of-sync” **Ages of Empire** Age of Empires 2 extra goals: - Fully 3D with animation - More than 8 players Used RTS3 Communication Architecture with their own layered architecture <table> <thead> <tr> <th>Game Communication</th> </tr> </thead> <tbody> <tr> <td>Multiplayer</td> </tr> <tr> <td>Link</td> </tr> <tr> <td>Socks</td> </tr> </tbody> </table> Level 1 – Socks layer provide the fundamental socket level routines Ages of Empire Layer 2 – Link level offers transport layer services such as the Link, Listener, and Network Address Layer 3 – Multiplayer level holds client information, session information, time sync, and shared data Layer 4 – Game Communication level basically boils down the game’s needs into a small easy-to-use interface Open Problems / Future Work • Cheating algorithms without sacrificing speed • Accurate and optimal Dead Reckoning algorithms • Minimizing scalability overhead • Administration and maintenance such as costs and resources Distributed Instant Messaging - IM systems deliver messages, as the name implies, instantly, i.e., messages are sent directly to the recipient without any intermediate storage and thus allow for real-time communication. - Current IM Systems rely on architectures that include central, or only partly distributed servers. Although some systems can exchange messages peer-to-peer, the user registration and lookup are still based on a centralized solution. <table> <thead> <tr> <th>Protocol</th> <th>Reg./Lookup</th> <th>Msg. exchange</th> </tr> </thead> <tbody> <tr> <td>AIM/OSCAR</td> <td>CS</td> <td>CS</td> </tr> <tr> <td>ICQ</td> <td>CS</td> <td>p2p</td> </tr> <tr> <td>IRC (DCC)</td> <td>Distr. servers</td> <td>CS/p2p</td> </tr> <tr> <td>Jabber</td> <td>CS</td> <td>p2p</td> </tr> <tr> <td>MSN IM</td> <td>CS</td> <td>CS</td> </tr> <tr> <td>Yahoo</td> <td>CS</td> <td>CS</td> </tr> </tbody> </table> CS=Centralized Server, p2p=peer-to-peer Table 1: Comparison of registration, lookup and message exchange mechanisms in different IM protocols. Distributed Instant Messaging • Although some of the mentioned applications, like Jabber and IRC (DCC) have some of the desired characteristics, they all suffer from a single point of failure where a malfunction will close the service, either by making it impossible to find clients or deliver messages. • Peer-to-peer systems provide powerful platforms for a variety of decentralized services, such as network storage and content distribution. • Today, we show 1 design: • DIMA based on PASTRY and SCAN DIMA based on PASTRY • Pastry is a generic peer-to-peer object location and routing substrate. It is a scalable, decentralized and self-organizing overlay network that automatically adapts to arrival, departure and failure of nodes. • Pastry Node: Each node joining the pastry overlay network is assigned a random 128-bit node identifier. • Each node maintains a routing table which is organized into \( \log_{16} N \) rows with 15 columns, where \( N \) is the number of nodes. Associated with each entry is the IP address of the closest nodes that have the appropriate prefix. • Additional to the routing table, each node maintains a leaf set. It contains IP-addresses of the \( L/2 \) numerically closest larger nodeIds and the \( L/2 \) closest smaller nodeIds. DIMA based on PASTRY • A new node joining the overlay network has to initialize its state tables and then inform the others of its presence. • As nodes may fail or depart without warning, neighboring nodes in the key space periodically exchange keep-alive messages. • The proposed DIMA uses Pastry for node insertion and message routing. It uses SCAN (Searching in Content Addressable Networks) to identify the nodes holding the most relevant information. • In SCAN, a Pastry key does not correspond to one physical host, but to a piece of content on a host. DIMA based on PASTRY • Keywords are encoded using the ASCII table, into a set of Pastry keys for nodeIds. A salt is added at the end of the pastry key to make sure that similar/equal keywords do not generate the same Pastry key. This method of key generation, builds a pastry network structured according to meta-data keywords. • To implement “Buddy Searching”, user info is used as the meta-data to put into the pastry network (like e-mail, nick, age, etc). • Using SCAN, we can search for this information and retrieve a UID in form of a Pastry key (or IP Address) to use for the communication channel. DIMA based on PASTRY - Buddy lists are stored on the user machine Figure 2: Inserting buddy information into the PASTRY network.
{"Source-Url": "http://zoo.cs.yale.edu/classes/cs538/ppt/MPV1.pdf", "len_cl100k_base": 4660, "olmocr-version": "0.1.53", "pdf-total-pages": 64, "total-fallback-pages": 0, "total-input-tokens": 82352, "total-output-tokens": 6871, "length": "2e12", "weborganizer": {"__label__adult": 0.0011043548583984375, "__label__art_design": 0.0010480880737304688, "__label__crime_law": 0.0013580322265625, "__label__education_jobs": 0.0017328262329101562, "__label__entertainment": 0.0007157325744628906, "__label__fashion_beauty": 0.0004305839538574219, "__label__finance_business": 0.0005717277526855469, "__label__food_dining": 0.0012216567993164062, "__label__games": 0.08575439453125, "__label__hardware": 0.00884246826171875, "__label__health": 0.000946044921875, "__label__history": 0.0013113021850585938, "__label__home_hobbies": 0.00027942657470703125, "__label__industrial": 0.0014390945434570312, "__label__literature": 0.0006175041198730469, "__label__politics": 0.0005211830139160156, "__label__religion": 0.001201629638671875, "__label__science_tech": 0.197021484375, "__label__social_life": 0.00030684471130371094, "__label__software": 0.04913330078125, "__label__software_dev": 0.64111328125, "__label__sports_fitness": 0.001239776611328125, "__label__transportation": 0.0013980865478515625, "__label__travel": 0.0007114410400390625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 20722, 0.00943]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 20722, 0.32702]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 20722, 0.91289]], "google_gemma-3-12b-it_contains_pii": [[0, 84, false], [84, 579, null], [579, 662, null], [662, 910, null], [910, 1128, null], [1128, 1211, null], [1211, 1283, null], [1283, 1553, null], [1553, 1623, null], [1623, 1948, null], [1948, 2035, null], [2035, 2143, null], [2143, 2244, null], [2244, 2314, null], [2314, 2555, null], [2555, 2650, null], [2650, 2691, null], [2691, 2894, null], [2894, 3140, null], [3140, 3235, null], [3235, 3453, null], [3453, 3656, null], [3656, 4081, null], [4081, 4533, null], [4533, 4842, null], [4842, 5153, null], [5153, 5716, null], [5716, 5799, null], [5799, 6148, null], [6148, 6533, null], [6533, 7049, null], [7049, 7257, null], [7257, 7759, null], [7759, 7854, null], [7854, 8344, null], [8344, 8427, null], [8427, 8886, null], [8886, 9279, null], [9279, 9417, null], [9417, 9761, null], [9761, 10036, null], [10036, 10334, null], [10334, 10651, null], [10651, 11218, null], [11218, 11861, null], [11861, 12439, null], [12439, 13057, null], [13057, 13616, null], [13616, 14004, null], [14004, 14409, null], [14409, 14717, null], [14717, 15066, null], [15066, 15366, null], [15366, 15990, null], [15990, 16287, null], [16287, 16645, null], [16645, 16974, null], [16974, 17195, null], [17195, 18142, null], [18142, 18651, null], [18651, 19421, null], [19421, 19984, null], [19984, 20592, null], [20592, 20722, null]], "google_gemma-3-12b-it_is_public_document": [[0, 84, true], [84, 579, null], [579, 662, null], [662, 910, null], [910, 1128, null], [1128, 1211, null], [1211, 1283, null], [1283, 1553, null], [1553, 1623, null], [1623, 1948, null], [1948, 2035, null], [2035, 2143, null], [2143, 2244, null], [2244, 2314, null], [2314, 2555, null], [2555, 2650, null], [2650, 2691, null], [2691, 2894, null], [2894, 3140, null], [3140, 3235, null], [3235, 3453, null], [3453, 3656, null], [3656, 4081, null], [4081, 4533, null], [4533, 4842, null], [4842, 5153, null], [5153, 5716, null], [5716, 5799, null], [5799, 6148, null], [6148, 6533, null], [6533, 7049, null], [7049, 7257, null], [7257, 7759, null], [7759, 7854, null], [7854, 8344, null], [8344, 8427, null], [8427, 8886, null], [8886, 9279, null], [9279, 9417, null], [9417, 9761, null], [9761, 10036, null], [10036, 10334, null], [10334, 10651, null], [10651, 11218, null], [11218, 11861, null], [11861, 12439, null], [12439, 13057, null], [13057, 13616, null], [13616, 14004, null], [14004, 14409, null], [14409, 14717, null], [14717, 15066, null], [15066, 15366, null], [15366, 15990, null], [15990, 16287, null], [16287, 16645, null], [16645, 16974, null], [16974, 17195, null], [17195, 18142, null], [18142, 18651, null], [18651, 19421, null], [19421, 19984, null], [19984, 20592, null], [20592, 20722, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 20722, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 20722, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 20722, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 20722, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 20722, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 20722, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 20722, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 20722, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 20722, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 20722, null]], "pdf_page_numbers": [[0, 84, 1], [84, 579, 2], [579, 662, 3], [662, 910, 4], [910, 1128, 5], [1128, 1211, 6], [1211, 1283, 7], [1283, 1553, 8], [1553, 1623, 9], [1623, 1948, 10], [1948, 2035, 11], [2035, 2143, 12], [2143, 2244, 13], [2244, 2314, 14], [2314, 2555, 15], [2555, 2650, 16], [2650, 2691, 17], [2691, 2894, 18], [2894, 3140, 19], [3140, 3235, 20], [3235, 3453, 21], [3453, 3656, 22], [3656, 4081, 23], [4081, 4533, 24], [4533, 4842, 25], [4842, 5153, 26], [5153, 5716, 27], [5716, 5799, 28], [5799, 6148, 29], [6148, 6533, 30], [6533, 7049, 31], [7049, 7257, 32], [7257, 7759, 33], [7759, 7854, 34], [7854, 8344, 35], [8344, 8427, 36], [8427, 8886, 37], [8886, 9279, 38], [9279, 9417, 39], [9417, 9761, 40], [9761, 10036, 41], [10036, 10334, 42], [10334, 10651, 43], [10651, 11218, 44], [11218, 11861, 45], [11861, 12439, 46], [12439, 13057, 47], [13057, 13616, 48], [13616, 14004, 49], [14004, 14409, 50], [14409, 14717, 51], [14717, 15066, 52], [15066, 15366, 53], [15366, 15990, 54], [15990, 16287, 55], [16287, 16645, 56], [16645, 16974, 57], [16974, 17195, 58], [17195, 18142, 59], [18142, 18651, 60], [18651, 19421, 61], [19421, 19984, 62], [19984, 20592, 63], [20592, 20722, 64]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 20722, 0.05738]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
76e9dd9a1f439160502735c030d22bb6ce22457d
Some Outstanding Projects Stephen A. Edwards Columbia University Fall 2017 Mathematical Languages: Mx, CAL Graphics Languages: CAL, CLAM, curve C- and Java-Like Languages: Cpi, Dice Hardware Description Languages: EHDL Music Languages: Note-Hashtag Mx: A Programming Language for Scientific Computation Tiantian Zhou, Hanhua Feng, Yong Man Ra, Chang Woo Lee 2003 Matlab-like language - Matrix literals, slicing (e.g., a[0, : ]) - User-defined functions; functions as first-class objects - Expression-only and imperative-style function declarations Compiled into Java with an extensive matrix library Example Plotting the Lorenz equations \[ \frac{dy_0}{dt} = \alpha(y_1 - y_0) \] \[ \frac{dy_1}{dt} = y_0(r - y_2) - y_1 \] \[ \frac{dy_2}{dt} = y_0y_1 - by_2 \] a = 10; /* Parameters for the Lorenz Equations */ b = 8/3.0; r = 28; func Lorenz ( y, t ) = [ a*(y[1]-y[0]); /* Matrix literal */ -y[0]*y[2] + r*y[0] - y[1]; y[0]*y[1] - b*y[2] ]; func RungeKutta( f, y, t, h ) { /* Differential Equation Solver */ k1 = h * f( y, t ); /* Invoke function f */ k2 = h * f( y+0.5*k1, t+0.5*h ); k3 = h * f( y+0.5*k2, t+0.5*h ); k4 = h * f( y+k3, t+h ); return y + (k1+k4)/6.0 + (k2+k3)/3.0; } N = 20000; p = zeros(N+1,3); /* matrix of zeros */ t = 0.0; h = 0.001; x = [ 10; 0; 10 ]; /* matrix literal */ p[0,::] = x'; /* matrix transpose */ for ( i = 1:N ) { x = RungeKutta( Lorenz, x, t, h ); /* Perform a step */ p[i,::] = x'; t += h; } colormap(3); plot(p); /* Plot points in the matrix */ return 0; /* Terminate */ YAPPL: Yet Another Probabilistic Programming Language For programming statistical models: Church-inspired language - OCaml-like functional syntax with explicit types - `fun` keyword for defining functions - Imperative code, too Compiled to OCaml An implementation of the Dirichlet Process (DP) using memoization ```haskell fun float:beta float:a float:b = ~rand in # get a stick, breaking more if necessary fun int:pickastick (fun float int):sticks int:j = if ~rand < ~sticks j then j else ~pickastick sticks j+1 in # generic Dirichlet process code fun (fun int):DP float:alpha (fun int):proc = fun float:sticks int:x := ~beta 1.0 alpha in fun int:atoms int:x := ~proc in fun int:f = ~atoms ~pickastick sticks 1 in f # return f in fun (fun (fun int) float):DPmem float:alpha (fun int float):proc = fun (fun int):dps float:arg := fun (fun int):dps float:arg := fun int:apply = ~proc arg in ~DP alpha apply in fun (fun int):dp float:arg = ~dps arg in dp in # this function will create Dirichlet process draws with geometric base distribution let (fun (fun int) float):geom_dp = ~DPmem 1.0 geom in # this is a DP draw with geometric base distribution with q = .2 let (fun int):mydraw = ~geom_dp .2 in # use a tail-recursive loop to generate some samples from the Dirichlet Process fun bool:loop int:i = ~print ~mydraw; if i > 0 then ~loop i - 1 else true in ~seed; ~loop 30; ~print_line ~mydraw ``` CAL: Concise Animation Language Tianliang Sun, Xinan Xu, Jingyi Guo, 2013 - C-like syntax - User-defined functions - Structs - OpenGL calls C-like language compiles into LLVM IR linked to OpenGL int i = 0, j = 0, size = 10; struct point_or_shape { point pt; shape shp; }; int add_point_or_shape(int x, int y, struct point_or_shape pos){ if(x == y || x == size - y - 1) add_shape(pos.shp); else add_point(pos.pt); return 0; } int main(){ struct point_or_shape pos; point pt; shape shp; for(i = 0; i < size; i=i++){ for(j = 0; j < size; j=j++){ pt.x=0.2*j+0.1-1.0; pt.y=-0.2*i-0.1+1.0; pt.vx=pt.y+pt.x; pt.vy=pt.x-pt.y; pt.r=pt.x/2.0+0.5; pt.g=pt.y/2.0+0.5; pt.b=0.0; shp.size=0.2; shp.x=0.2*j+0.1-1.0; shp.y=-0.2*i-0.1+1.0; shp.vx=shp.y/2.0+shp.x; shp.vy=shp.x/2.0+shp.y; shp.r=shp.x/2.0+0.5; shp.g=shp.y/2.0+0.5; shp.b=1.0; shp.omega=1.0; pos.pt = pt; pos.shp = shp; wait(0.05); add_point_or_shape(j, i, pos); } } for(i=0;i<size*size;i=i++){ wait(0.05); pop_shape(); pop_point(); } return 0; } CLAM: Concise Linear Algebra Manipulation Language Jeremy Andrus, Robert Martin, Kevin Sun, Yongxu Zhang, 2011 Image-processing language - Images with multiple channels (arrays, e.g., Red, Green) - Calculations: either literal C code or matrices - Kernel: sequence of calculations assembled with | - Convolution operator ★★ Compiles into C++ with extensive use of templates Image srcimg = imgread(1); /* Calc: functions on images */ /* # is "escape to C" */ Calc Lum := #[(3*Red + 6*Green + 1*Blue)/10]#; Calc sobelG<Uint8>:= #[sqrt((float)sobelGx*sobelGx + (float)sobelGy*sobelGy)]#; Calc sobelTheta<Angle>:= #[atan((float)sobelGy/(float)sobelGx)]#; srcimg |= Lum; /* Calculate luminance of source image */ Calc sobelGx<Uint8> := [1 / 1]{ -1 0 +1 , /* Convolution kernel */ -2 0 +2 , -1 0 +1 }; Calc sobelGy<Uint8> := [1 / 1]{ +1 +2 +1 , 0 0 0 , -1 -2 -1 }; Kernel sobel = | @sobelGx | @sobelGy | sobelG; /* Build up kernel */ sobel |= sobelTheta; /* Add another kernel */ Image edges = srcimg:Lum ** sobel; /* Convolve with sobel */ Image output; output:Red = edges:sobelG; /* Output B&W */ output:Green = edges:sobelG; output:Blue = edges:sobelG; imgwrite( output, "png", 2); Kun An, John Chan, David Mauskop, Wisdom Omuya, Zitong Wang, 2012 C-like language for animating vector graphics - int, Point, Curve, and Layer types - Wrote their own standard library with functions like rectangleXY Compiles into bytecode and interpreted int drawTree(int x, int y, int n) { Curve left; Curve right; if (n == 0) return 1; drawTree(x - exp(2, n), y - 50, n - 1); drawTree(x + exp(2, n), y - 50, n - 1); left = lineP((x, y), (x - exp(2, n), y - 50)); right = lineP((x, y), (x + exp(2, n), y - 50)); draw([left, right]); pause(100); return 1; } Cpi: A C dialect for the Raspberry Pi Edward Garcia, Niket Kandya, Naveen Revanna, Sean Yeh, 2013 Stripped-down C - Integers, characters, pointers, arrays, structs - User-defined functions - for, if, case, while statements Compiles into ARM V6 assembly int checkrow(char board[], int row){ int x1; int x2; x1 = row + 1; x2 = row + 2; if (board[row] == board[x1]){ if (board[x1] == board[x2]){ if (board[row] != ' '){ printf("Row win!\n"); return 1; } } } return 0; } int checkcol(char board[], int col){ int x1; int x2; x1 = col + 3; x2 = col + 6; if (board[col] == board[x1]){ if (board[x1] == board[x2]){ if (board[col] != ' '){ printf("Column win!\n"); return 1; } } } return 0; } int checkboard(char board[]){ int result; int j; result = 0; for (j = 0; j < 3; j = j + 1){ result = result + checkrow(board, 3*j) + checkcol(board, j); } // Check diags if (board[0] != ' '){ if (board[0] == board[4]){ // row = 0, col = 0 if (board[4] == board[8]){ // row = 0, col = 2 result = 1; } } } if (board[2] != ' '){ if (board[2] == board[4]){ // row = 2, col = 2 if (board[4] == board[6]){ // row = 2, col = 0 result = 1; } } } return result; } int printboard(char board[]){ printf("|%c|%c|%c|\n", board[0], board[1], board[2]); printf("-------\n"); printf("|%c|%c|%c|\n", board[3], board[4], board[5]); printf("-------\n"); printf("|%c|%c|%c|\n", board[6], board[7], board[8]); return 0; } char getchar(int p){ if (p == 1){ return 'O'; } return 'X'; } int main() { int player; int winner; int choice; int valid; int i; int count; char board[9]; char tempc; board[0] = ' '; board[1] = ' ' printf("Player 1: 'O'\nPlayer 2: 'X'\n\nValid inputs are 0-9\n\n") count = 0; winner = 0; player = 1; while (winner == 0){ printboard(board); valid = 0; while(valid == 0){ printf("Player %d, enter your move: ", player); printf("\n"); scanf("%d", &choice); valid = 1; if (choice < 0){ valid = 0; } if (choice > 9){ valid = 0; } if (valid == 1){ if (board[choice] != ' '){ valid = 0; } } } } } tempc = getchar(player); board[choice] = tempc; if (checkboard(board) > 0){ printboard(board); printf("Winner is Player %d!\n", player); winner = player; } if (player == 1) { player = 2; } else { player = 1; } count = count + 1; if (count >= 9){ if (winner == 0){ printf("No one wins!\n"); winner = -1; } } return 0; Dice: “Java, but worse” David Watkins, Emily Chen, Philip Schiffrin, Khaled Atef, 2015 Simplified Java language - Classes, inheritance - Methods, virtual function dispatch - Arrays - Strings - File I/O Compiles to LLVM include("stdlib"); class Player { public class LocationObj placeTile(bool retry) { return new LocationObj(); } public void setResult(class LocationObj move) { } } class HumanPlayer extends Player { private class Board board; public int myPieceType; constructor() { this.board = new Board(); this.myPieceType = 2; class Board b = this.board; b.initializeBoard(); } public class LocationObj placeTile(bool retry) { if (this.myPieceType == 2) this.myPieceType = 1; if (retry){ print("Last move was invalid. Retry. "); } print("It's your turn\n"); class Board b = this.board; b.printBoard(); print("Please enter your move\n"); class LocationObj move = this.getLocationObjChoice(); int temp = this.myChoiceType; b.setPlayerMove(move, temp); return move; } } public void setResult(LocationObj move) { int temp = this.myPieceType; if (temp == 1) { boolean one = (move.getHorizontal() == 3); boolean two = (move.getHorizontal() == 4); boolean three = (move.getVertical() == 3); boolean four = (move.getVertical() == 4); boolean five = (one || two) && (three || four); if (!five) { this.myPieceType = 0; } } int opponentPieceType; int temp2 = this.myPieceType; if (temp2 == 0) { opponentPieceType = 1; } else { opponentPieceType = 0; } Board b = this.board; b.setPlayerMove(move, opponentPieceType); } private class LocationObj getLocationObjChoice() { char[] userInput; String uInput; Board b = new Board(); LocationObj move = null; int temp = this.myPieceType; while (!b.isValid(move, temp)) { print("You are ", this.myPieceType, ". What is the x location of your next move?\n"); userInput = input(); uInput = new String(userInput); int x = uInput.toInteger(); print("You are ", this.myPieceType, ". What is the y location of your next move?\n"); userInput = input(); uInput = new String(userInput); int y = uInput.toInteger(); move = new LocationObj(x - 1, y - 1); boolean one = b.isValid(move, temp); if (!one) { print("invalid move, try again.\n"); } } return move; } EHDL: Hardware Description Language Paolo Mantovani, Mashooq Muhaimen, Neil Deshpande, Kaushik Kaul, 2011 - Bit vectors/binary numbers of a specific width - User-defined functions - If-then-else, switch-case - \( \text{POS} \) denotes clock boundaries in imperative code - \textbf{while} loops have an implicit clock - Arrays for little memories Compiles into VHDL (int(1) sum, int(1) carry) fulladder(int(1) a, int(1) b, int(1) carryin) { sum = a ^ b ^ carryin; carry = (a && b) ^ (carryin && (a ^ b)); } (int(4) s, int(1) overflow) main(int(4) a, int(4) b, int(1) carryin) { int(1) sum[4]; int(1) carry[4]; (sum[0], carry[0]) = fulladder(a(0),b(0),carryin); (sum[1], carry[1]) = fulladder(a(1),b(1),carry[0]); POS(1); (sum[2], carry[2]) = fulladder(a(2),b(2),carry[1]); (sum[3], carry[3]) = fulladder(a(3),b(3),carry[2]); POS(1); s(3) = sum[3]; s(2) = sum[2]; s(1) = sum[1]; s(0) = sum[0]; if ((a>0) && (b>0) && (sum[3]<0) )overflow = 1; else if ((a<0) && (b<0) && (sum[3]>0) )overflow = 1; else overflow = 0; } /* Sieve of Eratosthenes */ /* emits all the prime numbers less than m. m must be less than 200 as there is a bounded buffer of size 200 that is being used */ (int(32) primes=2) main (int(32) m) { int(1) a[200]; int(1) sig; int(32) n = 2; int(32) k = 2; while (n <= m) { if ((a[n] == 0) && (k <= m)) { if (k == n) { primes = n; /* generate output */ } else { a[k] = 1; } k = k + n; } else { n = n + 1; k = n + 1; } } /* Implicit clock cycle here */ } Note-Hashtag: Music Synthesis Language Kevin Chen, Brian Kim, Edward Li, 2015 - Vectors of notes with durations - Functional-like transformations (e.g., scale up two pitches) - Rhythm can be projected on a melody - Melody can be projected onto a key signature - User-defined composite types Generates C++ code that produces a .WAV file // Twinkle, Twinkle Little Star // main parts intro = quarter:[ 1 1 5 5 6 6 ] . half:5 chorus = Rhythms intro : [ 4 4 3 3 2 2 1 ] bridge = Relative 1 chorus // the tune twinkle_melody = intro . chorus . bridge . bridge . intro . chorus twinkle_harmony = Relative 2 twinkle_melody // supporting line base = eighth:[ 1 5 3 5 ] rise = eighth:[ 1 6 4 6 ] fall = eighth:[ 7@(-1) 5 2 5 ] bottom = eighth:[ 6@(-1) 5 1 5 ] intro_accomp = base . base . rise . base chorus_accomp = fall . base . bottom . base bridge_accomp = base . fall . base . fall // the accompaniment accomp = intro_accomp . chorus_accomp . bridge_accomp . \ bridge_accomp . intro_accomp . chorus_accomp twinkle_bass = Octave (-1) accomp // the song twinkle = Parallel { twinkle_melody twinkle_harmony twinkle_bass } twinkle$volumes = { 1.0 0.5 0.5 } Render twinkle "twinkle.wav" tempo = 74 // stairway to heaven - led zeppelin intro = eighth : [ 6@(-1) 1 3 6 7,5# 3 1 7 ] . e : [ 1@1,5 3 1 1@1 4#,4#@(-1) 2 6@(-1) 4 ] . e : [ 3,4@(-1) 1 6@(-1) ] . q:1 . e : [ 3 1 6@(-1) ] fin_chord = 5@(-1),7@(-1) fin = e:fin_chord,7@(-2) . Relative 1 ([ e (q+e) ]:fin_chord,5@(-2)) intro = intro . fin . Octave (-1) (e:[ 6@(-1) 4 3 ]) // note that the next phrase is the same except for the first and last notes intro_next = EndWith ([ e e h ]:Chords fin . q:~) (StartWith (e:6@(-2)) intro) stairway = intro . intro_next all_the_way_to_heaven = Parallel { stairway } Render all_the_way_to_heaven "stairway_to_heaven.wav"
{"Source-Url": "http://www1.cs.columbia.edu/~sedwards/classes/2017/4115-fall/projects.pdf", "len_cl100k_base": 5003, "olmocr-version": "0.1.53", "pdf-total-pages": 27, "total-fallback-pages": 0, "total-input-tokens": 39152, "total-output-tokens": 6594, "length": "2e12", "weborganizer": {"__label__adult": 0.0004887580871582031, "__label__art_design": 0.00047659873962402344, "__label__crime_law": 0.0002627372741699219, "__label__education_jobs": 0.0008382797241210938, "__label__entertainment": 0.0001704692840576172, "__label__fashion_beauty": 0.0001385211944580078, "__label__finance_business": 0.0001404285430908203, "__label__food_dining": 0.0005326271057128906, "__label__games": 0.0008382797241210938, "__label__hardware": 0.001468658447265625, "__label__health": 0.00040602684020996094, "__label__history": 0.0002181529998779297, "__label__home_hobbies": 0.00012803077697753906, "__label__industrial": 0.0003387928009033203, "__label__literature": 0.0003135204315185547, "__label__politics": 0.0002837181091308594, "__label__religion": 0.0005731582641601562, "__label__science_tech": 0.00981903076171875, "__label__social_life": 0.00011175870895385742, "__label__software": 0.003078460693359375, "__label__software_dev": 0.978515625, "__label__sports_fitness": 0.0003185272216796875, "__label__transportation": 0.0005125999450683594, "__label__travel": 0.00019371509552001953}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 15499, 0.03596]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 15499, 0.93109]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 15499, 0.50742]], "google_gemma-3-12b-it_contains_pii": [[0, 78, false], [78, 256, null], [256, 611, null], [611, 776, null], [776, 1533, null], [1533, 1846, null], [1846, 3048, null], [3048, 3246, null], [3246, 4397, null], [4397, 4775, null], [4775, 5611, null], [5611, 5869, null], [5869, 6216, null], [6216, 6216, null], [6216, 6473, null], [6473, 7746, null], [7746, 9000, null], [9000, 9364, null], [9364, 9587, null], [9587, 10531, null], [10531, 11983, null], [11983, 12351, null], [12351, 13064, null], [13064, 13668, null], [13668, 14007, null], [14007, 14862, null], [14862, 15499, null]], "google_gemma-3-12b-it_is_public_document": [[0, 78, true], [78, 256, null], [256, 611, null], [611, 776, null], [776, 1533, null], [1533, 1846, null], [1846, 3048, null], [3048, 3246, null], [3246, 4397, null], [4397, 4775, null], [4775, 5611, null], [5611, 5869, null], [5869, 6216, null], [6216, 6216, null], [6216, 6473, null], [6473, 7746, null], [7746, 9000, null], [9000, 9364, null], [9364, 9587, null], [9587, 10531, null], [10531, 11983, null], [11983, 12351, null], [12351, 13064, null], [13064, 13668, null], [13668, 14007, null], [14007, 14862, null], [14862, 15499, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 15499, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 15499, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 15499, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 15499, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 15499, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 15499, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 15499, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 15499, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 15499, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 15499, null]], "pdf_page_numbers": [[0, 78, 1], [78, 256, 2], [256, 611, 3], [611, 776, 4], [776, 1533, 5], [1533, 1846, 6], [1846, 3048, 7], [3048, 3246, 8], [3246, 4397, 9], [4397, 4775, 10], [4775, 5611, 11], [5611, 5869, 12], [5869, 6216, 13], [6216, 6216, 14], [6216, 6473, 15], [6473, 7746, 16], [7746, 9000, 17], [9000, 9364, 18], [9364, 9587, 19], [9587, 10531, 20], [10531, 11983, 21], [11983, 12351, 22], [12351, 13064, 23], [13064, 13668, 24], [13668, 14007, 25], [14007, 14862, 26], [14862, 15499, 27]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 15499, 0.0]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
f34148a0ae0936b3258f2321cd5acc47cd500f35
Circuits and Systems: Implementing Communication with Streams* by Steven D. Johnson Computer Science Department Indiana University Bloomington, Indiana 47405 TECHNICAL REPORT NO. 116 CIRCUITS AND SYSTEMS: IMPLEMENTING COMMUNICATION WITH STREAMS Steven D. Johnson Revised July 1982 *Research reported herein was supported in part by the National Science Foundation under grant number MCS 77-22325. To appear in the Proceedings of the 10th IMACS World Congress on Systems Simulation and Scientific Computation to be held in Montreal, Canada, 8-13 August; Edited by W.F. Ames and R. Vichnevetsky (Volume 5) Parallel and Large Scale Computers: Systems, Applications and Performance Evaluation. Circuits and Systems: Implementing Communication with Streams Steven D. Johnson Indiana University Computer Science Department 101 Lindley Hall Bloomington, Indiana, 47405 Models for a basic electronic circuit and a small time sharing system are implemented applicatively in Daisy, an output-driven list processing language. Rather than using shared variables to handle communication, these recursively defined systems use data streams, interpreted as changing over time. 1. Introduction Friedman and Wise propose applicative language constructs[8] and a new data constructor[11] to address concurrency and indeterminism. The programming language Daisy, being developed at Indiana University, incorporates these features. Its novelty lies in the fact that it is purely output-driven. All data creation, hence all computation, is on a call-by-need basis. Other terms for this approach to computation are delay rule,[24] demand driven computation,[17] lazy evaluation,[4] latent functions,[25] and suspending evaluation.[7] It is assumed that the reader is familiar with this idea, but not necessarily its practice; that is the subject of this report. Algorithms are implemented below that are distributed in nature. Since communication in such circuits tends to be regarded as mutual access to a shared variable (the wires connecting components[19]), programming them applicatively (without side effects) is a challenge. We shall instead implement the communication links as streams (non-finite lists) viewed here as functions-over-time. This is not an original approach; other proponents of applicative style adopt the same technique.[1, 13, 16, 2] The experience of implementing these circuits refines an understanding of technique and semantics, for which we pay very little syntaxically. We use the only tool at hand - systems of recursion equations - and find that it is nearly ideal for describing some circuits. Daisy's interpreter "solves" recursive systems lazily. Consequently, we are able to build and compute with non-finite as well as finite objects, without having to make a distinction between them. Here, we are concerned with stream-like objects - non-finite sequences of finite elements. Section 2 discusses Daisy's syntactic eccentricities. (Appendix A is a review of the language; Appendix B lists those primitive functions used in this report.) Sections 3, 4 and 5 each present a program and its implementation. Since we are concerned with a variety of issues about these programs, each section concludes with a number of loosely connected discussions. Section 6 is a summary. This report has two recurrent themes. First is the idea of program-as-schematic. Circuit drawings are a venerable algorithmic language, having evolved much longer than other programming languages. Expositions of ordinary algorithms usually start with some kind of picture - a state machine, flow diagram, etc. - but these descriptions are pure syntax. It is becoming increasingly clear that the meanings of these pictures can be found in systems of equations, just as finite-state processes are described by their transition matrices. Sections 4 and 5 model examples from two disparate areas of computer science: circuits and operating systems. Yet their schematics reveal their structural similarity. Second, the duality of process and data, reflected in the manipulation of streams, leads to a "type conflict". At lower levels, the content of a stream is viewed as the output of a function-over-time. Some functions describe components; a value change on their input stream results, a short time later, in a value change on their output stream. More complex functions are combinations of components. They simply express connectivity (that is, they describe schematics) and manipulate streams as objects. 2. Elements of Daisy's Syntax For more details, see Appendix A. Functions are denotable objects in Daisy. The expression \( \lambda x . E \) denotes the function \( \lambda x . E \), whose value when applied to an argument \( a \), is \( E \)'s value with all occurrences of \( x \) replaced by \( a \). All functions take one argument, which may be "structured" by a pure data description. This is analogous to a Pascal RECORD declaration or a Prolog EQUATION statement. Since the interpreter is output-driven, arguments are not compelled to match their declared structure, however, unless and until they are accessed according to it. Users partial to LISP might define: ``` car[<a!d>] \Leftarrow a. cdr[<a!d>] \Leftarrow d. cons[<a!d>] \Leftarrow [<a!d>]. ``` ``` oOrL \Leftarrow let [<a!d>] = L in if null L then <> else if Ld then Ld else orL. ``` Sequences of the form "\(<..>\)" are determinate in the sense that they specify an order for their elements. Mutisets, which are sequences surrounded by braces: "\({..}\)" , specify their elements, but not their order. When an order is needed, one is selected based on the relative cost of computing the elements. Divergent elements never precede convergent ones.[9, 10, 11] An exclamation point is the list concatenator. An asterisk is a primitive stream builder: \(<x >\) is equivalent to \[ \text{rec let } L = \langle x \downarrow ! \rangle \text{ in } L. \] Both expressions yield a non-terminating sequence whose elements are identical. Examples: \[ \begin{align*} \langle x > & \text{ where } x = 5 \text{ evaluates to } [5 5 5 \ldots] \\ \langle 1 2 3 > & \text{ evaluates to } [1 2 3 3 3 \ldots] \end{align*} \] Structures are applied to arguments in a manner analogous to vector arithmetic \([10.14]\). The argument, assumed to be in “row major” format (a list of rows), is transposed. The function-vector is applied coordinate-wise to the transposed argument. The key word “#” defines argument-matrices; #’s are skipped during transposition. Examples: \[ \begin{align*} \text{dotproduct}:[V1 \ V2] & \leftarrow \text{sum}[\text{multiply}]:[V1 \ V2]. \\ \text{matrixadd}[M1 \ M2] & \leftarrow [[\text{add} + ]]:[M1 \ M2]. \end{align*} \] \[ \begin{align*} \text{rows cons}[:] \begin{bmatrix} a & \# \\ \# & b \\ c & d \end{bmatrix} \end{align*} \] \[ \text{wireS} \leftarrow \langle(\text{ x x} >) + \rangle S. \] The reader should pause here to become comfortable with the definition of wire, which is used throughout. We would like to identify functions that return streams of sequences with functions that return sequences of streams. (This is the “type conflict” alluded to in the Introduction.) Functional combination transposes the (possibly non-finite) argument for us; all that is needed is to apply the identity function \(\lambda x . x\) repeatedly. If \(\Sigma\) contains no #’s, \(\text{wirewire}\ X\) is equivalent to \(\Sigma\). 3. Generating Streams We may think of streams either as objects or processes. Correspondingly, there are at least two ways to build them: with “functional recursion” and with “data recursion”\([9]\). This is primarily a syntactic distinction, although an implementation may favor one technique over the other. To illustrate, consider a stream of increasing integers. The non-finite sequence can be expressed as the result of a function: \[ \text{rec } N 0 \text{ where } \text{Ni} \leftarrow \langle i ! \text{Nadd}:<i \ 1 >\rangle. \] However, the expression \[ \text{rec } N \text{ where } N = \langle 0 \ 1 \text{[add*]}:\langle N <1* >\rangle. \] yields the same result. Regardless of their semantic equivalence, there is a subjective difference between these expressions. In the first expression \(N\) is a stream transformer, a function that iteratively computes its output. In the second expression, \(N\) is just the name of a stream, specifying the connectivity of an expression-circuit. The second schematic is composed of more primitive components: 1. A constant stream that supplies a source of 1’s to... 2. The component ADD, a stream transformer that distributes the primitive add operation pair-wise on its input streams, \([\text{add}]+<\ U \ V >\). Discussion: Implementation [Figure 1] Figure 1 shows an interactive session with Daisy in which both stream builders are implemented. The operator requests an infinite stream of integers and one is printed: the program must be aborted. (The host is a Digital Equipment computer, where the system interrupt character is EXIT, typed “Q”) Daisy is restarted, and the alternative expression yields the same behavior. Discussion: Call-by-need Still in Figure 1, Daisy is entered a third time. This time we ask for an element of the integer stream. Since all that is needed (for output) is a single element, interaction can continue. Normal termination follows, brought about by typing an end of file character on the keyboard stream. It is not the fact that an object is infinite that ties up the system, rather that the system has been asked to print an infinite object\([12]\). Discussion: Mapping The form of functional combination implemented in Daisy, a LISP-like “mapping” operation\([8]\) subsumes some commonly used recursion patterns. For example, it contains an implicit conditional to check for list termination. Mapping has always been the preferred way to deal with sets and arrays, and it is the preferred way to deal with streams, too. However, this form of combination is not the only way to map functions\([3, 15, 22]\). Often a stream transformer must carry some history (state) across iterations. When this is the case, we shall see occurrences of functional circularity (see the functions SELECT and MERGE in Section 5). 4. Feedback In the previous section a system of one recursive function (data) symbol is associated with a schematic of one component. Recursion is expressed as a feedback loop in the circuit. This generalizes immediately to systems of more than one recursive symbol. In this section we program a model of a “reset/set flip-flop”. % Daisy % rec: N \( \langle i : N : \text{add} : i \rangle \) % N: 0 % ( 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 \) interrupt % % Daisy % rec: N \( \langle 0 ! \langle \text{add} \rangle : i \rangle \) % N % ( 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 \) interrupt % % Daisy % 705: rec: ( N \( \langle 0 ! \langle \text{add} \rangle : i \rangle \) % N % ) % 699 % 51 52 52 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 DSI exit. Figure 1 Interaction with Daisy The components are identical: \[ \text{NAND} : [L, R] \leftarrow [\text{and*}] : [L, R] \] where \[ \text{and*} : [u, v] \leftarrow \text{if} \langle [u, 0] \rangle \text{then} 1 \] \[ \text{false} \text{if} \langle [v, 0] \rangle \text{then} 1 \text{else} 0. \] The "logic" function \text{and*} takes truth levels, 1 or 0, and interprets 1 as \text{true}. \text{NAND}, like \text{ADD} in Section 3, distributes \text{and*} across a pair of streams. We would like the program \text{RSFF} to be a transcription of its schematic: \[ \text{idealRSFF} : [R, S] \leftarrow \text{rec} < \text{Qhi}, \text{Qlo} > \] where \[ \text{Qhi} = \text{NAND} : < R \text{Qlo} > \] \[ \text{Qlo} = \text{NAND} : < S \text{Qhi} > . \] But this expression does not work. The mutually dependent outputs, \text{Qhi} and \text{Qlo}, are \text{deadlocked}. As is demonstrated in Figure 2, deadlock is alleviated by initializing both streams. \[ \text{RSFF} : [R, S] \leftarrow \text{rec} < \text{Qhi}, \text{Qlo} > \] where \[ \text{Qhi} = \langle 1 ! \text{NAND} : < R \text{Qlo} > \rangle \] \[ \text{Qlo} = \langle 0 ! \text{NAND} : < S \text{Qhi} > \rangle . \] \textbf{Discussion: Implementation of RSFF (Figure 2)} Figure 2 shows an interactive test of \text{RSFF} in Daisy. \text{Wire} (defined in Section 2) converts \text{RSFF}'s two outputs to a single stream of pairs so they can be printed in parallel. To test the function, two channels are established with the operator's keyboard. To the prompts "R" and "S", streams of 1's and 0's are typed. Each output line reflects the two keyboard inputs immediately preceding it. \textbf{Line (1):} \text{RSFF} retains its state (the values on \text{Qhi} and \text{Qlo}) as long as its inputs (the values on \text{R} and \text{S}) are held high. \textbf{Line (2):} A pulse on \text{S} (a burst of 0's) leads to a change in state. After a moment of confusion, \text{Qhi} and \text{Qlo} reverse their values. \textbf{Line (3):} A spike on one of the input streams (a single 0) is captured by the system. The outputs start oscillating... \textbf{Line (4):} ... and continue to do so until a "reset" is asserted. \textbf{Line (5):} \text{RSFF} issues ambiguous output (\text{Qhi} = \text{Qlo}) if both \text{R} and \text{S} are asserted... \textbf{Line (6):} ... and becomes "netastable" if \text{R} and \text{S} return to high values simultaneously. Discussion: Idealized Behavior Both of RSFF’s outputs vary over time, subject to the condition of its inputs. The granularity of the model depends on how time is quantized in its streams. RSFF’s behavior is similar to that of a real flip-flop. It is ambiguous on invalid inputs, and in extreme conditions goes into a kind of metastable state.[20] Because it is a discrete model, there are no thermal fluctuations or manufacturing disparities to attenuate its oscillation. Nor does it manipulate voltage levels in detail. Some of these discrepancies can, of course, be eliminated by refined modeling.[5, 21] Discussion: The Principle of Stream Conservation Disregarding any notion of causality, RSFF works best when its outputs are consumed at the same “rate” as its inputs are supplied. Were RSFF to be used as a component in a system that, over the long run, needed two Qhi values for every Qlo value, we would have to adjust RSFF’s code accordingly; and we could do so for any known ratio of rates. This has the flavor of an equilibrium assumption, and is an analytic property of RSFF’s computation. A sketch of a proof that RSFF produces no faster than it consumes uses the circuit’s structure. \[ \text{RATE(Qhi)} = \text{MIN}(\text{RATE(R)}, \text{RATE(Qlo)}) \] The first equality comes from axiomatic properties of primitive components. The second is by symmetry of the circuit. The rest come from facts about MIN. Discussion: Coercion This system contains both stream transformers and stream handlers. The functions RSFF and NAND are just connectivity expressions; they steer their stream-arguments to more primitive components. The expression \(\text{R} \land \text{X} \rightarrow \text{NAND} \text{X} \) uses the underlying system (via functional combination) to compose two stream-arguments into one argument-stream-of-pairs, which in turn is transformed by sequential applications of \(\text{NAND} \). Discussion: Stream Initialization The need to put initial values on streams is analogous to the need to code termination conditions in numerical functions. Since our real interest is in RSFF’s running behavior, it seems like a bothersome detail. Of course these values form the inductive basis for any assertion about the program, so they are necessary. For example, to prove the invariant: “Qhi differs logically from Qlo as long as R and S remain high,” Qhi and Qlo must be different to begin with. 5. Indeterminacy RSFF is “synchronized” by stream construction. While this property can be preserved within a system, there is no guarantee that its inputs and outputs behave so well. This section describes a technique to handle indeterminacy. Suppose we are to write a system with the hypothetical specification: "...MSG is a full duplex message sending system for two computer terminals, A and B. Input from A's (respectively B's) keyboard, \( K_1 \) (\( K_2 \)) is echoed on A's (B's) screen, \( S_1 \) (\( S_2 \)). However, when \( K_1 \) issues a "send", the ensuing form should be displayed in a timely fashion on \( S_2 \) (and conversely for \( K_2 \) and \( S_1 \))." The schematic for MSG has roughly the same connectivity as RSFF’s, except that its ROUTE components have two outputs instead of one – for screen display and for message feedback. \[ \text{MSG:} \langle \text{KA KB} \rangle \leftarrow \text{rec} \langle \text{SA SB} \rangle \] \[ \text{where} \] \[ \langle \text{SA MA} \rangle = \text{ROUTE:} \langle \text{KA MB} \rangle \] \[ \langle \text{SB MB} \rangle = \text{ROUTE:} \langle \text{KB MA} \rangle. \] MSG's components are themselves circuits. The function ROUTE takes keyboard (K) and message input (Min), combines them, and delivers screen output (S) and message feedback (Mout). \[ \text{ROUTE:} [\text{K Min}] \leftarrow \text{rec} <S \text{ Mout}> \] \[ \text{where} \] \[ [Mout Dplx] = \text{wire:} <\text{#} \text{On} \ # > \text{! SELECT:} [K] \] \[ S = \text{MERGE:} <\text{Dplx Min}> \] ROUTE takes care of stream initialization, as well as the extraction of distinct streams from SELECT. MERGE manages indeterminacy in a manner similar to that of [H] . \[ \text{SELECT:} [K] \leftarrow \] \[ \text{rec let } K_h!K_t = K \] \[ [Kth!Kt] = K_t \] \[ \text{in} \] \[ \text{if same?:} <K_h \#send> \] \[ \text{then } <K_h \text{ # } > \text{! SELECT:} K_h \] \[ \text{else } <K_h \text{ # } > \text{! SELECT:} K_t. \] \[ \text{MERGE:} [L \text{ R}] \leftarrow \] \[ \text{let } L_a!L_d = L \] \[ R_a!R_d = R \] \[ \text{in} \] \[ \langle L_a, L_d \rangle: \] \[ \text{strictify:} <L_a <L_d \text{ MERGE:} <R_a \text{ R_d} > > \] \[ \text{strictify:} <R_a <R_d \text{ MERGE:} <L_a \text{ L_d} > >. \] Of concern is whether MSG meets the informal specification "...in a timely fashion...". Not only must MSG avoid deadlock (a data dependency like that in ideal RSFF, Section 4), it must avoid lockout as well. Lockout would result if the system were to wait deterministically for input from a specific terminal. **Discussion: Implementation of MSG (Figure 3)** Lines beginning with the prompt "A" (respectively "B") are the keyboard input for terminal A (B). The remaining lines show the output to terminal A's screen. B's screen is not shown. We may think of the keyboard inputs as concurrent. B only sends messages, which appear on A's screen prefixed with the character,"!". A's first entries ("hm hm hm") are echoed on his screen with B's first messages interspersed. As A joins in the round, B's next messages are coming through. This continues as long as B transmits to A's screen. A \((SA SB).SA\): MSG:< keyboard:0B keyboard:0A > send ROW send ROW send (ROW YOUR BOAT) A hm hm hm hm hm (? ROW) hm (? ROW) hm hm (? (ROW YOUR BOAT)) A row row row your boat B send GENTLY send (DOWN THE STREAM) A send MERRILY send MERRILY send MERRILY send MERRILY row (? GENTLY) row row (? (DOWN THE STREAM)) your boat (? MERRILY) A gently down the stream gently (? MERRILY) down (? MERRILY) the stream (? MERRILY) A merrily merrily merrily merrily B send LIFE send IS send BUT send (A DREAM) merrily merrily (? LIFE) merrily (? IS) merrily A life is but a dream B HM HM HM HM (? BUT) life (? (A DREAM)) is but a dream A Figure 3 An Interactive Test of MSG The Role of “#” The system avoids deadlock because it is internally synchronous: the multivalued functions always produce values for each of their outputs. It is at the innermost component, MERGE, where the indeterminacy is resolved. SELECT's stream of pairs is coerced by ROUTE to a pair of streams. But SELECT creates pairs containing #’s, which functional combination skips during transposition. So while SELECT is synchronously producing its stream, that stream is deformed to present “real time” data to MERGE. Discussion: Is MSG Fair? A heuristic discussion on the fairness of MSG has the form of a subgoal induction [25]. At any level, we shall assert that if the system is unfair, it is the fault of its components. The function MSG is fair by symmetry. Its connectivity precludes favoritism for either keyboard. ROUTE is a function combination. Its components are connected, more or less in series, so if either induces lockout, ROUTE may. SELECT waits for its input to converge, but SELECT has only one input! Surely it is all right for a function to wait for its only source of information. This brings us to MERGE. The form: \( (\text{strictify} . u . x) \) \text{strictify} . x . y \) is analogous to the guarded command \[ \text{if} u \rightarrow v \] \text{then} \[ x \rightarrow y \] Identifiers \( x \) and \( y \) play the role of input guards [14]. MERGE is fair modulo the “( ... )” construction [10]. In fact it is probably fairer. MERGE swaps its inputs occasionally (note carefully the recursive calls). Suppose that the underlying system is neither fair nor malicious, rather that it is biased — favoring multiset arguments according to their textual order. Then by switching that order from time to time MERGE ameliorates the bias. 6. Summary In Sections 1 and 5 models are implemented for a fundamental electrical circuit and a small timesharing system. That they were implemented in the same language speaks not so much for the language itself as for the similarity of their schematic structure. Both are circuits of two autonomous components; both have about the same feedback relationship. The translation from schematic to program is testimony to the expressiveness and usefulness of recursive systems of equations. In these systems, communication is achieved by encoding time in streams. Since the interpreter used is output-driven, streams are built without special language primitives. For completeness, designers of applicative languages must choose an interpretation for the application of a structure to an argument. The form of combination used in Daisy works well in these examples because it provides the right transformation to implement the connectivity of schematic programs. Where the behavior of input producers and output consumers is known, systems are synchronized by the rate at which they build streams. Multisets can be used to model lockout avoidance in systems with indeterminate input behavior. Notes 1 Research reported herein was supported (in part) by the National Science Foundation under grant number MCS77-2222925. 2 Daisy's infinite lists are not "legitimate" streams (in the sense of [18]) since they are not strict in their elements. But until Section 5 there is little need to make a distinction. 3 The versions of car and cdr defined here, however, are not strict, since cons is suspended. Consequently, the laws: \[ \text{car cons } \langle a \, b \rangle = a \] \[ \text{cdr cons } \langle a \, b \rangle = b \] hold, even if \( a \) or \( b \) diverges. 4 Daisy's full parser is still under development. The syntax of programs run to generate the Figures differs from what is presented in this report. References Appendix A Dyaln Syntax \[ \text{EXP} ::= \text{ATOM} \mid \text{FERN} \mid \text{APPL} \mid \text{FNTN} \mid \text{COND} \mid \text{SYS} \\ \text{EXP} ::= (\text{EXP}) \mid \text{LET} \text{ EXP} \\ \] The six forms of expression are described below. Parentheses are used for parser direction. The special symbol \texttt{LET} means "quote", that is, inhibit evaluation. \textbf{ATOM} ::= \text{LTRL} \mid \text{NMBR} Numerals are expressed and represented as rational numbers. They evaluate to themselves. \textit{Literals} are strings of characters and evaluate to their bindings in the current environment. \textbf{FERN} ::= [\text{ELST}] \mid \langle \text{ELST} \rangle \mid \{ \text{ELST} \} \textbf{ELST} ::= \text{empty} \mid \text{EXP} \cdot \text{EXP} \mid \text{EXP} \mid \text{ELST} \\ A \textit{fern} is a list specification. The three enclosure symbols express progressively weaker specifications of content and order. The [...] construct is a structural quotation; it evaluates to precisely the list expressed. The <...> construct evaluates to a list of \textit{values} in the order specified. However, computation of these values does not take place unless and until the list is accessed. Ferns of the form [...] specify content but not order. The interpreter chooses an order at run-time, by evaluating the elements concurrently. The ordering of the element values list depends on how fast they converge. The examination point is the list concatenation operator; an asterisk denotes a stream of identical elements. \textbf{APPL} ::= \text{EXP} \cdot \text{EXP} The left-hand expression in an \textit{application} is interpreted as a function and applied to the argument on the right. If the function is primitive, it is executed by the interpreter. For example, numeric functions denote list access, so \texttt{SIX} evaluates to \texttt{x}'s fifth element. Some of the literals reserved to name primitive functions are shown in Appendix B. If the function-expression evaluates to a list, the interpreter first transposes the argument, which is assumed to consist of a list of "rows". Any instances of the keyword "#" are removed during transposition. The elements of the function are then applied coordinate-wise to the transposed argument's "columns". \textbf{FNTN} ::= \backslash \text{EXP} \cdot \text{EXP} A \textit{function} is analogous to a lambda-expression. When applied, the function's \textit{formal argument} (to the left of the \texttt{\texttt{LET}}) is superimposed on the actual argument of the application. This associates identifiers in the formal argument to their relative positions in the actual argument. The association is \textit{suspended}, and so is not enforced until the binding for the identifier is actually used in the computation. The value of a function is its \textit{closure}, a non-printable object that saves the environment in effect when the function was created. All free variables are bound in the closure's environment, making the language lexically scoped. \textbf{COND} ::= \text{IF} \text{ EXP} \text{ THEN} \text{ EXP} \text{ ELSE} \text{ EXP} The \textit{predicate} (if part) is evaluated. If the result is non-null the conditional returns the value of its \textit{consequent} (then part). Otherwise, the value of the \textit{alternate} (else part) is returned. Evaluation of the consequent and alternate are deferred until the predicate converges. \textbf{SYS} ::= \text{BODY} \mid \text{LET BODY} \mid \text{EXP where DCL} \mid \text{DCL}::=\text{empty} \mid \text{DFN DCL} \mid \text{DFN} ::= \text{EXP} \text{ = EXP} \mid \text{LET} \text{ EXP} \text{ <= EXP} A typical Dyaln program is a system of defining equations, followed by an expression to be evaluated in that system. If the defining equations are not recursive, they are equivalent to a lambda-expression. That is, \[ \text{let } (x = a) (y = b) (z = c) \text{ in e} \] is equivalent to \[ (\lambda [x \ y \ z]. \ c) <a \ b \ c> \] The "let...in" and "where..." forms have equivalent meanings. Systems preceded with the keyword \textit{let} are recursively defined. The defining equations may define either functions or data; their left hand sides may be either atomic or lists. The symbol \texttt{<=} makes function definitions easier to read. One may write \[ \text{Fix} \leftarrow e, \] rather than \[ F = \lambda x. e. \] Global assignments are allowed at top level. Thus the operator can extend the set of basic operators with definitions of his own. Appendix B Operators The following primitive Daisy operators are used throughout this report. *add* Returns the arithmetic sum of the first two elements of its argument. *console* Takes a single character argument and establishes an independent channel to the operator's keyboard, using that character as a prompt. Returns a stream of characters. *eq?* A test for numeric equality. *format* A user defined function that inserts carriage returns in a stream. Used in Figure 2. *keyboard* A user defined function to convert operator input to a useful format. In Section 4. \[ \text{keyboard} \triangleleft \text{filter} \circ \text{parse} \circ \text{console} \triangleleft \text{p where} \] \[ \begin{align*} \text{filter} & \triangleleft \text{let} \ [S!S_i] = S \text{ in} \\ & \quad \text{if null?S then } <> \text{ else} \\ & \quad \text{if num?S!S_i then } \text{<Sh!filter:St>} \text{ else } \text{filter:St.} \end{align*} \] In Section 5. \[ \text{keyboard} \triangleleft \text{parse} \circ \text{console} \triangleleft \text{p.} \] *num?* A test for a numeric argument. *null?* A test for the empty list. *parse* Daisy’s parser from character stream to internal representation of expressions. *same?* A test for reference equality. *strictify* Functions cannot test whether a value is suspended, but can exploit Daisy’s interpreter to force a value into existence. \[ \text{strictify}:\langle x \ y \rangle \triangleleft \text{if } x \text{ then } y \text{ else } y. \]
{"Source-Url": "https://www.cs.indiana.edu/pub/techreports/TR116.pdf", "len_cl100k_base": 8070, "olmocr-version": "0.1.50", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 11430, "total-output-tokens": 10292, "length": "2e12", "weborganizer": {"__label__adult": 0.00046133995056152344, "__label__art_design": 0.000499725341796875, "__label__crime_law": 0.0003237724304199219, "__label__education_jobs": 0.0006747245788574219, "__label__entertainment": 0.00012159347534179688, "__label__fashion_beauty": 0.00020766258239746096, "__label__finance_business": 0.0002593994140625, "__label__food_dining": 0.0004780292510986328, "__label__games": 0.000598907470703125, "__label__hardware": 0.00426483154296875, "__label__health": 0.0005903244018554688, "__label__history": 0.0003352165222167969, "__label__home_hobbies": 0.0001646280288696289, "__label__industrial": 0.0008859634399414062, "__label__literature": 0.00036716461181640625, "__label__politics": 0.0003101825714111328, "__label__religion": 0.0007219314575195312, "__label__science_tech": 0.100341796875, "__label__social_life": 9.500980377197266e-05, "__label__software": 0.005756378173828125, "__label__software_dev": 0.880859375, "__label__sports_fitness": 0.0004146099090576172, "__label__transportation": 0.0011749267578125, "__label__travel": 0.0002378225326538086}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 33477, 0.02087]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 33477, 0.47442]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 33477, 0.84129]], "google_gemma-3-12b-it_contains_pii": [[0, 698, false], [698, 5758, null], [5758, 10594, null], [10594, 13957, null], [13957, 16697, null], [16697, 19536, null], [19536, 23163, null], [23163, 27463, null], [27463, 31975, null], [31975, 33477, null]], "google_gemma-3-12b-it_is_public_document": [[0, 698, true], [698, 5758, null], [5758, 10594, null], [10594, 13957, null], [13957, 16697, null], [16697, 19536, null], [19536, 23163, null], [23163, 27463, null], [27463, 31975, null], [31975, 33477, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 33477, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 33477, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 33477, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 33477, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 33477, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 33477, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 33477, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 33477, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 33477, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 33477, null]], "pdf_page_numbers": [[0, 698, 1], [698, 5758, 2], [5758, 10594, 3], [10594, 13957, 4], [13957, 16697, 5], [16697, 19536, 6], [19536, 23163, 7], [23163, 27463, 8], [27463, 31975, 9], [31975, 33477, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 33477, 0.0]]}
olmocr_science_pdfs
2024-11-30
2024-11-30
5690b67fb6688668ae2e0b20c780cadbc693092a
Sched Ext The extensible sched_class Dan Schatzberg Research Scientist Agenda 01 Background and motivation 02 Building schedulers with sched_ext 03 Example schedulers 04 Current status and future plans 05 Questions? 01 Background and motivation What is a CPU scheduler? CPU schedulers multiplex threads onto core(s) - Manages the finite resource of CPU between all of the execution contexts on the system - Decide who gets to run next, where they run, and for how long - Does context switching What about multiple cores? No problem, just move tasks between cores when one becomes available Except that caches exist, there’s a latency penalty for migrations, etc… Things get very complicated very quickly - Very challenging technical problem - **Fairness**: Everyone should get some CPU time - **Optimization**: Make optimal use of system resources, minimize critical sections - **Low overhead**: Should run for as short as possible - **Generalizable**: Should work on every architecture, for every workload, etc. CFS: The Completely Fair Scheduler CFS is a “fair, weighted, virtual time scheduler” - Threads given proportional share of CPU, according to their weight and load - In example on right, all threads have equal weight - Conceptually quite simple and elegant - Also has drawbacks, more on this later Ideal Precise Multi-tasking CPU - Each task runs in parallel and consumes equal CPU share CFS is a “fair, weighted, virtual time scheduler” - Threads given proportional share of CPU, according to their weight and load - In example on right, all threads have equal weight - Conceptually quite simple and elegant - Also has drawbacks, more on this later ![Conceptual Diagram] **Ideal Precise Multi-tasking CPU** - Each task runs in parallel and consumes equal CPU share CFS is a “fair, weighted, virtual time scheduler” - Threads given proportional share of CPU, according to their weight and load - In example on right, all threads have equal weight - Conceptually quite simple and elegant - Also has drawbacks, more on this later CFS has been in the kernel since 2007 --- **01 Background and motivation** --- CFS has been in the kernel since 2007. CFS was built in a simpler time - Much smaller CPUs - Topologies much more homogeneous - Cores spaced further apart, migration cost typically high - Power consumption and die area wasn’t as important CFS was built in a simpler time - Much smaller CPUs - Topologies much more homogeneous - Cores spaced further apart, migration cost typically high - Power consumption and die area wasn’t as important Intel Xeon MP 71xx die Just two cores Just one L3 cache New reality: complex hardware topologies, and heterogeneity - **CCD**’s (Core Complex Dies) aggregate groups of **CCX**’s (Core Complexes) - A CCX is a cluster of cores that share an L3 cache - Can have multiple CCXs per NUMA node - Can have multiple CCXs per CCD Architectures *much* more complicated now - Heterogeneity is becoming the norm - Non-uniform memory accesses between sockets - Non-uniform memory accesses between CCDs - Non-uniform memory accesses between CCXs - Non-uniform memory accesses between CCXs in the same CCD **32MB Unified L3 Cache Benefits** - **Zen 2** AMD EPYC 7202 - **Zen 3** AMD EPYC 7003 **AMD Zen 2 Rome** **AMD Zen 3 Milan** Architectures *much* more complicated now - Heterogeneity is becoming the norm - Non-uniform memory accesses between sockets - Non-uniform memory accesses between CCDs - Non-uniform memory accesses between CCXs - Non-uniform memory accesses between CCXs in the same CCD 4 cores per “CCX” 8 cores per “CCD” 2 L3 caches per CCD! AMD Zen 2 Rome 8 cores per “CCX” 8 cores per “CCD” 1 L3 cache per CCD! CFS is great, but has some drawbacks - Experimentation is difficult: need to recompile + reboot + rewarm caches - Generalizable scheduler - Often leaves some performance on the table for some workloads / architectures - Impossible to make everyone happy all of the time - Difficult to get new features upstreamed - Can't regress the scheduler - High bar for contributions (understandably) - Results in lots of out of tree schedulers, vendor hooks, etc Result: usually lots of heuristics in the scheduler - Scheduler did something I didn’t like, tweak the behavior to accommodate - Err on the side of keeping a task local to promote cache locality - Be more likely to schedule someone who was previously your hypertwin - Don’t apply well to every workload or architecture - Often result in non-intuitive behavior - Setting sched_migration_cost_ns knob to 0 may still not migrate a task to use an idle core - SHARED_RUNQ patchset is meant to help address this: https://lore.kernel.org/all/20230809221218.163894-1-void@manifault.com/ Quick aside on BPF BPF: The safe way to run kernel code - Kernel feature that allows custom code to run safely in the kernel - Started in the early days as a way to do custom packet filtering, now a much, much larger and richer ecosystem - Write C code, compile it to BPF bytecode, userspace can load it into the kernel - Far too much to cover here. Conceptually, just think “safe JIT in the kernel” Introducing: sched_ext sched_ext enables scheduling policies to be implemented in BPF programs 1. Write a scheduler policy in BPF 2. Compile it 3. Load it onto the system, letting BPF and core sched_ext infrastructure do all of the heavy lifting to enable it - New sched_class, at a lower priority than CFS - No ABI stability restrictions – purely a kernel <-> kernel interface - GPLv2 only Rapid experimentation - No reboot needed – just recompile BPF prog and reload - Simple and intuitive API for scheduling policies - Does not require knowledge of core scheduler internals - Safe, cannot crash the host - Protection afforded by BPF verifier - Watchdog disables sched_ext scheduler if a runnable task isn’t scheduled within some timeout - New sysrq key for disabling sched_ext scheduler through console Bespoke scheduling policies - CFS is a general purpose scheduler. Works OK for most applications, not optimal for many - Optimizes some major Meta services (more on this later) - HHVM optimized by 2.5-3+% RPS - Looking like a 3.6 - 10+% improvement for ads ranking - Google has seen strong results on search, VM scheduling with ghOSt 01 Background and motivation Moving complexity into user space - Offload complicated logic such as load balancing to user space - Use of floating point numbers - Use standard debugging tools - BPF makes it easy to share data between the kernel and user space Background and motivation Sharing Scheduling Logic - No need to maintain out of tree scheduler patches - Meta and many other companies need to do this currently - Share BPF schedulers instead What is sched_ext *not*? sched_ext is not meant to replace CFS - Virtual runtime is an elegant fairness algorithm for a general purpose scheduler - The kernel will likely always need a general purpose scheduler - Features discovered with and experimented on with sched_ext can be upstreamed to CFS. One of the main motivators - SHARED_RUNQ patchset is is a direct result of sched_ext experimentation: https://lore.kernel.org/all/20230809221218.163894-1-void@manifault.com/ sched_ext is **not** meant to replace upstream development - A sched_ext scheduler **must** be GPLv2 to be loaded by the verifier - Will fail to load at runtime otherwise - Several schedulers included in the upstream patch set (mentioned later in the presentation) - So much out of tree scheduler code already. The hope is that this will *improve* things. sched_ext is **not** meant to impose UAPIs restrictions on the kernel - struct_ops, the main BPF feature backing sched_ext, does not have UAPI guarantees - Strict kernel <-> kernel interface - User space programs can talk to BPF programs over maps, but this is nothing new for BPF - The core scheduler API can change, and could break out of tree schedulers - Not expected to happen with regularity, but it is allowed according to advertised UAPI policy for sched_ext and struct_ops BPF programs **DISCLAIMER:** This is a somewhat subjective topic. We do our best to be explicit and both state and document our UAPI guarantees, but at the end of the day, it is up to Linus to interpret this. 02 Building schedulers with sched_ext Implementing scheduling policies - BPF program must implement a set of **callbacks** - Task wakeup - Task enqueue/dequeue - Task state change (runnable, running, stopping, quiescent) - CPU needs task(s) (balance) - Cgroup integration - ... - Also provides **fields** which globally configure scheduler - Max # of tasks that can be dispatched - Timeout threshold in ms (can't exceed 30s) - Name of scheduler /* Return CPU that task should be migrated to on wakeup path. */ s32 (*select_cpu)(struct task_struct *p, s32 prev_cpu, u64 wake_flags); /* Enqueue runnable task in the BPF scheduler. May dispatch directly to CPU. */ void (*enqueue)(struct task_struct *p, u64 enq_flags); /* Called when the CPU has no tasks to run */ void (*dispatch)(s32 cpu, struct task_struct *prev); ... /* Maximum time that task may be runnable before being run. Cannot exceed 30s. */ u32 timeout_ms; /* BPF scheduler’s name. Must be a valid name or the program will not load. */ char name[SCX_OPS_NAME_LEN]; From https://github.com/sched-ext/sched_ext/blob/sched_ext/include/linux/sched/ext.h Dispatch Queues (DSQs) are the basic building block of scheduler policies - Every core has a special “local” DSQ called SCX_DSQ_LOCAL - Otherwise, can create as many or as few as needed - Gives schedulers flexibility - Per-domain (NUMA node, CCX, etc) DSQ? - Global DSQ? - Per-cgroup DSQ? - The data structure / abstraction layer for managing tasks between main kernel <-> BPF scheduler (more on next slide). Local DSQs are per-CPU – the “runqueue” that the core kernel actually chooses from. Local DSQs are per-CPU – the “runqueue” that the core kernel actually chooses from. Local DSQs are per-CPU – the “runqueue” that the core kernel actually chooses from - FIFO or priority queue of tasks. “dispatched” (i.e. enqueued) from BPF - What’s actually pulled from when a task is scheduled in Example 0: Global FIFO – enqueueing - Scheduler “dispatches” tasks to global DSQ at enqueue time - Not where tasks are pulled from when being scheduled in - Task must be in local DSQ to be chosen to run ![Diagram showing task dispatch and scheduling process] Global DSQ Example 0: Global FIFO – enqueueing ```c s32 BPF_STRUCT_OPS_SLEEPABLE(mysched_init) { scx_bpf_create_dsq(/* queue id = */ 0, -1); } void BPF_STRUCT_OPS(mysched_enqueue, struct task_struct *p, u64 enq_flags) { scx_bpf_dispatch(p, /* queue id = */ 0, SCX_SLICE_DFL, enq_flags); } ``` - Cores “consume” tasks from the global DSQ when going idle (i.e. no tasks left in the core’s local DSQ) Cores "consume" tasks from the global DSQ when going idle (i.e. no tasks left in the core’s local DSQ) and enqueue them on their local DSQ to be scheduled. Example 0: Global FIFO – consuming ```c void BPF_STRUCT_OPS(mysched_dispatch, s32 cpu, struct task_struct *prev) { scx_bpf_consume(/* queue id = */ 0); } ``` Global FIFO works surprisingly well on single socket / CCX machines - Work conserving - Very, very simple - 155 lines of code const volatile bool switch_partial; /* Can be set by user space before loading the program. */ s32 BPF_STRUCT_OPS(simple_init) { if (!switch_partial) /* If set, tasks will individually be configured to use the SCHED_EXT class. */ scx_bpf_switch_all(); /* Switch all CFS tasks to use sched_ext. */ return 0; } void BPF_STRUCT_OPS(simple_enqueue, struct task_struct *p, u64 enq_flags) { if (enq_flags & SCX_ENQ_LOCAL) /* SCX_ENQ_LOCAL could be set if e.g. the current CPU has no other tasks to run. */ scx_bpf_dispatch(p, SCX_DSQ_LOCAL, enq_flags); /* Dispatch task to the head of the current CPU’s local FIFO. */ else scx_bpfDispatch(p, SCX_DSQ_GLOBAL, enq_flags); /* Dispatch task to the global FIFO, it will be consumed automatically by ext. */ } void BPF_STRUCT_OPS(simple_exit, struct scx_exit_info *ei) { bpf_printk("Exited"); /* Can do more complicated things here like setting flags in user space, etc. */ } SEC(".struct_ops") struct sched_ext_ops simple_ops = { .enqueue = (void *)simple_enqueue, .init = (void *)simple_init, .exit = (void *)simple_exit, .name = "simple", }; Not pictured: selecting a core in \texttt{ops.select_cpu()} callback - Default implementation if not defined is to pick an idle core using the following priority order: - Waking core, if it would otherwise go idle - When SMT is enabled, a wholly idle core with no hypertwin running - Any idle CPU in the system - If core is idle, an IPI is automatically sent to wake it up - Whichever CPU is specified here is where the \texttt{ops.enqueue()} callback is eventually invoked Example 1: Per-CCX FIFO – enqueuing - Exact same idea as global FIFO, but on a per-CCX granularity - A core “dispatches” tasks to the DSQ for its CCX / L3 cache - And “consumes” from it when going to idle - Cores pull from their CCX’s DSQ - Better L3 cache locality - Unlike global FIFO, *not* work conserving - What if one CCX’s DSQ runs out, but the other has work? Many possibilities - Always steal only if your CCX’s DSQ is empty - Only steal if the other DSQ has X tasks enqueued - Only steal if user space marked the task as special and always steal-able? - ... - Correct answer is: run experiments with sched_ext to see what works. 03 Example schedulers Meta-developed Schedulers Rusty: https://github.com/sched-ext/sched_ext/tree/sched_ext/tools/sched_ext/scx_rusty Simple: https://github.com/sched-ext/sched_ext/blob/sched_ext/tools/sched_ext/scx_simple.bpf.c Flatcg: https://github.com/sched-ext/sched_ext/blob/sched_ext/tools/sched_ext/scx_flatcg.bpf.c scx_rustland by Andrea Righi Prioritizes interactive workloads over CPU-intensive workloads Kernel is building (make -j32) Default Linux scheduler ~25-30 fps scx_rustland scheduler ~60 fps scx_rusty - Multi-domain BPF / user space hybrid scheduler - BPF portion is simple. Hot paths do round robin on each domain - User space portion written in rust. Contains more complex and substantial logic of load balancing, etc. - Suitable for production workloads. Has parity with CFS on multi-domain (NUMA, CCX, etc) hosts for HHVM scx_simple - Example scheduler showed earlier - A simple weighted vtime / global FIFO - About 200 lines total, including user space code, stats collection, etc. - May not always be suitable for production - Only performant on single-socket, uniform L3 cache architectures scx_flatcg - Flattened cgroup hierarchy scheduler - Implements performant, hierarchical weight-based cgroup CPU control by flattening cgroup hierarchy - Vulnerable to cgroup thundering herd inaccuracies - If many low-pri cgroups wake at the same time, they may get excess of CPU Next: example schedulers - Not meant to be used in production environments (yet) - Used to illustrate various sched_ext features - Can be forked to create your own, or improved upon and made production worthy Qmap: [https://github.com/sched-ext/sched_ext/blob/sched_ext/tools/sched_ext/scx_qmap.bpf.c](https://github.com/sched-ext/sched_ext/blob/sched_ext/tools/sched_ext/scx_qmap.bpf.c) Central: Pair: Userland: ### Example schedulers #### scx_qmap - Simple five-level FIFO queue scheduler - Slightly more complex than scx_simple, still very simple - Has no practical use, just useful for demonstrating features in a simple way - About 500 lines total, including comments, user space, stats collection, etc #### scx_central - A “central” scheduler making (almost) all scheduling decisions from a single CPU, on a tickless system - Possibly useful for workloads that could benefit from fewer timer interrupts or less scheduling overhead - VMs / cloud environment - Not usable for production in its current form - Not NUMA aware, resched IPIs sent every 20ms #### scx_pair - Demo scheduler that only schedules tasks in the same cgroup on a sibling CPU pair - Doesn’t have any priority handling inside or across cgroups. Would need to be added to be practically useful - Example of what could have been a stop-gap solution for L1TF before core scheduling was merged #### scx_userland - Simple vtime scheduler that makes all scheduling decisions in user space - Not production ready — uses an ordered list for vtime, not NUMA aware Minimum system requirements - Kernel compiled from repo (https://github.com/sched-ext/sched_ext) - .config options enabled: - CONFIG_SCHED_CLASS_EXT=y - CONFIG_DEBUG_INFO_BTF=y - CONFIG_BPF=y - CONFIG_BPF_SYSCALL=y - CONFIG_BPF_JIT=y - ...and any dependencies - clang >= 16.0.0 - gcc support hopefully coming soon, but it doesn’t yet fully support BPF in general - pahole >= 1.24 - rustup nightly (if you want to compile the scx_rusty scheduler) - See https://github.com/sched-ext/sched_ext/blob/sched_ext/tools/sched_ext/README for more information 04 Current status and future plans Upstream first philosophy - Developers need to first merge bug fixes or features upstream before using it internally. - General workflow is typically: 1. Debug issue and/or write patches, send upstream 2. Iterate with upstream community until patches are merged 3. Backport to Meta kernel(s) - Allows us to follow latest upstream kernel closely (rolling out 6.4 to production now) Top priority for sched_ext is upstreaming it - Still iterating with members of the upstream community and incorporating feedback - We are committed to getting sched_ext upstreamed as long as it takes - Latest v5 patch set (https://lore.kernel.org/all/2023111024835.2164816-1-tj@kernel.org/T/#u): - New example schedulers (scx_flatcg, overhauled rusty) - Google committed to building ghOSt on top of sched_ext [0] - Manipulating and querying cpumasks directly from BPF (struct bpf_cpumask *) - Adding rbtree / priority queue semantics to DSQs - ops.set_weight() callback added to allow schedulers to lazily track weight changes - Using new BPF iterator feature instead of bpf_loop() - Lots of bug fixes [0]: https://lore.kernel.org/all/CABk29Nt_iCv=2nbDUqFHSszMmDYNC7xEm1nNQXibnPKUxhsN_g@mail.gmail.com/ New features - Not much planned at the moment in terms of more sched_ext features. Mostly BPF (described below) - Would prefer to see what people need before adding more complexity - Currently rolling out to production at Meta - More example / upstreamed schedulers - Power-aware - Latency nice - Soft-affinity - Adding new BPF features - “Polymorphic” kfuncs — allowing BPF progs to call the same kfunc symbol, but have it be resolved to different implementation depending on context - Nested struct_ops - Enable different policies to be used on different partitions of a host - Calling into kfuncs with `struct bpf_spin_lock` held - Using assertions to simplify logic to appease verifier Links - Main repo: https://github.com/sched-ext/sched_ext - Latest upstream patch set (v5): https://lore.kernel.org/all/20231111024835.2164816-1-tj@kernel.org/T/#u - Example schedulers: https://github.com/sched-ext/scx/tree/main - sched_ext documentation: Appendix – useful supplementary info Flowchart illustrating how a newly runnable task becomes enqueued in the BPF scheduler. - Entering scheduler - Blocking (io DEVICE, ev Asynchronous, etc.) - Manual retried (e.g. scheduled) or cond (check)</s - On return to user space or if awakened, switched to set in p-flags - Is task waking up? - Yes: s32 (tasklet_cpu)(struct task_struct *p, s32 prev_cpu, u64 wake_flags): - Migrate to selected CPU - Task becomes runnable - void (*enqueue)(struct task_struct *p, u64 enq_flags): - Task enqueued in the CPU's local DSQ - Task dispatched directly to CPU? - Yes: Task enqueued in the BPF scheduler - No: Task enqueued in the BPF scheduler Diagram legend: - Scheduler callback – function implemented by scheduler developer in BPF - kfunc – function called from BPF program Ending action that returned true or with success - Task(s) successfully balanced to core - No tasks to run, core goes idle - Were any tasks dispatched in the dispatch callback above? - Yes: void sxc_tdp dispatch(struct task_struct *p, u64 dsq_id, u64 nice, u64 enq_flags): - book sxc tdp consume(u64 dsq_id): - No: Dispatch task to DSQ - Consume task from DSQ to local CPU - Can be called from BPF one or more times - void (*dispatch)(u32 cpu, struct task_struct *prev): Start balance pass - Does the CPU have locally dispatched tasks? - Yes: Dispatch task to DSQ - No: void sxc_tdp dispatch(struct task_struct *p, u64 dsq_id, u64 nice, u64 enq_flags): - book sxc tdp consume(u64 dsq_id):
{"Source-Url": "https://www.socallinuxexpo.org/sites/default/files/presentations/Sched%20Ext%20-%20SCaLE%2021x.pdf", "len_cl100k_base": 5286, "olmocr-version": "0.1.53", "pdf-total-pages": 68, "total-fallback-pages": 0, "total-input-tokens": 73216, "total-output-tokens": 7918, "length": "2e12", "weborganizer": {"__label__adult": 0.00027298927307128906, "__label__art_design": 0.000247955322265625, "__label__crime_law": 0.00018978118896484375, "__label__education_jobs": 0.0003840923309326172, "__label__entertainment": 5.6624412536621094e-05, "__label__fashion_beauty": 9.936094284057616e-05, "__label__finance_business": 0.00019299983978271484, "__label__food_dining": 0.00024247169494628904, "__label__games": 0.0005469322204589844, "__label__hardware": 0.0019779205322265625, "__label__health": 0.0002911090850830078, "__label__history": 0.0001875162124633789, "__label__home_hobbies": 8.809566497802734e-05, "__label__industrial": 0.0004298686981201172, "__label__literature": 0.00011664628982543944, "__label__politics": 0.0001932382583618164, "__label__religion": 0.00037169456481933594, "__label__science_tech": 0.0219268798828125, "__label__social_life": 5.8591365814208984e-05, "__label__software": 0.007724761962890625, "__label__software_dev": 0.9638671875, "__label__sports_fitness": 0.0002287626266479492, "__label__transportation": 0.00035500526428222656, "__label__travel": 0.00016057491302490234}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 21340, 0.01556]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 21340, 0.35996]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 21340, 0.82205]], "google_gemma-3-12b-it_contains_pii": [[0, 73, false], [73, 223, null], [223, 252, null], [252, 277, null], [277, 502, null], [502, 529, null], [529, 598, null], [598, 671, null], [671, 1030, null], [1030, 1065, null], [1065, 1423, null], [1423, 1808, null], [1808, 2075, null], [2075, 2197, null], [2197, 2398, null], [2398, 2658, null], [2658, 2929, null], [2929, 3330, null], [3330, 3732, null], [3732, 4195, null], [4195, 4791, null], [4791, 4810, null], [4810, 5192, null], [5192, 5215, null], [5215, 5585, null], [5585, 6007, null], [6007, 6346, null], [6346, 6607, null], [6607, 6803, null], [6803, 6828, null], [6828, 7284, null], [7284, 7643, null], [7643, 8342, null], [8342, 8380, null], [8380, 8807, null], [8807, 9478, null], [9478, 9902, null], [9902, 9986, null], [9986, 10070, null], [10070, 10285, null], [10285, 10558, null], [10558, 10850, null], [10850, 10955, null], [10955, 11111, null], [11111, 11274, null], [11274, 11476, null], [11476, 12623, null], [12623, 13106, null], [13106, 13312, null], [13312, 13768, null], [13768, 13790, null], [13790, 14189, null], [14189, 14351, null], [14351, 14382, null], [14382, 14417, null], [14417, 14448, null], [14448, 15352, null], [15352, 15770, null], [15770, 16894, null], [16894, 17459, null], [17459, 17494, null], [17494, 17884, null], [17884, 18703, null], [18703, 19412, null], [19412, 19763, null], [19763, 19763, null], [19763, 19800, null], [19800, 21340, null]], "google_gemma-3-12b-it_is_public_document": [[0, 73, true], [73, 223, null], [223, 252, null], [252, 277, null], [277, 502, null], [502, 529, null], [529, 598, null], [598, 671, null], [671, 1030, null], [1030, 1065, null], [1065, 1423, null], [1423, 1808, null], [1808, 2075, null], [2075, 2197, null], [2197, 2398, null], [2398, 2658, null], [2658, 2929, null], [2929, 3330, null], [3330, 3732, null], [3732, 4195, null], [4195, 4791, null], [4791, 4810, null], [4810, 5192, null], [5192, 5215, null], [5215, 5585, null], [5585, 6007, null], [6007, 6346, null], [6346, 6607, null], [6607, 6803, null], [6803, 6828, null], [6828, 7284, null], [7284, 7643, null], [7643, 8342, null], [8342, 8380, null], [8380, 8807, null], [8807, 9478, null], [9478, 9902, null], [9902, 9986, null], [9986, 10070, null], [10070, 10285, null], [10285, 10558, null], [10558, 10850, null], [10850, 10955, null], [10955, 11111, null], [11111, 11274, null], [11274, 11476, null], [11476, 12623, null], [12623, 13106, null], [13106, 13312, null], [13312, 13768, null], [13768, 13790, null], [13790, 14189, null], [14189, 14351, null], [14351, 14382, null], [14382, 14417, null], [14417, 14448, null], [14448, 15352, null], [15352, 15770, null], [15770, 16894, null], [16894, 17459, null], [17459, 17494, null], [17494, 17884, null], [17884, 18703, null], [18703, 19412, null], [19412, 19763, null], [19763, 19763, null], [19763, 19800, null], [19800, 21340, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 21340, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 21340, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 21340, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 21340, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 21340, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 21340, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 21340, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 21340, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 21340, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 21340, null]], "pdf_page_numbers": [[0, 73, 1], [73, 223, 2], [223, 252, 3], [252, 277, 4], [277, 502, 5], [502, 529, 6], [529, 598, 7], [598, 671, 8], [671, 1030, 9], [1030, 1065, 10], [1065, 1423, 11], [1423, 1808, 12], [1808, 2075, 13], [2075, 2197, 14], [2197, 2398, 15], [2398, 2658, 16], [2658, 2929, 17], [2929, 3330, 18], [3330, 3732, 19], [3732, 4195, 20], [4195, 4791, 21], [4791, 4810, 22], [4810, 5192, 23], [5192, 5215, 24], [5215, 5585, 25], [5585, 6007, 26], [6007, 6346, 27], [6346, 6607, 28], [6607, 6803, 29], [6803, 6828, 30], [6828, 7284, 31], [7284, 7643, 32], [7643, 8342, 33], [8342, 8380, 34], [8380, 8807, 35], [8807, 9478, 36], [9478, 9902, 37], [9902, 9986, 38], [9986, 10070, 39], [10070, 10285, 40], [10285, 10558, 41], [10558, 10850, 42], [10850, 10955, 43], [10955, 11111, 44], [11111, 11274, 45], [11274, 11476, 46], [11476, 12623, 47], [12623, 13106, 48], [13106, 13312, 49], [13312, 13768, 50], [13768, 13790, 51], [13790, 14189, 52], [14189, 14351, 53], [14351, 14382, 54], [14382, 14417, 55], [14417, 14448, 56], [14448, 15352, 57], [15352, 15770, 58], [15770, 16894, 59], [16894, 17459, 60], [17459, 17494, 61], [17494, 17884, 62], [17884, 18703, 63], [18703, 19412, 64], [19412, 19763, 65], [19763, 19763, 66], [19763, 19800, 67], [19800, 21340, 68]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 21340, 0.0]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
eee499cd24cedc4855ca88619babfa28c4b9b3f0
State Space Methods in RATS Technical Paper No. 2010-2 Thomas A. Doan * January 2010 *Estima, 1560 Sherman Ave #510, Evanston, IL 60201 USA, email: tomd@estima.com Prepared for special issue of the Journal of Statistical Software on software packages for state space time series analysis. 1 Introduction RATS is a general-purpose econometrics and programming package, with a specialty in time series analysis. The instruction in RATS for handling state space models is called DLM (for Dynamic Linear Models). This was introduced with version 5.00 in 2001. Since then, there have been many improvements. With version 8, the instruction has the following features: - All component matrices can be fixed matrices, or time-varying formulas, or can be computed using functions of arbitrary complexity. - Multiple observables ($y_t$ with dimension $>1$) are permitted, with proper handling of situations where some components are missing, but some are present. - Non-stationary roots in the transition matrix are treated with the “exact” (limit) methods of Koopman (1997) and Durbin and Koopman (2002). The transition matrix is analyzed automatically for stationary and non-stationary roots. - The ergodic variance for the stationary (linear combinations of) states is computed using the efficient Schur decomposition method described in Doan (2010). - The calculations of the Kalman filter and smoother can switch under user control to use the last calculated values of the Kalman gain and predictive variances to save time in large models with time-invariant component matrices. With the RATS distribution, we include the worked examples from several textbooks devoted to space-space models, including Durbin and Koopman (2002), Commandeur and Koopman (2007) and West and Harrison (1997). These are also posted on our web site at [www.estima.com/textbookindex.shtml](http://www.estima.com/textbookindex.shtml). Our state space structure takes a bit broader form than the one described in the introduction to this issue. Because the components are input to the DLM instruction using short alphabetical names based upon our own description of the state space model, we will use that from this point on in this article: \[ X_t = A_t X_{t-1} + Z_t + F_t w_t \quad (1) \] \[ Y_t = \mu_t + C_t' X_t + v_t \quad (2) \] The addition of the $\mu_t$ term to the measurement equation is only a minor matter of convenience, since the identical model can be produced by subtracting $\mu_t$ from both sides of the equation. However, the enhanced form of the state equation with the $Z_t$ state shift can’t so easily be accommodated in the simpler form, particularly when the state shift component is time-varying. Given a state space model, you can choose to: 1. Note that RATS uses a different timing on the components in the state equation. Kalman filter, computing the likelihood function assuming Gaussian errors; this also computes predictions for the states and the observables, the prediction errors and variances for the predictions and states. Kalman smooth, with calculations of smoothed states and their variances, disturbances and their variances. Simulate unconditionally, with random draws for the state and measurement shocks, producing simulated states and observables. Simulate conditional on observed data, producing simulated states and shocks. A recent addition to RATS is the instruction DSGE, which takes a model with expectational terms and solves it symbolically for a backwards-looking state space representation. The combination of DSGE and DLM can be used to evaluate the likelihood (for Gibbs sampling) or directly estimate by maximum likelihood the deep parameters in a DSGE. This paper is organized as follows. Section 2 introduces the model used in the example. Section 3 demonstrates Kalman smoothing, given values for the variances. Section 4 shows the various ways to estimate the hyperparameters (variances). Section 5 discusses several types of calculated or graphed diagnostics for the state space model. Section 6 shows how to forecast out-of-sample and Section 7 offers examples of the use of both unconditional and conditional simulations. In all cases, we are providing only the segment of code needed to demonstrate a technique. The full running examples are available on our web site at www.estima.com/resources_articles.shtml. 2 The example The model that we’ll use for the examples is the local level model, applied to the Nile flow data, annual from 1871 to 1970. The model is \[ y_t = \alpha_t + \varepsilon_t \] \[ \alpha_t = \alpha_{t-1} + \eta_t \] where \( \alpha_t \) is the unobservable local level. The model has time-invariant components \( A = C = F = 1 \), \( Z = \mu = 0 \). These are the default values for all but \( C \). The measurement error variance \( \sigma^\varepsilon_t^2 \) is input using the SV option, while the state shock variance \( \sigma^\eta_t^2 \) comes in through the SW option. As with other Unobserved Components (UC) models, the state has non-stationary dynamics. To handle the initial conditions, we can use the option PRESAMPLE=DIFFUSE, which indicates that the initial condition for the state is fully diffuse. This is implemented using the “exact” method of Koopman (1997) and Durbin and Koopman (2002). The same outcome will be obtained using the more flexible PRESAMPLE=ERGODIC, which analyzes the transition matrix and determines its roots. 3 Kalman Smoothing For now, we’ll take the component variances as given, and discuss estimation in Section 4. We’ll peg them at $\sigma^2_\xi = 15099$ and $\sigma^2_\eta = 1469.1$ which are the maximum likelihood values. The instruction for Kalman smoothing with the Nile data is: ``` dlm(a=1.0,c=1.0,sv=15099.0,sw=1469.1,presample=diffuse,y=nile,$ type=smooth) / xstates vstates ``` **TYPE=SMOOTH** chooses Kalman smoothing. The default analysis is Kalman filtering—the extra calculations for Kalman smoothing aren’t done unless requested. The **XSTATES** parameter gets the smoothed state estimates and **VSTATES** gets the smoothed state variances. Since the state vector is (in almost all cases) bigger than a single element, **XSTATES** is a time series of vectors and **VSTATES** is a time series of (symmetric) matrices. Code for generating 90% confidence intervals and graphing them is given next: ``` set a = %scalar(xstates) set p = %scalar(vstates) set lower = a+sqrt(p)*%invnormal(.05) set upper = a+sqrt(p)*%invnormal(.95) graph(footer="Figure 1. Smoothed state and 90% confidence intervals") 4 # nile # a # lower / 3 # upper / 3 ``` **SET** is the main **RATS** instruction for creating and transforming time series. The **%SCALAR** function selects the first element out of a vector or matrix, so the series **A** will be the time series of estimated states, and **P** the time series of estimated variances. **GRAPH** is the time series graphing instruction; the / 3 on the last two lines forces the upper and lower bounds to use the same color or pattern. The graph produced by this is Figure 1. 4 Estimation of Hyperparameters The **DLM** instruction will always, as a side effect, compute the log likelihood of the model given the input variances. This can be maximized, with a wide range of choices for optimization, allowing for both derivative-based hill-climbing techniques, and slower but more flexible search methods. It also has the ability to (easily) incorporate equality or inequality constraints. One way to estimate the two variances in the local level model is: The `NONLIN` instruction declares the set of free parameters to be estimated—here, that's $\psi = \log \left( \frac{\sigma^2}{\sigma^2_e} \right)$. The measurement error variance is concentrated out, which can sometimes be helpful in improving the behavior of difficult estimation problems. The estimation method being used here is the hill-climbing method BFGS. The output is shown in Table 1. Note that, while there are 100 data points, the likelihood is calculated using only the final 99 of them. This is done automatically here because of the diffuse initial conditions—the predictive variance for observation 1 is infinite, and so it's dropped from the calculation of the likelihood. `DLM` has an additional option `CONDITION` which can control the number of data points which are included in the filtering calculations, but omitted from the likelihood used for estimation. This is generally not needed, since `DLM` handles the diffuse states automatically, but is useful when the number of non-stationary states isn’t known a priori, if, for instance, autoregressive parameters are being estimated. Both variances can also be estimated directly with: ```plaintext nonlin sigsqeps sigsqeta stats(noprint) nile compute sigsqeps=.5*%variance,sigsqeta=.1*sigsqeps * dlm(a=1.0,c=1.0,sv=sigsqeps,sw=sigsqeta,y=nile,${ method=bfgs,presample=diffuse,admissible=concentrate}) ``` Direct estimation of the variances requires a bit more care with guess values. This DLM - Estimation by BFGS Convergence in 6 Iterations. Final criterion was 0.0000001 <= 0.0000100 Annual Data From 1871:01 To 1970:01 Usable Observations 100 Rank of Observables 99 Log Likelihood -632.54563 Concentrated Variance 15098.51951564 <table> <thead> <tr> <th>Variable</th> <th>Coeff</th> <th>Std Error</th> <th>T-Stat</th> <th>Signif</th> </tr> </thead> <tbody> <tr> <td>1. PSI</td> <td>-2.329895195</td> <td>1.012133212</td> <td>-2.30196</td> <td>0.02133715</td> </tr> </tbody> </table> Table 1: Estimation with Concentrated Variance uses scalings of the series sample variance, which should get the order of magnitude correct. The output is in Table 2. DLM - Estimation by BFGS Convergence in 9 Iterations. Final criterion was 0.0000000 <= 0.0000100 Annual Data From 1871:01 To 1970:01 Usable Observations 100 Rank of Observables 99 Log Likelihood -632.54563 <table> <thead> <tr> <th>Variable</th> <th>Coeff</th> <th>Std Error</th> <th>T-Stat</th> <th>Signif</th> </tr> </thead> <tbody> <tr> <td>1. SIGSQEPS</td> <td>15098.510028</td> <td>3126.130999</td> <td>4.82978</td> <td>0.00000137</td> </tr> <tr> <td>2. SIGSQETA</td> <td>1469.172357</td> <td>1266.235944</td> <td>1.16027</td> <td>0.24593993</td> </tr> </tbody> </table> Table 2: Estimation with Both Variances While not important here, the NONLIN instruction can also handle various constraints on the parameters, either equality or inequality. With no change to the setup, we could estimate this with \( \sigma_\eta^2 \) pegged to zero (which here gives a model with a fixed mean) using \[ \text{nonlin sigsqeps sigsqeta}=0.0 \] \[ \text{dlm(a=1.0,c=1.0,sv=sigsqeps,sw=sigsqeta,y=nile,}$ \] \[ \text{method=bfgs,presample=diffuse) 1871:1 1970:1} \] In a more complex model, where there is some chance that a component variance might be zero, the NONLIN instruction can be used to set an inequality constraint: \[ \text{nonlin sigsqeps sigsqeta}>=0.0 \] \[ \text{dlm(a=1.0,c=1.0,sv=sigsqeps,sw=sigsqeta,y=nile,}$ \] \[ \text{method=bfgs,presample=diffuse) 1871:1 1970:1} \] This uses a penalty function variation on BFGS. Since it’s quite a bit slower than standard BFGS, we generally don’t recommend using it unless the simpler unconstrained estimates fail to provide values in range. The equality constraints from the previous case, on the other hand, are done by taking the constrained parameter out of the parameter set and using standard BFGS, so it actually runs faster than unconstrained BFGS. 5 Diagnostics The most straightforward diagnostics come from the standardized residuals. These can be computed with the help of the \texttt{VHAT} and \texttt{SVHAT} options. \texttt{VHAT} is used to fetch the measurement errors and \texttt{SVHAT} the predictive variance. Again, these will be in the form of a \texttt{VECTOR} (for \texttt{VHAT}) and a \texttt{SYMMETRIC} matrix (for \texttt{SVHAT}) to allow for the possibility of multiple observables. The following generates standardized predictive errors (into the series \texttt{EHAT}), graphs them (Figure 2) and does a standard set of diagnostics on the recursive residuals (output in Table 3): ```r dlm(a=1.0,c=1.0,sv=sigsqeps,sw=sigsqeta,y=nile,$ method=bfgs,presample=diffuse,$ vhat=vhat,svhat=svhat) 1871:1 1970:1 set ehat = %scalar(vhat)/sqrt(%scalar(svhat)) graph(footer="Standardized residual",vgrid=||-2.0,2.0||) # ehat @STAMPDiags(ncorrs=9) ehat ``` The \texttt{VGRID=||-2.0,2.0||} option on the \texttt{GRAPH} puts the horizontal lines at ±2. Note that, because of the diffuse prior, the first standardized error is omitted. This is handled automatically in the code because the \texttt{SVHAT} for 1871:1 is a missing value. The diagnostics in Table 3 include a Ljung-Box Q test for serial correlation, a Jarque-Bera normality test and a Goldfeld-Quandt style test for heteroscedasticity. The \texttt{STAMPDiags} procedure also produces the graph of autocorrelations seen in Figure 3. \cite{Durbin and Koopman} (2002) recommend also computing auxiliary residuals, which Statistic Sig. Level <table> <thead> <tr> <th>Statistic</th> <th>Value</th> <th>Level</th> </tr> </thead> <tbody> <tr> <td>Q(9-1)</td> <td>8.84</td> <td>0.3557</td> </tr> <tr> <td>Normality</td> <td>0.12</td> <td>0.9441</td> </tr> <tr> <td>H(33)</td> <td>0.61</td> <td>0.1650</td> </tr> </tbody> </table> **Table 3: State Space Model Diagnostics** Residual Analysis ![Residual Analysis Graph] **Figure 3: Autocorrelations of prediction errors** are the Kalman smoothed estimates for the measurement errors and state disturbances. Large values for these can help identify outliers (in the measurement errors) or structural shifts (in the state disturbances). These can be obtained using the `vhat` and `what` options when Kalman smoothing. The results returned from those are standardized to mean zero, unit variance. ```r dlm(a=1.0,c=1.0,sv=sigsgreps,sw=sigsgeta,y=nile, type=smooth,presample=diffuse, vhat=vhat,what=what) ``` * set outlier = %scalar(vhat) diff(standardize) outlier set break = %scalar(what) diff(standardize) break The following graphs both of these. This uses `spgraph` instructions to create a graph page with two panes. The result is Figure 4. Figure 4: Diagnostic plots for auxiliary residuals spgraph(vfields=2,$ footer="Diagnostic plots for auxiliary residuals") graph(vgrid=||-2.0,2.0||,hlabel="Observation residual") # outlier graph(vgrid=||-2.0,2.0||,hlabel="State residual") # break spgraph(done) 6 Forecasts Out-of-sample forecasts can be generated by simply running a Kalman filter past the end of the data set. When the Y value is missing, DLM does the Kalman “update” step but not the “correction”. This is how embedded missing values are handled. For out-of-sample forecasts, however, it’s generally more straightforward to Kalman filter through the observed data, then run a separate filter into the forecast range. This next code segment uses the X0 and SX0 options to feed in the final estimated mean and variance for the states (from Kalman filtering over the sample) into the Kalman filter for the forecast range. The YHAT and SVHAT options are used to get the prediction and the predictive error variance for the dependent variable. You can also get the predicted value of the state and its predictive variance using the standard state parameters. The following organizes a graph of the forecasts with their 50% confidence interval. Only forty years of actual data are included to give the forecast range enough space. This produces Figure 5. 7 Simulations There are two choices for random simulations of a model: TYPE=SIMULATE chooses unconditional simulation, where shocks for the states and measurements are drawn independently, and TYPE=CSIMULATE, where they are drawn subject to the requirement that the observed data are produced. TYPE=SIMULATE would generally be used in out-of-sample operations, while TYPETE=CSIMULATE is especially useful for Gibbs sampling, since it draws a set of shocks and states conditional on the data and other parameters. The following is an example of unconditional simulation. First, Kalman filtering is used through the observed range of the data to get the end-of-period estimates of the mean and variance of the state. Then 10000 realizations for the process over the next fifty periods are generated. The maximum flow for each realization is recorded. The percentiles are computed once the simulations are done. This could be used, for instance, to estimate the level for 50-year or 100-year floods. dlm(a=1.0,c=1.0,sv=15099.0,sw=1469.1,$ type=filter) / xstates vstates compute ndraws=10000 set maxflow 1 ndraws = 0.0 do reps=1,ndraws dlm(a=1.0,c=1.0,sv=15099.0,sw=1469.1,$ x0=xstates(1970:1),sx0=vstates(1970:1),$n type=simulate,yhat=yhat) 1971:1 2020:1 xstates set simflow 1971:1 2020:1 = %scalar(yhat) end do reps stats(fractiles,nomoments) maxflow Statistics on Series MAXFLOW Observations 10000 Minimum 646.279562 Maximum 2277.525740 01-%ile 797.704496 99-%ile 1664.309419 05-%ile 884.530943 95-%ile 1498.885021 10-%ile 933.496769 90-%ile 1409.103502 25-%ile 1024.542961 75-%ile 1274.081468 Median 1135.600473 Table 4: Percentiles from Maximum Simulated Flows The following is an example of the use of conditional simulation for Gibbs sampling. The two hyperparameters are modeled as the precision $h$ of the measurement error and the relative variance $\psi$ of the state shock to the measurement error. The two hyperparameters are given very loose priors, with $h$ being inverse gamma with 1 degree of freedom and $\psi$ being gamma with 1 degree of freedom. calculate nuh=1.0 calculate s2h=100.0^2 calculate hdraw=nuh/s2h *calculate nupsi=1.0 calculate s2psi=.1 calculate psidraw=s2psi/nupsi In the example, the Gibbs sampler is run with 100 burn-in draws and 2000 keeper draws. DLM with TYPE=CSIMULATE does a draw from the joint distribution of the measurement error and state disturbances subject to the simulated data hitting the observed values for Y. The WHAT and VWHAT options are used to get the simulated values of the disturbances, while the states parameter gets the simulated values of the states. This does the simulation conditional on the current draws for \( h \) and \( \psi \). \[ \text{dlm(a=1.0,c=1.0,sv=1.0/hdraw,sw=psidraw/hdraw,y=nile,}$ \text{type=csimulate,presample=diffuse,$$ \text{what=what,vhat=vhat) / xstates} \] The hyperparameters are then drawn conditional on the just-created draws for the disturbances. First \( \psi \): \[ \text{sstats / vhat(t)(1)^2>>sumvsq what(t)(1)^2>>sumwsq} \] \[ \text{compute psidraw=(hdraw*sumwsq+nupsi*s2psi)/%ranchisqr(%nobs+nupsi)} \] then \( h \): \[ \text{compute hdraw=}$ \text{ %ranchisqr(nuh+%nobs*2.0)/(nuh+s2h+sumvsq+sumwsq/psidraw)} \] Estimates of the local level and its 90% confidence interval are shown in Figure 6. This is similar to Figure 1 but allows for the fact that the hyperparameters are estimated, and not known. **Figure 6: Local level and 90% CI from Gibbs sampling** 8 Conclusion This paper has used a simple example to give a taste of how RATS can be used to work with state space models. The DLM instruction has many options, allowing it to handle a wide range of tasks. Its internal calculations for filtering, smoothing and simulation have been highly optimized. When combined with the programming flexibility of the RATS package, many models which are quite cumbersome when done with matrix languages or less flexible packages can be done simply and quickly. We invite you to check our web site or e-mail us for more information. References
{"Source-Url": "https://estima.com/articles/TP2010-2%20State%20Space%20Introduction.pdf", "len_cl100k_base": 5253, "olmocr-version": "0.1.50", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 27928, "total-output-tokens": 6226, "length": "2e12", "weborganizer": {"__label__adult": 0.000270843505859375, "__label__art_design": 0.00057220458984375, "__label__crime_law": 0.00042629241943359375, "__label__education_jobs": 0.0012378692626953125, "__label__entertainment": 0.00014102458953857422, "__label__fashion_beauty": 0.0001786947250366211, "__label__finance_business": 0.0009222030639648438, "__label__food_dining": 0.0004220008850097656, "__label__games": 0.0006537437438964844, "__label__hardware": 0.0012044906616210938, "__label__health": 0.0006103515625, "__label__history": 0.0004911422729492188, "__label__home_hobbies": 0.00022530555725097656, "__label__industrial": 0.0010976791381835938, "__label__literature": 0.0002760887145996094, "__label__politics": 0.0005102157592773438, "__label__religion": 0.0004062652587890625, "__label__science_tech": 0.426025390625, "__label__social_life": 0.0001806020736694336, "__label__software": 0.04095458984375, "__label__software_dev": 0.52197265625, "__label__sports_fitness": 0.00037789344787597656, "__label__transportation": 0.0006012916564941406, "__label__travel": 0.0002541542053222656}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 19979, 0.07287]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 19979, 0.50746]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 19979, 0.82353]], "google_gemma-3-12b-it_contains_pii": [[0, 292, false], [292, 2836, null], [2836, 5433, null], [5433, 7551, null], [7551, 9022, null], [9022, 11149, null], [11149, 12864, null], [12864, 13922, null], [13922, 15060, null], [15060, 15672, null], [15672, 17472, null], [17472, 18744, null], [18744, 19979, null]], "google_gemma-3-12b-it_is_public_document": [[0, 292, true], [292, 2836, null], [2836, 5433, null], [5433, 7551, null], [7551, 9022, null], [9022, 11149, null], [11149, 12864, null], [12864, 13922, null], [13922, 15060, null], [15060, 15672, null], [15672, 17472, null], [17472, 18744, null], [18744, 19979, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 19979, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 19979, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 19979, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 19979, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 19979, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 19979, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 19979, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 19979, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 19979, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 19979, null]], "pdf_page_numbers": [[0, 292, 1], [292, 2836, 2], [2836, 5433, 3], [5433, 7551, 4], [7551, 9022, 5], [9022, 11149, 6], [11149, 12864, 7], [12864, 13922, 8], [13922, 15060, 9], [15060, 15672, 10], [15672, 17472, 11], [17472, 18744, 12], [18744, 19979, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 19979, 0.0543]]}
olmocr_science_pdfs
2024-11-28
2024-11-28
0685238deee6432d24f772f6a1dde609c9c57bc5
Assembly output codes for learning neural networks Philippe Tigréat, Carlos Rosar Kos Lassance, Xiaoran Jiang, Vincent Gripon, Claude Berrou To cite this version: HAL Id: hal-01502488 https://hal.archives-ouvertes.fr/hal-01502488 Submitted on 5 Apr 2017 HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers. L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés. Assembly Output Codes for Learning Neural Networks Philippe Tigréat*, Carlos Rosar Kos Lassance*, Xiaoran Jiang**, Vincent Gripon*, Claude Berrou* *Electronics Department, Télécom Bretagne **INRIA Rennes *name.surname@telecom-bretagne.eu, **name.surname@inria.fr Abstract—Neural network-based classifiers usually encode the class labels of input data via a completely disjoint code, i.e., a binary vector with only one bit associated with each category. We use coding theory to propose assembly codes where each element is associated with several classes, making for better target vectors. These codes emulate the combination of several classifiers, which is a well-known method to improve decision accuracy. Our experiments on data-sets such as MNIST with a multi-layer neural network show that assembly output codes, which are characterized by a higher minimum Hamming distance, result in better classification performance. These codes are also well suited to the use of clustered clique-based networks in category representation. Keywords—Assembly coding; Clustered Clique Networks; ECOC; Deep Learning; Coding theory; Classification 1. INTRODUCTION Automatic learning systems are different from storing systems in that they aim at generalizing to unknown inputs. This happens through the extraction of the core features of learned data, and works as long as the unknown data to extrapolate to follows a similar distribution. The system thus learns a dictionary of features that is targeted to be well suited for the task at hand, e.g., classification. These features are meant to correspond to the most relevant building blocks underlying the training inputs, that unseen data samples would likely also be made of. In supervised Deep Learning networks, an output is calculated through a pipeline of vector-matrix products between input data and connection weights, intertwined with non-linear mathematical operators. Each level of the network is associated with a set of features that is more and more abstract as one moves towards the upper layers. During learning, an error is calculated from the difference between the resulting output and an objective vector specific to the class of the input. A gradient is then calculated from this error for the whole set of connection weights, and the hierarchy of features thus gets optimized through gradient descent for the task of classifying the data-set examples. Combining classifiers has been an extensive area of research for a few decades [1] and several algorithms have been shown to bring improved decision by leveraging the diversity brought by an assembly of systems. Among these methods, boosting is a way to combine opinions of experts by weighting them based on their respective estimated accuracy. These base classifiers can be differentiated using various strategies, like training them on various subsets of the data or by providing them with different sub-parts of an ensemble of learned feature detectors. Another way to combine classifiers is to split the problem into a set of binary problems. A base classifier will then focus on classifying inputs between two of the initial classes, as in One-Vs-One (OVO), or between one class and the rest as in One-Vs-All (OVA). A way to implement these strategies is to provide a classifier with objective vectors that are not always specific of a single class but can be associated with a set of classes. Much attention is paid here to the Error-Correcting Output Coding (ECOC) method, which splits a multi-class problem into several two-way classification problems between meta-classes. It is shown in [2] that ECOC can reach a better classification performance on an image data-set as compared to other multi-class methods. The approaches presented here are derived from ECOC for multi-class problems. These methods allocate assemblies of output neurons to the different input classes, with potential overlap between the codes of two classes. A clustering of the output layer is also applied, with only one active neuron per cluster for each target vector, and a local soft-max [3] process applied in each cluster at test time. The soft-max operator has the effect of normalizing to 1 the sum of energies of output neurons in each cluster. Experimental results suggest that the number of classes sharing an output node impacts performance, and so does the minimal distance between class codes. This finding is maintained when output codes are repeated so as to ensure that the different tested networks have very similar numbers of parameters. The outline of the paper is as follows. Section II provides theoretical considerations on the advantages of different output codes. Section III explains the methodology used in training the networks. Section IV presents experimental results. II. CODING THEORY Prior to experimenting with assembly codes as output for neural networks, a theoretical analysis can provide insights about which assemblies should perform better. Consider a classifier with $P$ classes to identify. The simplest way to make the classifier express its decision is to assign a single output node (the so-called grandmother cell) to each class. We propose to replace these $P$ nodes with $n=P\choose m$ nodes representing all the combinations (or assemblies) of $m$ classes among $P$. Let us define the coding rate $R$ of the corresponding code as the ratio between $$R = \frac{\log_2(P)}{m}.$$ (1) To calculate the minimum Hamming distance, let us consider any two classes among $P$. The number of assemblies that contain neither one nor the other is $P - 2\choose m - 2$ and the number of assemblies that contain both is $P - 2\choose m$. The minimum Hamming distance of the code is given by $n$ minus the latter two terms; $$d_{\text{min}} = \frac{P - 2}{m} - \frac{P - 2}{m - 2}.$$ (2) The product of $R$ and $d_{\text{min}}$, called the merit factor $F$, is deduced as: $$F = R d_{\text{min}} = \frac{2 m (P - m) \log_2(P)}{(P - 1) P}$$ (3) and its maximal value is obtained for $m = P/2$: $$F_{\text{max}} = \frac{P \log_2(P)}{2 (P - 1)}.$$ (4) The corresponding minimum distance may be expressed as: $$d_{\text{min}}(\text{max}) = \frac{P}{2 (P - 1)}.$$ (5) For instance, with $P = 10$ (e.g. for MNIST classification), the best code involves quintuplet assemblies and offers a minimum distance of 140 with $n = 252$. If quintuplets are replaced with couples, the parameters become: $d_{\text{min}} = 16$ and $n = 45$. Note that the classical output code (one node per class), still with $P = 10$, has a minimum distance of 2 with $n = 10$. $$m \text{ classes among } P \quad 1 \quad 2 \quad c$$ Figure 1. The output layer of the classifier is organized in $c$ clusters, each one having $l$ nodes. These $l$ nodes represent disjoint combinations of $m$ classes among $P$ with $l = P/m$. Now we propose that the $n$ assemblies are distributed among $c$ clusters such that each class appears once and only once in each cluster. Therefore, there are $l = P/m$ nodes in each cluster, assuming that $P$ is a multiple of $m$ (Fig. 1). This structure has two advantages. Firstly, it compiles exactly with the clustered clique-based associative memory proposed in [4] which offers the possibility to store a number of patterns proportional to $l$ (for larger sought diversities, the sparse scheme proposed in [5] may be contemplated). However, the optimal value $l = 2$ (as deemed by the optimization of $F$) is too low for a clique-based implementation and a trade-off has then to be found. For instance, $l = 5$ (that is, $n = 2$) seems a good choice for $P = 10$. The second advantage is that a cluster containing disjoint assemblies and therefore probabilities, through the soft-max principle [6], may be rigorously used for both learning and testing. III. METHODOLOGY 3.1. MNIST MNIST [7] is a data-set of grey-scale images of handwritten digits that is widely used in deep learning. The data-set is made of 60000 images targeted for training and 10000 test examples. Many published works use the first 50000 examples from the training set to actually train the network, saving the last 10000 examples to perform cross-validation. Some papers however present networks trained on the whole set of 60000 training images, as is the case in [8]. Here the 50000/10000 split of the training set is used for the experiments of section 4.1, whereas in sections 4.2 and 4.3 the networks are trained with all 60000 examples. 3.2. SVHN SVHN [9] is a data-set made of color images of digits captured in real-world situations, e.g. house numberings. It contains 73257 training images and 26032 test images. We use 60000 examples from the train set to actually train our networks, and the remaining 13257 serve for cross-validation. 3.3. Assembly codes Couple cells are a method we introduce for encoding the class using a distributed code. Each cell no longer reacts to a single class but is specific of a couple of classes. Hence since the experiments are performed on data-sets with 10 classes, there are 45 possible couplings a given output neuron can be associated with. The whole set of 45 couplings is used here. Moreover, it is possible to partition these 45 couplings into 9 clusters of 5 couple cells where each individual class is represented exactly once in each cluster. This way the soft-max methodology can be applied inside of every cluster, between 5 competing hypotheses that are mutually exclusive. Quintuplets are yet another code where each neuron is associated with a combination of classes, this time 5 among 10. The same approach as for the couples is used, by using all 252 possible quintuplets and partitioning them into 126 clusters each containing 2 complementary quintuplet cells. The first two important factors considered to choose assembly codes are usability in a clique-based architecture and the merit factor. Alongside with the grandmother cell (our baseline), couples of classes (best trade-off cliques/merit factor) and quintuplets of classes (best merit factor, but larger output network) are tested. But only comparing these parameters is not enough, because one could argue that couples and quintuplets work better because they have a larger number of parameters for the last layer of the neural network. To avoid this we also train networks using repeated codes to reach output length of equal or comparable size. This repetition allows us to make a fair comparison between networks with virtually the same number of parameters in spite of using different output codes. Couples of classes have an interesting characteristic, in that there are plenty of different possible ways to partition 45 couple cells into 9 clusters, each featuring the 10 classes. Therefore it is possible to design an output layer of 1260 couple cells parted in 252 clusters where no cluster configuration is repeated twice. During the training phase, the categorical cross-entropy is used as the loss function. For classification, a majority voting is done where each active output node votes for its associated set of classes. The assembly codes are summarized in Table 1. <table> <thead> <tr> <th>Assembly Code</th> <th>n</th> <th>m</th> <th>l</th> <th>c</th> <th>F</th> <th>$d_{\text{min}}$</th> </tr> </thead> <tbody> <tr> <td>Grandmother cell (1G)</td> <td>10</td> <td>1</td> <td>10</td> <td>1</td> <td>0.66</td> <td>2</td> </tr> <tr> <td>Couples (1C)</td> <td>45</td> <td>2</td> <td>5</td> <td>9</td> <td>1.18</td> <td>16</td> </tr> <tr> <td>Quintuplets (1Q)</td> <td>252</td> <td>5</td> <td>2</td> <td>126</td> <td>1.84</td> <td>140</td> </tr> <tr> <td>Grandmother cell * 25 (25G)</td> <td>250</td> <td>1</td> <td>10</td> <td>25</td> <td>0.66</td> <td>50</td> </tr> <tr> <td>Couples * 6 (6C)</td> <td>270</td> <td>2</td> <td>5</td> <td>54</td> <td>1.18</td> <td>96</td> </tr> <tr> <td>Grandmother cell * 126 (126G)</td> <td>1260</td> <td>1</td> <td>10</td> <td>126</td> <td>0.66</td> <td>252</td> </tr> <tr> <td>Couples * 28 (28C)</td> <td>1260</td> <td>2</td> <td>5</td> <td>252</td> <td>1.18</td> <td>448</td> </tr> <tr> <td>Quintuplets * 5 (5Q)</td> <td>1260</td> <td>5</td> <td>2</td> <td>630</td> <td>1.84</td> <td>700</td> </tr> <tr> <td>Special Couples ¹ (SC)</td> <td>1260</td> <td>2</td> <td>5</td> <td>252</td> <td>1.18</td> <td>448</td> </tr> </tbody> </table> Table 1: Summary of the tested assembly codes. Assembly Code * number: Code repeated number times. ¹: 252 non-repeated clusters 3.4 Neural network settings For tests, the neural networks used are multi-layer perceptrons. Two architectures of network are used, one that is shallow and the other deep. The shallow network has only 1 hidden layer, while the deep network has 5 hidden layers. The results are presented by the mean and standard deviation over 10 executions with different weight initialization, noise, and image order. In sections 4.1 and 4.2 the neural network is shallow and its only hidden layer is composed of 2000 feature units. Training lasts for 200 epochs with a constant learning rate of 0.1. The model “baseline + noise” from [8] is chosen as a base for the deep network used in sections 4.3 and 4.4. This is a network that gets close to the current state-of-the-art in the task of permutation-invariant MNIST. It has 6 layers, where the first 5 of them are fully connected layers (with sizes 1000-500-250-250-250) and the last one is an output layer. At each connection layer, between the input and the activation, a batch normalization [11] and a Gaussian noise with mean 0 and standard deviation 0.3 are used. To finish the connection layer, a rectifier activation is used. The output layer has the length of the output code. A batch normalization is applied between the input and the activation and as in the case of the shallow network it uses a per-cluster softmax activation. The number of parameters of each network is given by the formula: $1000*(\text{input length}) + 750000 + 250*(n)$. This means: 1534000-250*(n) for MNIST and 3822000 + 250*(n) for SVHN. This deep network has 150 epochs to learn where it optimizes the weights with the ADAM optimizer [10], using an initial learning rate of 0.002 that has an annealing phase of 50 epochs where the learning rate decays linearly to 0. IV. RESULTS 4.1. Experimenting with codes Assigning the same number of output nodes to the different classes may not be ideal for a real-world data-set. Following this idea, it may be interesting to allocate different amounts of the output material to the different combinations of classes, as for instance the distributions of examples can be more correlated in a subset of classes than on average in the whole data-set. An experimental scheme inspired from the quintuplet configuration is tested, with 252 output neurons parted in 126 clusters of size 2 where a soft-max is applied. Instead of rigorously associating an output cell with each possible quintuplet however, 10 binary output codes are generated following a binomial distribution. This distribution is modulated to make vary the average number of ones in the output codes. Used as output for a shallow network, the average number of ones has an impact on classification performance, as shown by figure 2. Figure 2: Influence of the proportion of ones in the output target vectors on classification error rates. We see here that the error rate is maximal when there are less than 10% of ones in the output codes. It decays with higher values down to a minimum reached when there are around 60% of ones. Above that proportion, the error rate raises again. The minimal distance is obtained when generating as many ones as zeros on output as shown on figure 3, whereas the classifier performs better with output codes made of 60% up to 80% of ones. The error rate is also about 1.7 times lower for 90% of ones as compared to the case with 10% of ones, while the minimal distance is the same in both cases. This asymmetry is due to the way the class label is selected at test time, where a majority voting procedure is applied in which each output unit getting a value of 1 increments the score of all classes it is associated with. In this setting, the higher the number of ones in the output targets, the more connection weights end up being involved in the decision process at test time. The classifier thus makes use of a finer features-output mapping in this case. With too many ones however, e.g. 90%, the distance between codes becomes too low which affects performance. ![Figure 3: Measured mean Hamming distance between generated class codes depending on the proportion of ones.](image) 4.2 MNIST – Shallow Network The first test with the assembly codes defined in section 3.3, applies the shallow network to the MNIST data-set. The goal of this test is to compare the assemblies in similar settings, rather than achieving a competitive result to the state-of-the-art. The results indicate that Quintuplets are better than Grandmother cells and also that Couples are better than Grandmother cells, but it is inconclusive in the comparison between Couples and Quintuplets (less than two misclassified images of difference on average between the best networks of the two assemblies). ![Figure 4: Results summary for a shallow network on the MNIST data-set](image) 4.3 MNIST – Deep Network Another test is conducted on the MNIST data-set, now trying to emulate the results from [8]. It is summarized in figure 5. Despite respecting the hierarchy of Quintuplets ≥ Couples ≥ Grandmother cells, the results are too close to take any conclusions (less than one image on average between 5Q and 126G). ![Figure 5: Results summary for a deep network on the MNIST data-set](image) 4.4 SVHN – Deep Network Finally, applying the deep network to the SVHN data-set allows us to obtain more significant results than the ones obtained over MNIST. SVHN is more difficult to classify and has been less extensively studied. The results respect the hierarchy drawn from coding theory in section 2 (Quintuplets ≥ Couples ≥ Grandmother Cells), with an average distance of 0.11% (~26 images) between the worst quintuplets network and the best couples network and 0.33% (~85 images) between the worst quintuplets network and the best grandmother cells. On both MNIST and SVHN, these results show the interest of the quintuplets code which gives better performance than most other output codes for a comparable number of parameters. The only case where a code outperforms the quintuplets is the “special couples” (SC) code of non-repeated couple cells clusters, which beats 5Q on MNIST. It is also worth noting that the non-repeated couples perform better than the repeated 28C on both data-sets. V. CONCLUSIONS AND PERSPECTIVES A way to represent categories in multi-class problems is presented, that departs itself from the usual "grandmother cell" approach. Experimental results show that an assembly of neurons representing meta-classes can do a better job as output for a neural network. On the widely studied MNIST data-set, we use as starting point a multi-layer perceptron network that is close in performance to the state-of-the-art, and show that the proposed assembly codes can improve its accuracy. Furthermore, these results are in accordance with predictions drawn from coding theory in that a higher minimal Hamming distance between code words typically results in a better training of the classifier. The comparison also holds when code repetition is used to adjust the lengths of the outputs, so that all compared networks have about the same number of parameters. However one of the goals underlying this work is to combine deep neural networks with clustered clique-based associative memories, and the quintuplet configuration which gives the best results here would not be a good fit for this use. Indeed, even if it has a good minimal distance, the resulting clique patterns would have too many nodes in common. In this 10-class case, couple cells would be a good trade-off with a high minimal Hamming distance and a good suitability with Clustered Cliques Networks. Similar trade-offs may also be found for higher-dimensional classification problems. A prospect of our ongoing work is also to be able to classify datasets with a high number of classes. This way the compression power of the clustered clique code may be exploited, which allows to support a big dictionary of code words with a limited amount of material while keeping a good word recognition ability. The assembly output deep learner presented is a first step in this direction. Sets of images of words are a very interesting application case as it can have tens of thousands of categories. ACKNOWLEDGEMENT The authors would like to thank NVIDIA for providing us with a free graphics card allowing to speed up computations for the experiments performed during this work. The software developed to perform the simulations presented here was based on libraries Theano [12] and Keras [13]. REFERENCES
{"Source-Url": "https://hal.archives-ouvertes.fr/hal-01502488/file/PapierISTC.pdf", "len_cl100k_base": 5085, "olmocr-version": "0.1.53", "pdf-total-pages": 6, "total-fallback-pages": 0, "total-input-tokens": 20249, "total-output-tokens": 6305, "length": "2e12", "weborganizer": {"__label__adult": 0.00047516822814941406, "__label__art_design": 0.0007390975952148438, "__label__crime_law": 0.00048065185546875, "__label__education_jobs": 0.0009326934814453124, "__label__entertainment": 0.0002028942108154297, "__label__fashion_beauty": 0.0002741813659667969, "__label__finance_business": 0.0003097057342529297, "__label__food_dining": 0.0005445480346679688, "__label__games": 0.0008692741394042969, "__label__hardware": 0.002704620361328125, "__label__health": 0.0012788772583007812, "__label__history": 0.0004248619079589844, "__label__home_hobbies": 0.00020110607147216797, "__label__industrial": 0.0008940696716308594, "__label__literature": 0.0003910064697265625, "__label__politics": 0.0003857612609863281, "__label__religion": 0.0007009506225585938, "__label__science_tech": 0.4765625, "__label__social_life": 0.00015223026275634766, "__label__software": 0.010467529296875, "__label__software_dev": 0.49951171875, "__label__sports_fitness": 0.0004425048828125, "__label__transportation": 0.0007419586181640625, "__label__travel": 0.0002608299255371094}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 24055, 0.06955]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 24055, 0.53693]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 24055, 0.89865]], "google_gemma-3-12b-it_contains_pii": [[0, 1110, false], [1110, 6458, null], [6458, 12020, null], [12020, 17026, null], [17026, 19410, null], [19410, 24055, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1110, true], [1110, 6458, null], [6458, 12020, null], [12020, 17026, null], [17026, 19410, null], [19410, 24055, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 24055, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 24055, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 24055, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 24055, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 24055, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 24055, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 24055, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 24055, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 24055, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 24055, null]], "pdf_page_numbers": [[0, 1110, 1], [1110, 6458, 2], [6458, 12020, 3], [12020, 17026, 4], [17026, 19410, 5], [19410, 24055, 6]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 24055, 0.10185]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
64f076bd7bc9bc753f4cdec7b84592187498bc52
Parametric Polymorphism and Abstract Models of Storage (In memory of Christopher Strachey, 1916-1975) Uday S. Reddy 1University of Birmingham Strachey-100, Oxford My introduction to Strachey’s ideas Section 1 Introducing the terms The term **Parametric polymorphism** appears in *Fundamental Concepts in Programming Languages* (1967). Contrasted with “*ad hoc* polymorphism” or *definition by cases* on the types involved. Example given: $$\text{map}_{\alpha, \beta} : (\alpha \Rightarrow \beta, \alpha \text{ list}) \rightarrow \beta \text{ list}$$ Reynolds (1974) defines **Polymorphic lambda calculus**. The world is a different place! Abstract models of storage - *The Varieties of Programming Language* (1973) gives a model of store (based on locations) which is said to be “deliberately simplified”. - A more “complicated model” and a more “formalised description” is promised in a forthcoming paper titled *An abstract model of storage*. - What was Strachey planning to say in this paper? - Once again, Reynolds steals the thunder by proposing an abstract model of storage in *The Essence of Algol* (1981). Section 2 Parametric polymorphism In Reynolds’s explanation: - “a parametric polymorphic function is one that behaves the same way for all types,” whereas an ad hoc polymorphic function may have “unrelated meanings” at different types. Therefore, he wants to give a definition for what it means for a polymorphic function to be parametric. \[ \text{map}_{\alpha,\beta} : (\alpha \Rightarrow \beta, \alpha \text{ list}) \rightarrow \beta \text{ list} \] Why? The naive models of the polymorphic lambda calculus have \textit{ad hoc} polymorphic functions. We must “exclude” them. Mathematicians knew parametricity - Eilenberg and Mac Lane: - *Natural Isomorphisms in Group Theory* (1942) - *General Theory of Natural Equivalences* (1945) - *Algebra* (1967) - "... is considered *natural* because it furnishes for each $G$ a unique isomorphism *not dependent on any choice of generators*.” - This is representation independence or data abstraction. - “*This exhibition of the isomorphism... is natural in that it is given simultaneously for all ... vector spaces $L$.*” - This is *definability* without case analysis. But... - Naturality doesn’t work! \[ \text{map}_{\alpha,\beta} : (\alpha \Rightarrow \beta, \alpha \text{ list}) \rightarrow \beta \text{ list} \] The input type \((\alpha \Rightarrow \beta, \alpha \text{ list})\) is not a functor of \(\alpha\). - Reynolds notices that it is a relator. \[ \begin{array}{ccc} A & \Rightarrow & B \\ \uparrow R & & \uparrow \text{map}_{A, B} \end{array} \] \[ \begin{array}{ccc} A & \Rightarrow & B \\ \downarrow \text{L}(A) & & \downarrow \text{L}(B) \end{array} \] \[ \begin{array}{ccc} A' & \Rightarrow & B' \\ \downarrow S & & \downarrow \text{map}_{A', B'} \end{array} \] \[ \begin{array}{ccc} A' & \Rightarrow & B' \\ \downarrow \text{L}(A') & & \downarrow \text{L}(B') \end{array} \] - This is termed relational parametricity. It is a conservative extension of naturality. How does mathematics deal with it? - It doesn’t, actually. - Quite a lot of mathematics just deals with first-order functions. - For first-order functions naturality and relational parametricity are equivalent. - Quite a lot of mathematics assumes that types are sets. - For sets (with equality and membership operations), the only allowed relations are isomorphisms. - Category theorists also use dinaturality which is an approximation of relational parametricity. - But, dinaturals don’t compose! An example problem - The definition of a category involves composition: \[ \text{comp}_{A,B,C} : \text{Hom}(A, B) \times \text{Hom}(B, C) \rightarrow \text{Hom}(A, C) \] This should be parametric in \(A\), \(B\) and \(C\). If it is, I call it a parametric category. \[ \text{Hom}(R, S) \times \text{Hom}(S, T) \rightarrow \text{Hom}(R, T) \] - Example: **Set**, the category of sets and functions, is a parametric category. - Counterexample: **Rel**, the category of sets and binary relations, is *not a parametric category.* An example problem - contd. \[(p, q) \mapsto p; q \equiv a\] \[ \begin{align*} \text{Rel}(A, B) \times \text{Rel}(B, C) & \xrightarrow{\text{comp}_{A,B,C}} \text{Rel}(A, C) \\ \text{Rel}(R, S) \times \text{Rel}(S, T) & \xrightarrow{\text{comp}_{A,B,C}} \text{Rel}(R, T) \\ \text{Rel}(A', B') \times \text{Rel}(B', C') & \xrightarrow{\text{comp}_{A',B',C'}} \text{Rel}(A', C') \end{align*} \] \[(p', q') \mapsto p'; q' \equiv a'\] \[(a, a') \in \text{Rel}(R, T) \text{ means } (x, x') \in R \land (z, z') \in T \implies (a(x, z) \iff a'(x', z'))\] More abstractly, we are treating \(\text{Rel}(A, C) \equiv [A \times C \to 2]\) An example problem - contd. ▶ To show \((p; q, p'; q') \in \text{Rel}(R, T)\): \[ \begin{array}{cccccc} & A & p & B & q & C & z \\ x & & & & & & \\ R & & & & & & T \\ x' & A' & p' & B' & q' & C' & z' \\ \end{array} \] ▶ Consider \((x, x') \in R\) and \((z, z') \in T\). ▶ We need to show \((p; q)(x, z) \iff (p'; q')(x', z')\). ▶ The left hand side implies there exists \(y \in B\) such that \(p(x, y) \land q(y, z)\). ▶ However, there may be nothing in \(B'\) related to \(y\). The relation \(S\) could be the empty relation! ▶ If we turn “set-theoretic”, i.e., assume that all types are sets and all relations are isomorphisms, then ▶ Parametricity forces us to forget that sets are sets (when we use them as types). The upshot - By generalising Plotkin’s **logical relations theorem**, we can argue that anything definable in a good typed language is parametric. - All **constructive mathematics** is parametric. - For example, **natural deduction rules** are parametric. So are all category-theoretic **adjunctions**. - The rule of **excluded middle** and the **axiom of choice** are not parametric. - By the way, remember Abramsky’s slogan: \[ \text{composition} = \text{parallel composition} + \text{hiding} \] Parallel composition is always parametric: \[ \text{Rel}_2(A, B) \times \text{Rel}_2(B, C) \rightarrow \text{Rel}_3(A, B, C) \] But hiding is parametric only if we can produce the mediating witness **constructively**. Parametricity is about information hiding - We can use a polymorphic type for map: \[ map : \forall \alpha. \forall \beta. (\alpha \Rightarrow \beta, \alpha \text{ list}) \rightarrow \beta \text{ list} \] - The \( \forall \) quantifiers signify that the types provided as \( \alpha \) and \( \beta \) are hidden from map. Those values are “black boxes” for map. This is local information hiding. - The dual existential quantifier \[ \exists \alpha. T(\alpha) \] describes global information hiding (data abstraction). - We provide a type \( A \) and a suite of operations of type \( T(A) \). - But the client programs (or client mathematicians) cannot “see” the type \( A \). - Reynolds explains this in terms of Descartes and Bessel teaching complex analysis. Section 3 Abstract models of storage: Intuitionism We know that Peter Landin was a strong influence on Strachey. Landin was a great believer in functional programming: - *The commonplace expressions of arithmetic and algebra have a certain simplicity that most communications to computers lack.* (1966) But Strachey, who was a master programmer in imperative programming languages, knew that there must be ways to reason about imperative programs systematically. - *[Declarative languages] are an interesting subset, but... inconvenient... We need them because at the moment we don’t know how to construct proofs with ... imperatives and jumps.* (1966) Strachey seems to have thought the solution was to reduce the “imperatives” to “mathematics” (the commonplace expressions of arithmetic and algebra). This was perhaps too limiting. A critique of “mathematical semantics” - Mathematics is strongly tied into the Plato’s world of concepts, which are timeless and non-material. - But concepts are not the only things that exist. - Physics constructs mathematical models for physical phenomena that involve time and matter, but does not attempt to reduce them to mathematics. - The point of the models is to allow us to make predictions (i.e., construct proofs), but not necessarily to state the essence of the phenomena. - A part of Strachey’s programme was successful: Commands can be modelled as state-to-state functions. - But the store on which the commands act is a physical object, not a Platonic concept. Is “mathematical semantics” possible - Today, we know that it is not possible to reduce imperative programming languages to mathematical languages. - Functional languages, e.g., PCF, satisfy Milner’s context lemma, which can be thought of as an extensionality principle. But imperative programming languages do not satisfy it. - In Games semantics, we can see that functional languages can be interpreted by history-free strategies, but imperative languages need history-sensitive strategies. - However, in a broad sense “mathematics” contains everything that can be logically constructed. Computer Science itself is a branch of mathematics in this sense. - We can certainly build models for programming languages using traditional mathematical tools. But this does not amount to a reduction. Intuitionism - Aristotle’s first syllogism: All men are mortal Socrates is a man Socrates is mortal - What did Aristotle mean by men? What would Aristotle say if you said: - All men are mortal - Christopher Strachey is a man perhaps he would have said, “it is not a good example because there is no man called Christopher Strachey”? What we mean by men is different from what Aristotle would have meant by “men”. (Or is it? Did Aristotle believe in Platonic concepts?) But the meaning of All men are mortal is robust. Even if Aristotle didn’t know what we mean by “men”, he certainly meant that all men in our world are mortal too. Intuitionism - contd - I would make a case that, whenever we apply logic to physical phenomena, we have such possible worlds in mind. - We don’t reduce men to mathematics, but we can reason about them just the same. - We have typed lambda calculus and intuitionistic logic, i.e., all parametric principles of reasoning still applicable to these physical objects. - The store of imperative programs is similar. There is no fixed collection of locations just as there is no fixed collection of men. - If we define a function of type \( \text{var}[\text{int}] \rightarrow \text{com} \), the possible arguments are not just the variables that exist when the function is defined, but the variables that might exist when the function is applied. Intuitionistic set theory - An “intuitionistic” set (in the sense of Kripke and Lawvere) is a set parameterized by some context, which we call a “world.” $A(X) = \ldots$ Lawvere also calls them “variable sets.” Normal sets are called “constant sets.” - In our case, “worlds” will be store shapes. - There is also a sense of another world being a “possible future world” of $X$. \[ \begin{array}{c} Y & \quad & A(Y) \\ \uparrow f & & \uparrow A(f) \\ X & \quad & A(X) \end{array} \] If the world grows from $X$ to $Y$, then every value of type $A$ at $X$ continues to be a value at $Y$ via the translation $A(f)$. Intuitionistic function space - **Functions:** \((A \Rightarrow B)(X) = \forall_{Y \leftarrow X} A(Y) \Rightarrow B(Y)\) - Intuitively: a “function” of type \(A \Rightarrow B\) at world \(X\) can work at every future world \(Y\), accepting arguments of type \(A\) at world \(Y\) and giving results of type \(B\) at world \(Y\). - In other words, functions must be **stable under the growth of the world**. - In fact, all values in intuitionistic set theory must be stable under growth in this way. - This is a **fundamental idea for Computer Science**: All the programs we write must be stable under the growth of the world. Examples: - Programs for the Internet. - Databases. Parametric Intuitionistic function space - **Functions:** \((A \Rightarrow B)(X) = \forall_{Y \leftarrow X} A(Y) \rightarrow B(Y)\). - The \(\forall\) type quantifier signifies *parametricity*. (The plain categorical construction is written as \(\int_{Y \leftarrow X} A(Y) \rightarrow B(Y)\).) - If \(f\) is a “function” of type \((A \Rightarrow B)(X)\) then it can only depend on the information available in world \(X\). - Even if it is called at a future world \(Y\) that has additional information, the new information available in \(Y\) would be hidden from \(f\). - This is a construct of “parametric category theory”. - The need for extending category-theoretic intuitionism (toposes) with parametricity was first identified by O’Hearn and Tennent (1993): *Parametricity and Local Variables*. - It came as a surprise to most of us at that time that category theory alone could not do the job on its own! Example for parametric intuitionism Consider the equivalence (for $p : \text{com} \rightarrow \text{com}$): $$ \text{newvar } x. \{ x := 0; \ p(x := !x + 1) \} \equiv \text{newvar } x. \{ x := 0; \ p(x := !x - 1) \} $$ The argument depends on the fact: “$x$ is hidden from $p$.” Equivalent to: “$p$ is parametrically polymorphic in the state space of $x$.” I.e., $p$ must preserve all possible relationships between the state spaces of $x$. For example, $R : \mathbb{Z} \leftrightarrow \mathbb{Z}$ given by: $$ n \ [R] \ n' \iff n \geq 0 \land n' = -n $$ Since $x := !x + 1$ and $x := !x - 1$ preserve this relation, $p(x := x + 1)$ and $p(x := !x - 1)$ must preserve it too. Section 4 Abstract models of storage: Automata Towards an abstract store - The “store” does not just contain locations that hold numbers/characters, but all kinds of data structures, like stacks, trees, or graphs, as well as databases, I/O devices, network connections etc. - The store is everything that can change. - When we apply functions to objects in the store, we build layers of abstractions, at each level of which we have a more abstract store. ```let S2 = RemoveLayoutChars[ IntcodefromFlexowriter[ BytesfromPT]] ``` (An example from [Stoy and Strachey, 1971]) What should a store be? - **Idea 1**: A store is a collection of locations. - **Idea 2**: A store can be abstracted to a set of states. - **Idea 3**: A store should be abstracted to a set of states along with its possible state transformations. Reynolds arrived at Idea 3 in 1981! But, perhaps, he didn’t have a strong reason to pursue it. Oles produced a variant of the model using Idea 2 and proved that it was isomorphic to the Reynolds model. It became standard from then on. However, the tension between category theory and relational parametricity, which exists with the Oles model, is not present in the Reynolds model. (This problem led me to reinvent it in 1998.) Views and lenses - Morphisms in a category can be viewed in either direction ($C$ vs. $C^{\text{op}}$). \[ \begin{array}{ccc} Y & \xrightarrow{f} & X \\ \uparrow & \quad & \downarrow \quad \uparrow \\ \downarrow & \quad & \downarrow \quad \downarrow \\ X & & X \end{array} \] - In the reverse direction, $f^\#$ is a way of viewing a large store $Y$ (a database) as a small store $X$ (a view). In the database theory, $f^\#$ is called a lense. - A “lense” is a bidirectional concept: Not only can we treat the state of the database as a state of the view, but we also want to transmit the changes made to the view as changes to the database [Czarnecki et al, 2009]. Reynolds transformation monoids A store $X$ is represented as a tuple $$(Q_X, T_X, \alpha_X, \text{read}_X)$$ (Reynolds transformation monoid) where: - $Q_X$ - a (small) set of states, - $T_X$ - a monoid of state transformations $T_X \subseteq [Q_X \to Q_X]$, - $\alpha_X : T_X \hookrightarrow [Q_X \to Q_X]$ - the implicit monoid action, - $\text{read}_X : [Q_X \to T_X] \to T_X$ - called “diagonalization”: $$\text{read}_X p = \lambda x. p x x = \lambda x. \alpha_X(p x) x$$ allows a state transformation to be dependent on the initial state. For example, $$\text{cond}_X b \ c_1 \ c_2 = \text{read}_X \lambda s. \text{if } b(s) \neq 0 \text{ then } c_1 \text{ else } c_2$$ Note: Transformation monoids in algebraic automata theory [Eilenberg, 1974] are triples $(Q_X, T_X, \alpha_X)$. Logical relations for RTM’s - A logical relation $R : (Q_X, T_X) \leftrightarrow (Q_{X'}, T_{X'})$ is a pair $(R_q, R_t)$ where $$ \begin{array}{c} X \\ \downarrow R \\ \downarrow X' \end{array} = \begin{pmatrix} Q_X & T_X \\ \downarrow R_q & \downarrow R_t \\ Q_{X'} & T_{X'} \end{pmatrix} $$ - $R_q : Q_X \leftrightarrow Q_{X'}$ is a relation, and - $R_t : T_X \leftrightarrow T_{X'}$ is a logical relation of monoids, such that - $\alpha_X [R_t \rightarrow [R_q \rightarrow R_q]] \alpha_{X'}$, and - $\text{read}_X [ [R_q \rightarrow R_t] \rightarrow R_t ] \text{ read}_{X'}$. Morphisms for RTM’s - A homomorphism \( f : (Q_X, T_X) \to (Q_Y, T_Y) \) is a pair \((f_q, f_t)\) \[ \begin{array}{c} Y \\ \uparrow f \\ X \\ \end{array} \begin{pmatrix} Q_Y & T_Y \\ \downarrow f_q & \uparrow f_t \\ Q_X & T_X \\ \end{pmatrix} \] where - \( f_q : Q_Y \to Q_X \) is a function, and - \( f_t : T_X \to T_Y \) is a homomorphism of monoids, such that \((\langle f_q \rangle \dashv, \langle f_t \rangle)\) is a logical relation of RTM’s. - Note that \( f_q \) and \( f_t \) run in opposite directions. (Mixed variance) - No “parametricity vs. naturality” tension with RTM’s. Logical relations subsume homomorphisms. Interpretation of Algol types - Algol types are now functors of type $\text{RTM} \rightarrow \text{Set}$ (ignoring divergence): $$\text{COM}(X) = T_X$$ $$\text{EXP}(X) = [Q_X \rightarrow \text{Int}]$$ $$(A \Rightarrow B)(X) = \forall Y \leftarrow X A(Y) \rightarrow B(Y)$$ This model does not have command snapback, i.e., models irreversible state change. - **Fact**: $\text{Hom}(\text{COM}, \text{COM}) \cong \mathbb{N}$, representable by $$\lambda c. \text{skip}, \lambda c. c, \lambda c. (c; c), \ldots$$ - But it has expression snapback (does not model passivity). - Reddy (MFPS, 2013) shows that, with an apparently minor adjustment, passivity is also obtained. The challenge for denotational semantics - How to capture the intensional aspects of computations in an extensional model? **Example of extensionality:** \[ gv(x) \implies (x := !x + 1; x := !x + 1) \equiv (x := !x + 2) \] - Intensional models - Object spaces [Reddy, O’Hearn, McCusker] - Action traces [Hoare, Brookes] - Game semantics [Abramsky, McCusker, Honda, Murawski] Intensional models distinguish between the two sides of the equivalence. - We are after extensional models. **Another example of extensionality:** \[ \text{read}_x(2), \text{write}_x(3), \text{read}_x(3), \text{write}_x(4) \] \[ \text{read}_x(2), \text{write}_x(4) \] \[ \text{stack}(s) \implies (s.\text{push}(v); s.\text{pop}) \equiv \text{skip} \] Naive extensional models have “junk” - **Command snapback** (with divergence): ``` try : com → com try c = λs. \{ s, \text{ if } c(s) \neq \bot \bot, \text{ if } c(s) = \bot \} ``` State changes should be **irreversible**. (The state is single-threaded). - **Expression snapback**: ``` do_result_ : com × exp → exp do c result e = λs. e(c(s)) ``` Expressions should only read the state (**passivity**). - Intensional models can eliminate such “junk” relatively easily. - Eliminating “junk” in extensional models involves inventing mathematical structure. Example equivalences - **Irreversible state change** is involved in this equivalence. Suppose \( p : \text{com} \rightarrow \text{com} \). \[ \text{new } x. \ \text{let } inc = (x := !x + 1) \\ in x := 0; \ p(inc); \ \text{if } !x > 0 \ \text{then diverge} \\ \equiv p(\text{diverge}) \] - The first command diverges if \( p \) runs its argument command and terminates if \( p \) ignores its argument. The second command has exactly the same effect. - The command **snapback** would break this equivalence. If \( p = \text{try} \), then it can run the argument command and set the state back to the initial state. Passivity is involved in this equivalence (remember call-by-name): \[ \text{if } !x = 0 \text{ then } f(!x) \text{ else } 2 \equiv \text{if } !x = 0 \text{ then } f(0) \text{ else } 2 \] where \( x : \text{var} \) and \( f : \text{exp} \rightarrow \text{exp} \). Since \( f(!x) \) is a passive expression, it can only read \( x \) and it gets the value 0. Expression snapback would break this equivalence. Suppose: \[ f = \lambda e. \text{do } x := !x + 1 \text{ result } e \] then \( f(!x) \) would have the effect of \( f(1) \). Prospective - Strachey was a great pioneer, a founder of our discipline, an intellectual father for all of us. - But, if he were here, he might not be satisfied with what we have done with his ideas. - He possibly did not intend semantics to be merely a research discipline, but rather a practical tool to be used in everyday programming. - Can we do more to propagate these ideas and to make them practical?
{"Source-Url": "https://www.cs.ox.ac.uk/strachey100/slides/Reddy.pdf", "len_cl100k_base": 6123, "olmocr-version": "0.1.53", "pdf-total-pages": 40, "total-fallback-pages": 0, "total-input-tokens": 65838, "total-output-tokens": 7980, "length": "2e12", "weborganizer": {"__label__adult": 0.000644683837890625, "__label__art_design": 0.0008311271667480469, "__label__crime_law": 0.0005693435668945312, "__label__education_jobs": 0.0022830963134765625, "__label__entertainment": 0.00022220611572265625, "__label__fashion_beauty": 0.0003197193145751953, "__label__finance_business": 0.0005307197570800781, "__label__food_dining": 0.000911235809326172, "__label__games": 0.000835418701171875, "__label__hardware": 0.0013866424560546875, "__label__health": 0.001789093017578125, "__label__history": 0.0008344650268554688, "__label__home_hobbies": 0.0003161430358886719, "__label__industrial": 0.0011663436889648438, "__label__literature": 0.0027256011962890625, "__label__politics": 0.0007281303405761719, "__label__religion": 0.0013322830200195312, "__label__science_tech": 0.417236328125, "__label__social_life": 0.00029754638671875, "__label__software": 0.00545501708984375, "__label__software_dev": 0.55712890625, "__label__sports_fitness": 0.00055694580078125, "__label__transportation": 0.0015192031860351562, "__label__travel": 0.00028967857360839844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 21271, 0.00631]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 21271, 0.55346]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 21271, 0.81706]], "google_gemma-3-12b-it_contains_pii": [[0, 166, false], [166, 202, null], [202, 235, null], [235, 766, null], [766, 1245, null], [1245, 1245, null], [1245, 1280, null], [1280, 1829, null], [1829, 2377, null], [2377, 3198, null], [3198, 3704, null], [3704, 4236, null], [4236, 4868, null], [4868, 5603, null], [5603, 6330, null], [6330, 7116, null], [7116, 7168, null], [7168, 7957, null], [7957, 8635, null], [8635, 9435, null], [9435, 9579, null], [9579, 10083, null], [10083, 10824, null], [10824, 11443, null], [11443, 12125, null], [12125, 13037, null], [13037, 13723, null], [13723, 13771, null], [13771, 14329, null], [14329, 15006, null], [15006, 15675, null], [15675, 16473, null], [16473, 17059, null], [17059, 17697, null], [17697, 18373, null], [18373, 19114, null], [19114, 19707, null], [19707, 20325, null], [20325, 20862, null], [20862, 21271, null]], "google_gemma-3-12b-it_is_public_document": [[0, 166, true], [166, 202, null], [202, 235, null], [235, 766, null], [766, 1245, null], [1245, 1245, null], [1245, 1280, null], [1280, 1829, null], [1829, 2377, null], [2377, 3198, null], [3198, 3704, null], [3704, 4236, null], [4236, 4868, null], [4868, 5603, null], [5603, 6330, null], [6330, 7116, null], [7116, 7168, null], [7168, 7957, null], [7957, 8635, null], [8635, 9435, null], [9435, 9579, null], [9579, 10083, null], [10083, 10824, null], [10824, 11443, null], [11443, 12125, null], [12125, 13037, null], [13037, 13723, null], [13723, 13771, null], [13771, 14329, null], [14329, 15006, null], [15006, 15675, null], [15675, 16473, null], [16473, 17059, null], [17059, 17697, null], [17697, 18373, null], [18373, 19114, null], [19114, 19707, null], [19707, 20325, null], [20325, 20862, null], [20862, 21271, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 21271, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 21271, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 21271, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 21271, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 21271, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 21271, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 21271, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 21271, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 21271, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 21271, null]], "pdf_page_numbers": [[0, 166, 1], [166, 202, 2], [202, 235, 3], [235, 766, 4], [766, 1245, 5], [1245, 1245, 6], [1245, 1280, 7], [1280, 1829, 8], [1829, 2377, 9], [2377, 3198, 10], [3198, 3704, 11], [3704, 4236, 12], [4236, 4868, 13], [4868, 5603, 14], [5603, 6330, 15], [6330, 7116, 16], [7116, 7168, 17], [7168, 7957, 18], [7957, 8635, 19], [8635, 9435, 20], [9435, 9579, 21], [9579, 10083, 22], [10083, 10824, 23], [10824, 11443, 24], [11443, 12125, 25], [12125, 13037, 26], [13037, 13723, 27], [13723, 13771, 28], [13771, 14329, 29], [14329, 15006, 30], [15006, 15675, 31], [15675, 16473, 32], [16473, 17059, 33], [17059, 17697, 34], [17697, 18373, 35], [18373, 19114, 36], [19114, 19707, 37], [19707, 20325, 38], [20325, 20862, 39], [20862, 21271, 40]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 21271, 0.0]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
b3390f6d037a1d32831f7006bceb90c1dc3e25fc
Women in Software and Cybersecurity: Anita Carleton *featuring Anita Carleton as Interviewed by Eileen Wrubel* --- **Eileen Wrubel:** Welcome to the SEI Podcast Series, a production of Carnegie Mellon University Software Engineering Institute. The SEI is a federally funded research and development center sponsored by the Department of Defense and operated by Carnegie Mellon. A transcript of today’s podcast is available on our website at [sei.cmu.edu/podcasts](http://sei.cmu.edu/podcasts). My name is **Eileen Wrubel**, and I am the co-lead of the SEI’s Lifecycle Innovation and Automation Directorate. With me today, is **Anita Carleton**, who leads the SEI’s **Software Solutions Division**. This interview is part of our series of podcasts highlighting the work of women in software and cybersecurity. Hi, Anita. Thank you so much for joining me today. **Anita Carleton:** It’s my pleasure. I’m really looking forward to the discussion. **Eileen:** You and I work closely on a number of things, but a lot of our listeners don’t know you very well. So I was wondering if you could start by telling us a little bit about your work at the SEI, maybe a typical day, and the things you really love about your job. **Anita:** Yes, I am currently the **Software Solutions Division** director with leadership and operating responsibility for about 150 people and $55 million in revenue. The division is one of three technical areas for SEI. The other being cybersecurity [CERT] and the other being the Emerging Technologies including artificial intelligence. I am responsible for the strategy, the leadership, the direction, and the management of SEI's activities in the area of software. I lead the division's software engineering research and development portfolio of work, which includes working with government, industry, academia in designing, and building, and deploying advanced software technologies for national security. A typical day for me, I am an early riser and I know you’re an early riser, too. I am an early riser. I am in the office by 7 or 7:30. I always take a few minutes each day to keep up with defense and tech news. Some of the things that I like to read will include Wired Magazine, IEEE Software, the New York Times, Defense Daily or Defense News. I like the MIT Technology Review, and there is a publication from CMUs School of Computer Science. It’s called Link. I can glance it, actually, very quickly and just get a sense of what’s going on. Those are some of the things that I just want to glance at and get a sense of what is going on in our communities. A typical day then is, part of what we have to do is solve complex engineering challenges for the Department of Defense [DoD]. That requires building strong partnerships and collaborations with DoD, with the research community, with various U.S. government agencies as well as other SEI leaders. This means I am in quite a few meetings. That is what my day is like when I get into the office, but they are important meetings. I am usually connecting with the executive team, with our leadership team, with leaders across SEI and CMU, and certainly defense leaders as well. Part of what we are trying to do is understand what their key challenges are and how we are going to devise the right kinds of research programs and the right kinds of solutions to be able to address the key challenges that DoD has. So that is sort of a typical day. Another thing that I do—and it’s another thing that you do—is that I travel. I travel a lot. I travel probably, weekly. That is important because we have got to get out to where our customers and our key stakeholders are. I travel pretty frequently to the Pentagon to meet with DoD senior officials, the Army, the Air Force, Navy, acquisition programs. We want to get a sense of what their pressing challenges are. Sometimes it requires getting some of our folks on site to work hand in hand with some of the engineers there. But it is important to actually be out in the environments where the work is really happening. That is a typical day, and I guess the best part of my day, I think there’s three best parts of my day. Knowing that the work that we do really matters, really matters to DoD, matters to our nation, matters to the world. Working on significant challenges that really are going to make a difference, that is something that is incredibly rewarding to me. I have been at the SEI 30 years. Time flies when you are having fun. The mission is why I came to the SEI, and what I find is that the mission is what keeps me at SEI. I think that is incredibly relevant. Working with our team and working with key stakeholders on devising a software strategy for the DoD, I think that is something so exciting that I think we are working on. Taking time—yes, we have got to address the day-to-day problems—but taking time to position our work for the future is incredibly important and of course very rewarding. That is really important. The most important part or the most, maybe, rewarding part of my day is just working with the great people that we have. They are talented, incredibly committed to the mission, dedicated to their customers, and dedicated to really being all in and coming up with really innovative solutions. To me, those are sort of the best parts of my day. Eileen: That is so much fun to just know that every day when you come to work, you are with people who are just in it to do the best thing, and everybody is so hungry and so curious and so ready to just push to the next level. Anita: I think what is important is part of the SEI’s role is to really do the groundbreaking research and being able to figure out, OK, how does this translate to what our customers need, and then how do we take that and transition this into practice? When we think about our role being all the parts of the software lifecycle, it makes it challenging but it makes it really rewarding. Eileen: Now I’m going to ask you to step into my way-back machine a little bit. I’d like to go back to your childhood. Can you tell me a little bit about what started you on this path? If there’s a kid out there listening, what clue might they find that, Hey, I’m like that, too. Maybe that is a path I could take some day. Anita: Yes. Well, I’m the daughter of Indian parents. If you know anything about what is important to Indian parents, there are two clues: math and science. My father is an engineer, and my parents were just so fabulous, exposing me to everything math and science. I love that, so it was no hardship by any means. I grew up being very good in math and science. It’s what I really love doing. In high school, I remember that I was selected to the Westinghouse Science Honors Institute. It was an opportunity to gain insight into various engineering and science fields. I couldn’t wait for every Saturday to come. It was a chance to go to where my Dad worked. So that was also very exciting. I looked up to my Dad. He was an engineer. It is something that I always wanted to do. I wanted to be like my Dad. I got to go to Westinghouse, and every Saturday morning was some deep dive in some area of science, some area of engineering. Just getting some exposure to the different engineering fields: math and science and physics and chemistry. All the different sciences and sort of the interplay, I think, was very exciting. But I have to say my first exposure in the software field wasn’t until I attended CMU. I attended CMU when the big computer science awakening was starting to happen. It was my first computer science course. It was my first programming course. It was FORTRAN. The other really exciting thing freshman year was there was a new class the year that I was starting. The core classes were, calculus, physics, chemistry, math. You also went to CMU. What was exciting is that I had a chance to take a special calculus course that was about programming or coding on a programmable calculator. It was the TI-58C. I remember buying that thing, and I could not wait until I was going to start at CMU, and that I was going to be taking this cool class. It is just some of those kinds of things. It is being exposed to things early on and developing the love of something, and feeling like, Hey, you know, I understand this. I’m pretty good at this. How can I take these things and apply them to the real world? Eileen: Can you tell me about any mentors that you had along the way and what wisdom they might have imparted to you or lessons you’ve learned from them? Anita: I’ve had several wonderful mentors, including both my mother and my father. The mentor that has had the most, I guess, significant impact on me and my leadership style is Watts Humphrey. Watts hired me into the SEI many, many years ago. I guess what I will remember most about Watts is his love of learning, his passion for the people that he worked with, and for the work that he was doing. He knew that this work, the work of trying to understand software engineering better, was really going to make a difference. I remember when I interviewed with him, he said, How would you like to come and join me in changing the world of software engineering? Who is going to say no to that? I was hooked. I was very, very excited to have that opportunity to work with him. It was about changing the world of software engineering, but more specifically, working with Watts was about thinking carefully about how software was going to be engineered and how software was going to be managed. Those were the key areas that were passionate to him. They became my passions, too. He was one of those kinds of people. I think that he was such an important person in my life because he really helped me to grow and develop as a software engineer but also as a software leader. He had a lot of fabulous ways that he did that. He looked for challenging assignments. He looked for lots of different kinds of assignments. He really encouraged me to take on leadership roles, even when I didn’t necessarily feel that I was ready to take some of those on. He really was quite an incredible man. He had a profound impact on the field of software engineering during his lifetime. He then went on to receive the National Medal of Technology, one of the highest honors given by the President of the United States to America’s leading innovators. He just was quite a remarkable person. I try very hard to be the Watts in other people’s lives. What I mean by that is I work very hard for the people that work on our team to look for leadership and growth opportunities for them, just the way that someone fabulous did for me. He’s someone very important in my life. Eileen: I know you really do live that. I have certainly benefitted from your perspective where you see an opportunity, and you match someone to it and give them a chance to stretch out of themselves and take on some new project or some new leadership role. That has been something that has been really formative for me, as well. I’m not just sucking up. Anita: That is awesome. Eileen: Now is the part where we talk about rocky things. Did you experience any roadblocks along your career journey, and how did you navigate those? Anita: Yes. I think like everybody else. Everyone experiences highs and lows and various challenges that they come across. I think this has to be a pretty common one. The balance of career and family was a tough one for me. My husband and I had kids a while after we were married, 9 1/2 years after we were married or so. For many years we could give our career our all: days, nights. I developed software. I developed missile-guidance systems. I was in labs and never saw sunlight for days, but you can do things like when it’s just yourself or maybe you and a partner. Once I had a family, that was challenging. There was a saying that I came across that I will never forget. It was I think in Forbes Magazine, and the quote was something like, *You can have it all but not all at one time.* It is something that always rings true for me, which is that, I think that when you are trying to balance career and family there are always sort of competing priorities making their way. That is something that takes an understanding and supportive environment and an understanding and supportive leaders and bosses. This is another...Watts was one of my leaders, managers at the time that I was starting to have my family. I was so lucky because I think he was a father of seven. He really valued and cherished family and family priorities. I’ll tell you, it was so helpful. Watts, as well as others at the SEI, I think made this time, which could have been really, really difficult, a lot easier as I progressed. Flexible working hours, some work at home time here and there when you need it, all of these things become really, really helpful as you are trying to juggle your career. It’s the sweet spot of your family, the time you have with your family. It is also a sweet spot of when your career takes off. That is another set of sort of competing priorities. Having leaders that are supportive, I think, make a big difference. I think there is something else. Maybe you and maybe others can relate to this. Over the years, especially early in my career, there were very few examples of women in high profile positions. That becomes important, too, because if you see that another woman is getting promotions or rising in the organization you say, *You know what? I can do that, too.* It gives you a chance. It provides some confidence that the organization values women’s contributions, and it gives you some confidence when you see somebody that you can identify with to say, *You know what, if they can do it, I can do it.* So those were some of things that I’ve encountered. Eileen: There’s a saying, *You can’t be what you can’t see.* Seeing other women in those positions really helps you know that it’s possible. Anita: I very much agree with that. Also, to have a chance to maybe even meet some of those women and understand what was their journey? How did they get there, or how did they do something? Having some of those lessons learned in conversations is really helpful I think. Eileen: That is why this podcast is so much fun for me. Anita: Yes, for me as well. Eileen: Our regular listeners know that I cultivate my reading list by asking the people who mentor and influence me what is on their bookshelves. So I was wondering, what are you reading now, or what books are on your list to do right now that you would recommend? Anita: I rarely have hard copies of books on my nightstand because I get up so early that I am actually pretty wiped out in the evenings. The best time for me to catch up is I love audio books. You will always find two, three, four, five books queued up on my phone because I travel a lot. So it is a perfect time to catch up. There are a few things that are on my list. I really enjoy leadership kinds of books. There is one, I think it’s called *How Remarkable Women Lead, the Breakthrough Model for Work and Life*. That’s one that I think maybe a number of us can relate to, which is, what drives and sustains successful women in the workplace. What are some of their lessons learned and how did they get there and how did they do it. So that is of interest. There is another one I can’t wait to read and it’s *Start Something That Matters* by Blake Mycoskie. He is the person that invented or came up with the idea of *Tom’s Shoes*, if you’re familiar with those. I think they are available in a lot of places. The reason why that’s of interest to me is he created a profitable business but with a greater cause in mind. That was really of interest and really appealing to me. I can’t wait to really dive into that. There’s another book, and it’s on creativity. The author is Ed Catmull, and it’s about how Pixar inspires creativity. So how do the people, I mean they have just the most incredible mission as well in entertainment and children’s entertainment. How do those people constantly keep the creativity engine going? I’m really looking forward to diving into that book, as well. So those are sort of three big ones that I’m looking forward to. Eileen: Great. Now, I have things to add to my e-book collection. I know you and I both commute from similar neighborhoods. We spend a lot of time with our audio books. Can you tell me a little bit about a mistake you have made, a good mistake that you have learned something about professionally or personally? Anita: Yes. This one stings. It still stings. That happens. That is how you learn, I guess. One of the reasons that I had come to SEI—and it was 30 years ago, so it’s hard to believe that it’s been 30 years, but it has been an incredible 30 years, so it’s something that I’m very proud of. One of the reasons I really wanted to come here is because that I knew that CMU had a School of Computer Science, and that computer science program was ranked a top program in the world. I thought, Well, this is great because not only can I learn about the DoD and contribute to the software engineering mission, but it’s an opportunity to also add to my credentials, beef up my credentials. That was an objective that I had. The problem was that I took on a lot more of the consulting role very early on in my career, which meant that like a lot of people in our team do, I left every Sunday or Monday, and I came back every Friday night or Saturday. Then I had one day to repack and kind of do that again. I did that for a long time, maybe 10, 12 years, 15 years. While I don’t regret that I got to know our customers, understand their challenges, and get a much better sense of the Department of Defense and the key programs. I kind of thought, *You know, I’ll do that another time.* Then I took on some other roles and so on. Pretty soon, I put my husband through law school. Then we had our sons. To me it’s a disappointment that I couldn’t find a way to get my PhD then because I feel that something that younger people in their careers should keep in mind is, *If there’s an opportunity to build on your credentials, take those opportunities when you have them.* At the time I thought, *Well, I can’t do this.* Well, maybe there might have been a way to restructure some things. I don’t know. I really didn’t pursue it. I took a few classes. I would sign up. I would withdraw. It just didn’t work out of my schedule, but if I had gone to somebody and said, *You know, this is a really important objective I have. How can we make this happen, or is there a way that we can do?* So to me that is a failure that I didn’t find a way to build on my credentials a little bit earlier on in my career. Because I feel that it’s been something that has haunted me. There are opportunities, and sometimes you don’t have to have a PhD or an advanced degree for everything. People are fabulous and can contribute and excel in a lot of ways but for me, that’s something I wish I would have done. So, it’s a regret. **Eileen:** I appreciate you sharing that with me. So can you tell me now something about yourself that isn’t about work, isn’t about software. Tell me a cool thing about Anita. **Anita:** Yes, I’ll tell you a few things. I have to say that I am most proud, maybe like a lot of us, I am most proud of the family my husband and I have created. Our sons are now already grown up at 22 and 24. Gosh, it’s been the most joyous part of our life. I am most proud of the family that we have created. My kids are sports enthusiast and especially hockey. I have to say that I have proudly earned the title of *Hockey Mom* over the years. We are a huge sports family but especially hockey. That has been just an awesome part of our life. I am very proud to have co-authored a *measurement book*. This was early on in my career with a lot of encouragement from Watts. This was in the early years of the SEI when we were trying to define the field of software engineering. One of the things we were trying to figure out is, *How do we actually instrument the software engineering process?* Of course, measurement was a key part of that. He had really encouraged me to write a book about measuring the software process. With one of his colleagues and friends from IBM, I had co-authored that book. It is something I am incredibly proud of, and Watts wrote the forward to that book. That is something that I always really cherish. I think from my parents, and I think from Watts, I have a love of learning. Just a few years ago, I decided that maybe get going back and getting that PhD wasn’t maybe the right thing for what I was doing now in my career. I went back and I went to MIT, and I got my executive MBA there in two-and-a-half years. It is an accomplishment that I am incredibly proud of. I forgot what it was like to not go out nights and weekends. I had underestimated the amount of homework, but, boy, I loved every moment of it. The colleagues and new friends and sort of the new ideas that I could come back here with. Those are some things. **Eileen:** Anita, thanks so much for joining me today. **Anita:** It’s been my pleasure. **Eileen:** This podcast is available anywhere you get your podcasts including Sound Cloud, Stitcher, and Apple Podcasts. It is available on the SEI website at sei.cmu.edu/podcasts and Apple Podcasts. As always, if you need any additional information or have any questions, please reach out to us at info@sei.cmu.edu. Thanks.
{"Source-Url": "https://resources.sei.cmu.edu/asset_files/Podcast/2019_016_100_636645.pdf", "len_cl100k_base": 4792, "olmocr-version": "0.1.53", "pdf-total-pages": 8, "total-fallback-pages": 0, "total-input-tokens": 25107, "total-output-tokens": 5113, "length": "2e12", "weborganizer": {"__label__adult": 0.0008983612060546875, "__label__art_design": 0.0011034011840820312, "__label__crime_law": 0.0010442733764648438, "__label__education_jobs": 0.43017578125, "__label__entertainment": 0.0004963874816894531, "__label__fashion_beauty": 0.0005426406860351562, "__label__finance_business": 0.00803375244140625, "__label__food_dining": 0.0010538101196289062, "__label__games": 0.001556396484375, "__label__hardware": 0.0008602142333984375, "__label__health": 0.0015439987182617188, "__label__history": 0.0005936622619628906, "__label__home_hobbies": 0.00038743019104003906, "__label__industrial": 0.0006732940673828125, "__label__literature": 0.0010509490966796875, "__label__politics": 0.0019025802612304688, "__label__religion": 0.0009641647338867188, "__label__science_tech": 0.0270233154296875, "__label__social_life": 0.0052032470703125, "__label__software": 0.03271484375, "__label__software_dev": 0.47998046875, "__label__sports_fitness": 0.0008587837219238281, "__label__transportation": 0.0007252693176269531, "__label__travel": 0.0004503726959228515}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 21511, 0.00107]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 21511, 0.00687]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 21511, 0.98584]], "google_gemma-3-12b-it_contains_pii": [[0, 2150, false], [2150, 5331, null], [5331, 8393, null], [8393, 11227, null], [11227, 14280, null], [14280, 17265, null], [17265, 20551, null], [20551, 21511, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2150, true], [2150, 5331, null], [5331, 8393, null], [8393, 11227, null], [11227, 14280, null], [14280, 17265, null], [17265, 20551, null], [20551, 21511, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 21511, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 21511, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 21511, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 21511, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 21511, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 21511, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 21511, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 21511, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 21511, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 21511, null]], "pdf_page_numbers": [[0, 2150, 1], [2150, 5331, 2], [5331, 8393, 3], [8393, 11227, 4], [11227, 14280, 5], [14280, 17265, 6], [17265, 20551, 7], [20551, 21511, 8]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 21511, 0.0]]}
olmocr_science_pdfs
2024-12-12
2024-12-12
88f83ed73fbef1ef131740c128bb97806466836c
1 INTRODUCTION Network commerce has consequences that go far beyond just a business model. [...] Markets are based on mistrust, networks on trust. Markets are based on the pursuit of self-interest, networks on shared interest. Markets are arm’s-length transactions, networks are intimate relationships. Markets are competitive, networks are cooperative. (Jeremy Rifkin ([18], p. 192 f)) The intra- and inter-company work models change from classic, pre-defined, inflexible business processes to agile value creation networks. Human, machines and software collaborate in an integrated and coordinated way to fulfill their objectives. This necessitates a new dimension of agility, speed of transformation and individuality. We strongly believe that we need an open network of self-coordinating, modular components that offer fully-fledged interoperability to tackle these challenges on the way to autonomous software systems. At the same time such a network will offer an economic alternative to the classic, centralized platform models and standards of the current IT-industry. These, e.g. BPMN, “fail to guarantee that standard-conforming business process models are interoperable (platform-independent)” ([4]). Some scientists are already aware of these challenges and laid out fundamental groundwork. Christian Stary proposes “a System-of-Systems specification as a network of cooperating behavior entities” ([19]). These and similar ideas converge on the creation of a new era in systems design. This whitepaper presents a methodology, a modular concept and the foundation of the Internet of Actors (IoA). The IoA will reduce complexity, programming efforts and unclear interfaces while creating an Interoperability Network. It is going to be an enabler for agile, decentralized, self-coordinating value creation networks, acting as the catalyst for the Internet of Things, Digital Transformation and Industry 4.0. 2 SMART ACTORS To create such an agile value creation network we first need to focus on the atomic components (= the nodes and their respective relations) the network is comprised of. Smart Actors (SMA) are the basic building blocks of the IoA. As the IoA is designed as a network, the network nodes need the respective capabilities to deal with challenges like inter-company collaboration in a (self-)coordinated, modular encapsulated manner (mentioned in 1 Introduction). 2.1 Requirements The main requirements to the network nodes are similar to the requirements that can be observed with the architectural pattern of microservices (based on [11]), as microservices can also be interpreted as dedicated nodes in network-like applications: (MS1) determine the functional scope based on a single business capability that is decomposed on its lowest level for the domain applicable (MS2) consistent encapsulation leading to very clear interfaces to other network nodes (e.g. according to the Law of Demeter [25]: each unit should have limited knowledge about other units) (MS3) "smartness" ("smart endpoints, dumb pipes" [11]) in a sense of being able to do everything needed to add value with its actions without doing "too much" (YAGNI-dilemma [31]) (MS4) independently releasable without being in the need of other components thus ensuring independent lifecycles of the different nodes (MS5) self-organizing - in regards to building a network, the nodes must be able to connect to each other in a meaningful way thus ensuring added value in terms of Aristoteles’ synergy-principle (the whole is greater than the sum of its parts [27]) and tackling the issue of messy service connections ([11]) by using a clear (and yet flexible) communication structure between different components (MS6) asynchronous connections between single network nodes in order to ensure resilience to temporarily breakdowns (due to infrastructure, scalability or timing issues in parts of the network) To meet these requirements, we propose the creation of Smart Actors as nodes and therefore as core building blocks of the peer-to-peer agile value creation network. Therefore, a Smart Actor is able to: (R1) fulfill a well-defined task (R2) "know" the execution-logic needed to fulfill this task, including decision-rules, different paths etc. (R3) gather and hold all data needed for the task (R4) offering a means to extract the essence of the task in a machine-readable way (as an enabler for self-organization) (R5) connect to arbitrary software-interfaces or physical machines in order to exchange data (R6) present its data to human users and offer possibilities to change these data or take decisions where defined by the SMA (= "frontend"/ UI [30]) (R7) communicate with other SMAs via well-defined protocols to gather information and/or to propagate its output(s) (R8) has its own release cycle (= being independently releasable) without being directly affected by the release cycles of others (R9) can be executed in a software system by interpreting or compiling its definition/source code The foundation of our Smart Actors can be found in software design concepts reaching back to the 1970’s. 2.2 The Foundation of Smart Actors: PASS In 1994, Albert Fleischmann proposed a concept called “SAPP/PASS” (Structured Analysis of Parallel Programs in conjunction with Parallel Activities Specification Scheme, [8], pp. 204 ff). This scheme is based on Milner’s and Hoare’s Calculus of Communicating Systems (CCS, [15]) which has later been developed into the Pi-calculus ([16]). 2.2.1 Calculus of Communicating Systems (CCS). Fleischmann describes the CCS as a “theoretically very important technique for describing the behaviour of processes explicitely” ([8], p. 130). Paraphrasing [8] (pp. 130-134), the CCS offers the following: The behaviour of a process is described as a rooted, unordered, finite branching tree. The initial state of the process is represented by its root. Branches are labelled and represent actions or transitions to a next state. The CCS distinguishes observable and unobservable actions. The trees offer elementary algebraic operations (see figure 1). These operations obey basic algebraic laws (associativity, commutativity and nullity, see figure 2). The trees are called behaviour trees (describing processes). Expressions represent these trees (see figure 3): After step a has been executed, steps b or c can be executed next. It is also possible to model agents with infinite behaviour in CCS. Figure 4 illustrates agents X and Y, both with 1 In our case, a “process” will become a Smart Actor 2 = its algorithm 3 observable or unobservable from outside of the process 4 in our terms later: Smart Actors potentially finite behaviour\(^5\), and agent \(Z\) with a definite infinite behaviour. Albert Fleischmann also focuses on the fact that for each observable action there exists a complementary (or: inverse) action in CCS. It is possible to link multiple agents together. If there exist complementary actions in the different behaviour trees, these agents can communicate in synchronous message exchanges\(^6\) (see [8], p. 132). In general, CCS offers a graph-style\(^7\) approach to model complex behaviours\(^8\) and communication between these. 2.2.2 Parallel Activities Specification Scheme (PASS). Based on the CCS\(^9\) Albert Fleischmann developed the Parallel Activities Specification Scheme (PASS) in conjunction with a method for Structured Analysis of Parallel Programs (SAPP). SAPP is a means to decompose complex systems into small, easy-to-handle components. These components are able to be executed in parallel and to call each other via clearly defined message channels ("message-types" [8], p. 205). Figure 5 exemplifies such a SAPP specification, where \(T\) can send messages of type \(M_3\) to \(P\) and \(P\) can send type \(M_2\) to \(T\)\(^10\). This type of diagram represents possible communication channels, but has no time, sequence or frequency restrictions. PASS is used to define a single "process" ([8])\(^11\). A PASS description contains information about synchronization of messages ("input pool"\(^12\)), a graph representing the process behaviour (= algorithm/"intelligence" of the SMA) and process-refinements handling data operations. The SAPP/ PASS concepts have also been adopted by parts of the Business Process Management (BPM) community ([9])\(^13\). In contrast to classic BPM methodologies, PASS is able to focus on actors and/or agents involved in business processes. These can be humans, software components or machines in mixed setups. One reason for this adoption by the BPM community, similar to the advantages/main features of software system development using PASS, is its Turing Completeness ([28]). This has been proven by an interpreter model based on Abstract State Machines (ASM, [12] and [6]), which are based on Finite State Machines. As PASS graphs themselves represent state machines, they can be interpreted like program source code. Therefore it is possible to execute a PASS model instantly without being forced to transform or manually code it. Egon Börger created such an interpreter "for both simulation (testing) and verification (logical analysis of properties of interest) of classes of S-BPM\(^14\) processes" ([5]). The original SAPP/ PASS methodologies unfortunately define that "in the PASS model each system consists of a fixed number of processes\(^15\) and each process has a unique name" ([8], p. 205). But to achieve independent releasability it is paramount that SMAs do not have fixed communication channels to other actors and allow agile reconfiguration of the communication network they are part of. 2.3 Independent Releasability of Smart Actors To tackle the requirement of independently releasable components, we created a concept of well-defined but loose-bound communication channels. This concept is based on CCS, ASM and PASS. Even if PASS in \(^5\)if transition \(X(a)\) or \(Y(e)\) is executed \(^6\)as opposed to asynchronous message exchange, which we will focus on later \(^7\)corresponds to tree-style \(^8\)matches in this case the term "algorithms" \(^9\)and other methods, [8], p. 201 \(^10\)for completeness of the example: \(Q\) can send \(M_1\) to \(P\), \(P\) can send \(M_1\) to \(R\), \(R\) can send \(M_2\) to \(P\) \(^11\)\(=\) Smart Actor in our terms \(^12\)Input pools are one of the most important concepts of PASS as they enable messages to be sent either synchronous or asynchronous between components and even offer possibilities to restrict the number of messages being received at a certain time etc. Without input pools, especially the crucial asynchronous communication would not work. We do not explain the details of this concept, as they are not needed for grasping the general communication of SMAs. \(^13\)English, enhanced version of the original (German) book: [10] \(^14\)S-BPM corresponds to PASS in our context \(^15\)again: process maps to Smart Actor in our context conjunction with SAPP basically tries to model and execute complete, enclosed systems. PASS graphs can be used to discern one or more observable behaviours. We use a PASS graph as constituting component of a Smart Actor. An observable behaviour is basically a reduced version of the PASS graph, focusing on the communication that can potentially happen with one specific communication partner (= another PASS graph). This can be named "role-based behaviour interface (RBI), as every communication partner acts in a specific role in its relation to the PASS graph in focus. It follows that a RBI can be created for every potential communication partner of a PASS graph. Figure 7 shows a graph $X$ that depicts communication with 2 different partners (partner 'A' and partner 'B'). Therefore 2 RBIs can be extracted from this graph. The RBI from $X$ to $A$, $RBI(X, A)$ consists of all possible message flows between $X$ and $A$, their direction and their structural content. To the relation between $X$ and $B$ applies the same, there is an $RBI(X, B)$. To every $RBI(graph_x, graph_y)$ (1) there exists an inverse $RBI'(graph_x, graph_y)$ (2). $$RBI(graph_x, graph_y) = \text{original Smart Actor}$$ $$RBI'(graph_x, graph_y) = \text{potential Communication Partner}$$ This inverse $RBI'$ is a tree performing the same message flows like $RBI$, but does a send where in $RBI$ there is a receive and a receive where there is a send. It is possible to find any SMA $Z$ that has one of its RBIs that corresponds to $RBI'$ (3). $$RBI(Z, Z') = RBI'(X, Z)$$ This means that these PASS graph representations of SMAs are able to communicate with each other; in this case, they can be connected (4 - 6): $$\Rightarrow Z' = X$$ $$\Rightarrow RBI(Z, X) = RBI'(X, Z)$$ $$\Rightarrow RBI(X, Z) = RBI'(Z, X)$$ If there are a lot of Smart Actors known, there may be more than one Smart Actor that can be found as a potential communication partner. In this case, rules on the communication context --- $^{16}$ with asynchronous communication within the system $^{17}$ see also CCS's observable actions, section 2.2.1. PASS graphs can also be transformed to CCS behaviour expressions, which aren't as powerful as some PASS features ([8], p. 259 ff), but are therefore suitable to "observe" the communication behaviour $^{18}$ sending messages or receiving messages $^{19}$ intentionally left out information about the types of the graph's states (send, receive, do (internal)) to focus on the RBI explanation. --- $^{20}$ by structural content we mean data structures (and semantics) transported by a message $^{21}$ or are being able to be discovered via address books, Smart Actor Name Systems (SMANS) etc. The Internet of Actors - A Peer-to-Peer Agile Value Creation Network could have been set within the SMAs themselves, further restricting the possible communication partners. Selection strategies (like "bestRated", "nearest", "firstComeFirstServe", ...) can apply additionally. This approach shows that a Smart Actor does not have to be connected with its communication partners before deployment for execution, as the RBIs make it possible to find suitable communication partners even at execution time (see also [20]). This represents also a difference to Agha’s approach ([2]) to software actors, as we do not need direct addressing of other actors, but can use rule based addressing (RBA) via RBIs. 2.4 Definition of Smart Actors Keeping the requirements (see 2.1), the foundational concepts CCS (see 2.2.1), ASM, PASS (see 2.2.2) and our thoughts on independent releasability (see 2.3) in mind, we can design a Smart Actor as follows: (SMA1) The pivotal part is the definition of an internal behaviour graph22. The behaviour graph consists of states with the 3 basic operations (send, receive, do), transitions between these states and references to the SMA’s data (see SMA2). The behaviour represents the smartness (or: algorithm), helping the Smart Actor to (SMA1) fulfill its task (requirement (R1)), (SMA2) know the execution logic needed (requirement (R2)), (SMA3) represent decision- and other rules as these are mapped to behaviour and communication (requirements (R2) and (R7)) (SMA4) extract the RBIs for defining the communication interfaces to other SMAs (requirement (R7)) - thus creating interoperable building blocks (SMA2) Additionally, a complete data structure can be defined for every Smart Actor. This data structure contains everything the SMA needs within its behaviour (requirement (R3)). (SMA3) If the Smart Actor is a Service Actor or Physical Actor, meaning it connects to microservices or arbitrary software components or software interfaces, it needs a Service Mapping for each of its do-states, defining calls and data exchange to and from these systems (requirement (R5)). (SMA4) In case the Smart Actor is intended to support a human in executing a task23, user interfaces (UI) can be defined by mapping to the do-states24 and data structures available, thus creating executable views on the Smart Actor (requirement (R6)). (SMA5) Metadata in a structured format are intended to offer machine- and human-readable data about the SMAs essence, intentions (see [22]), creators, costs and other useful information (requirement (R4)). (SMA6) As the extracted RBIs define communication interfaces instead of a tight coupling to other components, a SMA’s releasability/ deployability is completely independent from others. Therefore, a Smart Actor represents a self-contained component (requirement (R8)). (SMA7) Due to its ASM-based, Turing-complete nature, a SMA can be executed by interpreting its behaviour graph (requirement (R9)). In summary, these Smart Actors fulfill all requirements listed in section 2.1 Requirements. Therefore, SMAs can also be used to execute SmartContracts ([26] and [32] p. 37 ff) or act as DApps ([23] and [32] p. 39 ff). A possible XML data format for describing SMAs is proposed in [21]. 3 A PEER-TO-PER AGILE VALUE CREATION NETWORK The concept of Smart Actors allows the creation of a peer-to-peer agile value creation network which we call The Internet of Actors (IoA). We want this network to facilitate a clean architecture and stick to an important principle (known from bitcoin [17], p. 8): “The network is robust in its unstructured simplicity. Nodes work all at once with little coordination”, whereas ‘coordination’ is equivalent to ‘no centralized orchestration’. 3.1 Definition of the Peer-to-Peer Agile Value Creation Network The SMAs represent the main building blocks and are the nodes within the network. The characteristics of this network are: Peerto-Peer The SMAs can be executed in decentralized environments. If a Smart Actor has the means to find communication partners and message with them (see 3.3), the whole network can be built up in a distributed manner without having a centralized structure. Agile Smart Actors do not employ a tight coupling, but they are entirely uncoupled and independent from other SMAs. That allows the (self-sustaining) configuration of the network to change at any time with the addition, the removal or the update of new or existing Smart Actors (see 3.3). Each network node is part of one or more choreographies25 that emerge from the communication protocols (= RBI) and rules set by any SMA. Value Creation Objective of every SMA is to create a value (i.e. in terms of a capability), by transforming any inputs to any outputs26. Thus, in the network as a whole, there will be a multitude of focal areas (= choreographies) of value creation. Due to the synergy-principle ([27]) the total of value creation will be higher than the combined value-deltas of every single SMA involved. Network We talk of one single network instead of multiple networks, as - due to its decentralized character - all Smart Actors can contribute and will be part of the global network of collaboration and (therefore) interoperability. Similar to most blockchain-based peer-to-peer technologies, this network shall offer a standardized, open access for everyone who wants to contribute to the network, e.g. by creating new Smart 22A Smart Actor can have more than one behaviour graph for specific applications like Message Guards (see [10], p. 120 ff). Behavior Macros (see [10], p. 112 ff) etc. 23we call that a Business Actor 24there are also special UI’s possible for receive 25For definitions of the term “choreography” see [14] 26In- and outputs of SMAs are always messages within their respective communication patterns Actors. To facilitate this open access it is paramount to create two areas of standardization. 3.2 Internet of Actors Notation (IoAN) One area of standardization is the Internet of Actors Notation (IoAN) which will cover: - (IoAN1) the complete definition of SMAs (see 2.4 Definition of Smart Actors), - (IoAN2) the notation of the RBIs, - (IoAN3) means to show and visualize choreographies of SMAs. As mentioned before, first concepts regarding (IoAN1) have already been proposed ([21]) and implemented. Furthermore there is a standardization group working on an OWL-definition of an exchange format ([7]). 3.3 Smart Actor Operating System (SMAOS) The second area of standardization is a Smart Actor Operating System (SMAOS). As discussed before (see 2.4 Definition of Smart Actors), Smart Actors can be executed without any further preparations. For this execution, an operating system is needed, that serves three main purposes. The SMAOS - (SMAOS1) can interpret and therefore execute SMAs, - (SMAOS2) facilitates communication between Smart Actors on the same SMAOS instance and across different SMAOS instances, and - (SMAOS3) enables the discovery of other SMAs as potential communication partners. With actnconnect’s Actosphere ([1]) there exists a first implementation of a SMAOS. To address the issue of messaging between Smart Actors (see (SMAOS2)) in regards to transportation layers and formats, we propose the definition of a Smart Actor Communication Protocol (SMACP). The SMACP could also comprise possibilities to use blockchain technologies (like Hyperledger Fabric ([13] and [32] p. 40 f) or dedicated blockchains) for facilitating distributed storage of messages or even SMA system states. The discovery of SMAs and/or SMAOS instances anywhere in the IoA (see (SMAOS3)) requires a Smart Actor Name System (SMANS). Techniques like the Satoshi Client Node Discovery ([3]), the Domain Name System ([24]), UDDI ([29]) or similar might be used as an inspiration to define such SMANS. Putting all these definitions together, the components of the IoA will be well-defined, executable, communicating and the network can be accessed openly without any discrimination or censorship. 4 CONCLUSION The concept of Smart Actors presents a method and implementation of the central building blocks of a peer-to-peer agile value creation network. From a methodological point of view the SMAs offer all basic capabilities to build such a network due to their clear and open communication interfaces (RBIs). They enable communication between different network nodes regardless of their nature. Therefore the Internet of Actors can connect humans, machines and software to facilitate their individual contributions to shared and individual objectives. In a technical sense the Smart Actors are not just "structured" microservices but represent the base components for a new internet, the IoA. Even the very foundations of this network, administrative tools, can be described and implemented by SMAs. The IoA is therefore self-sustaining and self-extending. Individual value contributions\(^\text{27}\) can be priced and settled by means of the IoA itself in connection with blockchain-based techniques. Our further efforts need to go into - (ToDo1) the standardization of IoAN and SMAOS, - (ToDo2) the creation and facilitation of a growing community of (value) contributors for the IoA, - (ToDo3) the detailing of business models within the IoA and - (ToDo4) the creation of application examples for the building blocks and the value creation network itself. The IoA offers a serious economic alternative to the centralized platform models available today. The IoA comprises ideal conditions to 'go far beyond just a business model', but to build cooperative relationships based on trust to pursue shared interests ([18], p. 192 f). ACKNOWLEDGEMENTS We want to thank Christian Stary, Albert Fleischmann, Felix Gniza, Anton Friedl, Werner Schmidt, Matthias Lederer and the members of the I2PM community for the fruitful discussions and their support. \(^{27}\) remember: outputs will be sent in form of messages = communication The Internet of Actors - A Peer-to-Peer Agile Value Creation Network REFERENCES ACRONYMS ASM Abstract State Machines BPM Business Process Management CCS Calculus of Communicating Systems DApp De-centralized App DNS Domain Name System IoA Internet of Actors IoAN Internet of Actors Notation IoT Internet of Things OWL Ontology Web Language PASS Parallel Activities Specification Scheme RBA Rule Based Addressing RBI Role-based Behaviour Interface SAPP Structured Analysis of Parallel Programs SMACP Smart Actor Communication Protocol SMANS Smart Actor Name System SMAOS Smart Actor Operating System UDDI Universal Description, Discovery, and Integration XML eXtensible Markup Language
{"Source-Url": "http://ceur-ws.org/Vol-2388/paper2.pdf", "len_cl100k_base": 5364, "olmocr-version": "0.1.53", "pdf-total-pages": 7, "total-fallback-pages": 0, "total-input-tokens": 25544, "total-output-tokens": 7552, "length": "2e12", "weborganizer": {"__label__adult": 0.00033545494079589844, "__label__art_design": 0.0006465911865234375, "__label__crime_law": 0.00044465065002441406, "__label__education_jobs": 0.000934600830078125, "__label__entertainment": 0.00012350082397460938, "__label__fashion_beauty": 0.0001703500747680664, "__label__finance_business": 0.0020618438720703125, "__label__food_dining": 0.00038743019104003906, "__label__games": 0.0005679130554199219, "__label__hardware": 0.0012273788452148438, "__label__health": 0.0005106925964355469, "__label__history": 0.0004642009735107422, "__label__home_hobbies": 0.0001145005226135254, "__label__industrial": 0.0006875991821289062, "__label__literature": 0.0005497932434082031, "__label__politics": 0.0005559921264648438, "__label__religion": 0.0004992485046386719, "__label__science_tech": 0.1654052734375, "__label__social_life": 0.00014734268188476562, "__label__software": 0.0278472900390625, "__label__software_dev": 0.794921875, "__label__sports_fitness": 0.00024437904357910156, "__label__transportation": 0.0007758140563964844, "__label__travel": 0.0002505779266357422}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 28701, 0.03217]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 28701, 0.56736]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 28701, 0.88768]], "google_gemma-3-12b-it_contains_pii": [[0, 2544, false], [2544, 6671, null], [6671, 10988, null], [10988, 13697, null], [13697, 19544, null], [19544, 23694, null], [23694, 28701, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2544, true], [2544, 6671, null], [6671, 10988, null], [10988, 13697, null], [13697, 19544, null], [19544, 23694, null], [23694, 28701, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 28701, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 28701, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 28701, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 28701, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 28701, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 28701, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 28701, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 28701, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 28701, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 28701, null]], "pdf_page_numbers": [[0, 2544, 1], [2544, 6671, 2], [6671, 10988, 3], [10988, 13697, 4], [13697, 19544, 5], [19544, 23694, 6], [23694, 28701, 7]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 28701, 0.0]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
7b7ef2418df67eb101c420d8c865a800d9722304
[REMOVED]
{"len_cl100k_base": 4243, "olmocr-version": "0.1.50", "pdf-total-pages": 5, "total-fallback-pages": 0, "total-input-tokens": 16242, "total-output-tokens": 6145, "length": "2e12", "weborganizer": {"__label__adult": 0.0005145072937011719, "__label__art_design": 0.0005373954772949219, "__label__crime_law": 0.0006394386291503906, "__label__education_jobs": 0.0029964447021484375, "__label__entertainment": 0.00021564960479736328, "__label__fashion_beauty": 0.0002951622009277344, "__label__finance_business": 0.000560760498046875, "__label__food_dining": 0.000606536865234375, "__label__games": 0.000835418701171875, "__label__hardware": 0.0008153915405273438, "__label__health": 0.0010900497436523438, "__label__history": 0.0004041194915771485, "__label__home_hobbies": 0.00015151500701904297, "__label__industrial": 0.0007457733154296875, "__label__literature": 0.0016336441040039062, "__label__politics": 0.0005164146423339844, "__label__religion": 0.0006732940673828125, "__label__science_tech": 0.2236328125, "__label__social_life": 0.00028824806213378906, "__label__software": 0.01361846923828125, "__label__software_dev": 0.74755859375, "__label__sports_fitness": 0.00048470497131347656, "__label__transportation": 0.0008063316345214844, "__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, 22916, 0.02799]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 22916, 0.36102]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 22916, 0.85522]], "google_gemma-3-12b-it_contains_pii": [[0, 5459, false], [5459, 9503, null], [9503, 15292, null], [15292, 16775, null], [16775, 22916, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5459, true], [5459, 9503, null], [9503, 15292, null], [15292, 16775, null], [16775, 22916, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 22916, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 22916, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 22916, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 22916, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 22916, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 22916, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 22916, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 22916, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 22916, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 22916, null]], "pdf_page_numbers": [[0, 5459, 1], [5459, 9503, 2], [9503, 15292, 3], [15292, 16775, 4], [16775, 22916, 5]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 22916, 0.13208]]}
olmocr_science_pdfs
2024-11-29
2024-11-29
fe7107b62ea3758fc3dcedfd67e0ae56e522e260
Borst, Timo; Lehmann, Maren; Pianos, Tamara; Witt, Nils **Article** **Taking Libraries’ Cultural Content to the User – Approaches and Experiences from the EEXCESS Project** **LIBER Quarterly** Suggested Citation: Borst, Timo; Lehmann, Maren; Pianos, Tamara; Witt, Nils (2016) : Taking Libraries’ Cultural Content to the User – Approaches and Experiences from the EEXCESS Project, LIBER Quarterly, ISSN 2213-056X, LIBER, Den Haag, Vol. 26, Iss. 3, pp. 125-140, http://dx.doi.org/10.18352/lq.10168 This Version is available at: http://hdl.handle.net/11108/274 **Kontakt/Contact** ZBW – Leibniz-Informationszentrums Wirtschaft/Leibniz Information Centre for Economics Düsternbrooker Weg 120 24105 Kiel (Germany) E-Mail: info@zbw.eu http://zbw.eu/de/ueber-uns/profil/veroeffentlichungen-zbw/ **Standard-Nutzungsbedingungen:** **Terms of use:** This document may be saved and copied for your personal and scholarly purposes. You are not to copy it for public or commercial purposes, to exhibit the document in public, to perform, distribute or otherwise use the document in public. If the document is made available under a Creative Commons Licence you may exercise further usage rights as specified in the licence. http://creativecommons.org/licenses/by/4.0 **Kürzel:** zbw Taking Libraries’ Cultural Content to the User – Approaches and Experiences from the EEXCESS Project Timo Borst ZBW Leibniz Information Centre for Economics, Germany t.borst@zbw.eu, orcid.org/0000-0002-2481-029X Maren Lehmann ZBW Leibniz Information Centre for Economics, Germany m.lehmann@zbw.eu Tamara Pianos ZBW Leibniz Information Centre for Economics, Germany t.pianos@zbw.eu, orcid.org/0000-0002-4386-519X Nils Witt ZBW Leibniz Information Centre for Economics, Germany n.witt@zbw.eu Abstract Before the advent of the internet users had to physically visit libraries and other cultural institutions in order to search, find and access content. With the emergence and massive use of the World Wide Web and associated tools and technologies this situation has changed drastically. If content is to be found and used, it must be present where users do their daily digital work. The aim of the This work is licensed under a Creative Commons Attribution 4.0 International License Uopen Journals | http://liberquarterly.eu/ | DOI: 10.18352/lq.10168 Liber Quarterly Volume 26 Issue 3 2016 EU project EEXCESS (http://eexcess.eu/) is to inject the content into the working environments of the users. In this paper, we show some of the approaches, use cases and technical implementations we developed in the project. **Key Words:** cultural content; automatic recommendations; EU-project; privacy; Open Source 1. Introduction Libraries and related cultural institutions used to have a monopoly on providing access to books or journals and to information in general. Users had to physically visit a place in order to find and access library content. Today, the internet and especially technologies like search engines, content hubs like Wikipedia and social media platforms have become means of information and content provision. A lot of high quality content is freely available on the internet. However, users often cannot access all of the relevant content, because they either do not know it exists, or do not know the specialized search engines or databases they need to access, or do not have the domain knowledge to formulate appropriate search queries. Users very often start their searches either by using the big search engines, mostly Google, or they start their search in Wikipedia (Dzeyk, 2015; Rowlands et al., 2008). Thus, very specific items – like e.g. the image of a special historical garment – may be overlooked as they do not appear on the first two or three pages of the major search engines. If libraries and other cultural institutions still want their content to be found and used, they must adapt to these new environments in which users expect digital content to be available and accessible directly and at once. Libraries have reacted to the new challenges in a number of different ways, e.g. by making their content more visible in search engines through search engine optimization (SEO), by aligning their online services with user expectations through discovery systems or by offering their services at the point of need via chat or mail. The EU-funded project EEXCESS,1 on the other hand, aims to provide another solution for this challenge: Libraries and cultural institutions can deliver their online content directly to the users who will be able to work with their favourite tools and still find information otherwise hidden. Museums, archives, libraries, etc. possess immeasurable resources of cultural, scientific and educational content. Their holdings comprise of scientific research, historical sound recordings, images of sculptures, films, sheet music and much more. This highly specialized, carefully curated content is still largely invisible to the general public. In the internet context it is therefore often referred to as the long-tail (i.e. a huge body of specialized knowledge existing in the World Wide Web, but hidden from most users).² The vision of EEXCESS is to connect these valuable resources with the main stream content available via internet giants such as Google, Facebook and Wikipedia. EEXCESS is based on the simple principle of taking the content to the user, not the user to the content. It wants to bring the information directly to the users’ working environment, on their favourite platforms (Facebook, Twitter etc.) and their preferred devices (tablets, smartphones etc.). Instead of having to navigate through a multitude of libraries, repositories and databases, users should be able to find relevant and specialized information in their habitual environment. The long-tail content is brought to the surface, where it can be put to new and different uses.³ The general aim of EEXCESS is to ‘inject’ digital content into users’ everyday work environments like browsers, content management systems, a word processing programme or e-learning environments. Content, thus, is recommended by means of an organizational and technical framework of distributed partner recommenders and user profiles. The unique data sources in conjunction with EEXCESS technologies for recommendation and visualization offer new approaches to discover the best possible results for academic and cultural content. Relevant academic and cultural content can only be recommended if it is covered by the EEXCESS content partners. Institutions with cultural or academic texts, images etc. can offer their content for inclusion in the EEXCESS recommender in order to make it more visible to potential users. The EEXCESS project has 10 partners in four countries who are responsible for different aspects like the recommender, privacy issues or visualizations. The project started in February 2013 and ended in July 2016. In this paper, we show some of the approaches, use cases and technical implementations we developed in EEXCESS. We outline some use cases which we conceive as representative for our target groups (students and researchers). Protecting the privacy of the users in connection with personalized recommendations is a major task and effort of the project, so we will briefly cover the implications. We conclude the paper by depicting some of the approaches towards achieving dissemination and sustainability of the project results. 2. Application Scenarios: Use Cases The EEXCESS software prototypes work in different ways to support online research (content consumption) like looking for information on a particular topic or conducting studies. They also help with writing or editing a Wikipedia article, a blogpost, a Moodle entry or a Google Docs document (content production). At the beginning of the project, numerous use cases were identified to cover realistic examples of how students, teachers, researchers or librarians go about their work of searching for information or sorting content etc. 2.1. Content Consumption As an example of content consumption, we take a student researching a topic for a presentation. After a quick search in Google she reads a Wikipedia article in her browser (Figure 1). During the reading process, further information matching the topic of the article – or a section of it – is automatically recommended by EEXCESS. This example shows a relatively short Wikipedia article on the Ergolz, a river in Switzerland. When users search for Ergolz on Google they find the corresponding Wikipedia entry. But they also find a local hospital, tourist information, a Veterinarian as well as a miniature golf course. The EEXCESS extension on the right side of the screen shows pictures and documents on this topic from specialized cultural and academic databases that would otherwise remain hidden in the long tail of the internet. This example works well in EEXCESS because a museum of this region in Switzerland (Archäologie und Museum Baselland) is one of the project partners and early content providers. The more content providers have their content included in the EEXCESS recommendation, the more satisfying results will probably be delivered to searches in different contexts. 2.2. Content Production As an example of content production, we consider e.g. the creation and publishing of a blog post, which is supported by automatic recommendations of related documents. After writing the first few lines or paragraphs in the WordPress editor, the EEXCESS plugin can be activated to provide context sensitive recommendations. These documents can easily be inserted and cited in the blogpost using different citation styles. In the same fashion, the plugin also allows users to easily embed images, e.g. for illustrating a blog post (Figure 2). Another example for content production would be the writing or editing of a Wikipedia article. The Wikipedia Reference Butler (WRB), another EEXCESS prototype supports editors by showing suitable media-files from WikiCommons (media-container of Wikimedia) to be added to articles and it shows suitable references to scientific literature matching the context of the article.5 3. Toolbox: EEXCESS Prototypes, Content, and Partner Wizard All applications developed in the project are available through the EEXCESS website and can be used freely. The code for the prototypes is freely available under the terms of the Apache 2.0 Licence. 3.1. EEXCESS Prototypes A wide range of prototypes was developed in the project in order to cover a couple of content consumption and production scenarios.6 The prototypes and modules are: The most elaborate EEXCESS prototype is a Chrome browser extension. An unobtrusive icon can be used to trigger the recommendations and change the settings etc. The window showing the recommendations can be resized according to screen size and personal preferences. Multiple options for filtering the results are available to find specific (like e.g. images or publications from a specific era) or serendipitous results. The Chrome extension was optimized for the use in Wikipedia and works best with English language results, but it can also be used with any other website opened in the Chrome browser. Depending on the software component installed on either a user’s local machine or an application server, the list of recommendations is displayed in different ways: from a classical, text-oriented list, to a visualization of metadata records (Figure 3). Different visualizations can be used to break Fig. 3: One display option in the Chrome extension Visualization Dashboard. down the number of recommendations (Veas, Mutlu, di Sciascio, Tschinkel, & Sabol, 2015). 3.2. EEXCESS Content Some of the project partners also act as content providers: Museum Baselland, Mendeley, and EconBiz/ZBW. Another early content provider is Europeana. During the last year of the project a number of other content providers were included: The Digital Public Library of America, The National Archives UK, Swissbib, Deutsche Digitale Bibliothek, Rijksmuseum – The Museum of the Netherlands, and Core.ac.uk, so that EEXCESS can now recommend contents from ten different providers covering a wide range of cultural and academic topics. More than 150 Mio items can be found through EEXCESS in August 2016. New content can be easily submitted for integration by anyone who owns a repository or database with academic or cultural content accessible through an Application Program Interface (API) supporting search functionalities. 3.3. Submitting Content for Inclusion and Partner Wizard Institutions are encouraged to make their digital content and metadata discoverable through the EEXCESS recommendation technology. EEXCESS is not a content aggregator or archive, but a broker between cultural, educational and academic content and users. Providers who want to provide suitable content need to have a search API and comply with some metadata standards (Orgel, Höffernig, Bailer, & Russegger, 2015). EEXCESS accepts metadata about items in partner collections in LIDO or EDM standards. All metadata supplied by content providers to the EEXCESS aggregation infrastructure will be converted, without user intervention, to the EEXCESS metadata scheme [similar to Europeana Data Model (EDM)]. Every digital object needs to be published with a rights label that describes its copyright status. The partner wizard helps to customize the connection from the new database to the EEXCESS framework, i.e. if the new database delivers best results to queries formulated with AND or OR operators, the recommender will adapt this behaviour when querying the new database. New partners can click through result lists generated by prepared queries and thereby optimize the queries, rather than writing program code or metadata mappings themselves. The optimal results will be found automatically with the help of the partner wizard. Once a content partner has connected to this framework, the results will be listed and merged with the results of the other partners (Figure 4). 4. User tests and Feedback All prototypes developed during the project were tested by users. This was repeated in different stages of prototype development. As a general outcome, the overall acceptance of EEXCESS content and tools is high, but depends heavily on the relevance of the recommendations and usability of the software components. The first prototypes were created early in the project. It was quite obvious that they would not be able to meet all user expectations, but user tests were still conducted at early stages in order to get feedback and adapt the application. During the first part of the development many users said they liked the features and saw the potential of the project. However, the recommendations actually provided – especially by the early prototypes – were not matching the expectations of a number of users due to a couple of (technical) issues. The first recommendation tool did not work well with the different types of databases responding in many different ways. Also, there were only a small number of content providers hooked up to the central system in the beginning, so that there was only a relatively small pool of recommendations. Over the course of the project the recommendation system was fine-tuned and more content was integrated, so that the matching was improved. A number of experiments were conducted to enhance personalized recommendations (Seifert, Schlötterer, & Granitzer, 2015). A user test was conducted at a computer lab at the University of Passau with 77 individuals. The Chrome Browser with the EEXCESS extension was used for testing. The experiment was focussed on the following questions: - How accurate is the extraction/detection of paragraphs on a page? - Are users satisfied with the automatic query, in general? - What is a satisfying query? - Does the personalisation work? - What is the influence of explanations on perceived quality and trust? The test persons considered the quality of paragraph extraction/detection to be quite high. However, in general the rating of query results still varies a lot. At the time, there were no clear positive effects of personalization. Language filters are required by users to eliminate results in languages that they do not understand.9 Towards the end of the project the major findings of user tests and feedback are: - The different implementations are accepted as useful; - Easy to understand, simple components are more easily accepted than more complex components; - The more data providers are included, the better the results, - Respondents in several test beds stated that a client technology for Microsoft Word would be desirable. The quantitative evaluation revealed that both, the number of data providers and client technology have increased significantly since the last evaluation. This is a positive sign implying that the take-up by programming communities starts to show effect. 5. Privacy Protection A key objective of the project is privacy protection. Therefore, a dedicated work package focusing on privacy issues while providing personalized recommendations at the same time was part of the project. Private, sensitive information is exchanged at multiple levels like for example during recommendation and usage mining. Individuals reveal information about their usage behaviour through e.g. click rates, technical details of the devices used, profile information with respect to topical interests etc. Wherever data about individuals is involved, this raises privacy issues. On the other hand, relevant recommendations are best achieved if they are tailored to the user needs and preferences. Hence, privacy protection plays an important role in the research goals of EEXCESS. The project partners developed and implemented methods and protocols that guarantee privacy-preserving augmentation, recommendation, and user mining. All user profiles and context information are stored on the user’s device (instead of a central server), submitting only very little information to the recommender system. Data is only collected with prior and explicit permission by the user and it is anonymized. Furthermore, only information that enables better recommendations is stored. (i.e. no names, no exact address information etc.). A privacy proxy ensures that users can observe all traces, analyse the activity of the proxy and the type and volume of data exchanged etc. Research on the theoretical and practical implications of privacy protection was also part of the project (Petit, Ben Mokhtar, Brunie, & Kosch, 2014). 6. Sustainability of the Results To achieve sustainability of the project, dissemination and exploitation of the project results were a core element and a separate work package. Scientific dissemination mainly happened through conferences in the fields of Computer Science, cultural heritage and libraries. For general dissemination, the project website as a central hub for all information about the project proved very useful. Exploitation so far included internal exploitation of the technology within the partner institutions on the one hand, and external exploitation on the other hand. Regarding internal exploitation, EEXCESS partner institution Joanneum Research integrated EEXCESS features into their collection management system *imdasp*ro. Also, BitMedia and ZBW have integrated EEXCESS software modules into their systems. The servers that host the EEXCESS recommender will run beyond project lifetime at Joanneum Research. To achieve external exploitation (exploitation of the tools outside the EEXCESS consortium), EEXCESS partners approach cultural institutions as well as private enterprises, demonstrating the tools and exploring the options of integrating them into existing systems (Figure 5). The software components developed in EEXCESS are made available on platforms like Chrome Web Store, WordPress Plugin repository and Github. Some additional efforts will be needed after the end of the project to cover later releases of software environments like browsers or WordPress versions. Since a number of different institutions were involved in the development of individual components and more stakeholders are interested in the distribution *Fig. 5: Achieving Sustainability through involvement of different communities.* of their content, at least the prototypes most heavily used and needed by the communities will be adapted and maintained. Other components like the partner wizard for content integration focus on automated workflows which leads to minimized maintenance efforts. Since all software modules developed in the project are open source, a potentially large community of developers can maintain and enhance the components. A Hackathon during the project phase was held to get other developers involved in the project. Also, individual project partners worked together with Wikipedians on particular topics. Thus, there is reasonable hope that the institutions, developers and Wikipedians will all contribute to further developments of the project results. At the German National Library for Economics (ZBW) we also included some of the prototype features into our search portal EconBiz. 7. How Libraries and Other Institutions Can Benefit from the Results and Outlook In addition to the fact that the software developed for the prototypes can be reused by anyone, there are other ways for content providers to get involved. Libraries that have content they would like to share with potential users can disseminate their content through EEXCESS. Cultural heritage institutions, cultural aggregators, academic libraries and other organizations with valuable digitized content are invited to contribute to EEXCESS.\textsuperscript{10} Components that are useful in many different parts of the project were developed as independent modules, so that they can be easily used and reassembled. At ZBW, we included two components into our EconBiz Beta Services to make them available for testing. We will evaluate the benefits of including them into the main service. Taking Libraries’ Cultural Content to the User The visualization especially of the uRank technology where search results can be re-ranked may be of interest for a number of libraries and related institutions (Figure 6). The results change as more keywords are dragged and dropped into a special field. Users can move sliders to give individual keywords more or less weight. Last but not least, institutions with the abilities and resources to modify the code can easily adapt the prototypes or individual modules to their needs. **Acknowledgement** The presented work was developed within the EEXCESS project funded by the European Union Seventh Framework Programme FP7/2007-2013 under grant agreement number 600601. References Notes 1 http://eexcess.eu/. 2 The concept of the “long tail” describes a distribution where a few mega-sellers or hubs have a lot of usage whereas specialized content has only very few buyers or users. Since there is a very huge number of special items a graph of this distribution shows a “long tail”. See e.g. https://en.wikipedia.org/wiki/Long_tail. 3 Compare EEXCESS Vision: http://eexcess.eu/vision/. 6 All prototypes and visualizations can be found at http://eexcess.eu/results/. 7 Wikipedia was used because a number of surveys have shown that it is very often the most important source for starting research on a new topic even in academic contexts. Also, the structure with individual paragraphs and headlines supports the automatic detection of section topics. 8 Details on the requirements can be found at http://eexcess.eu/content-providers/. 9 All project deliverables are made available to the public on the eexcess website. They can be found on the project website from September 2016: http://eexcess.eu/publications/. 10 Information on how to become a content provider can be found at http://eexcess.eu/content-providers/.
{"Source-Url": "http://pub.zbw.eu/dspace/bitstream/11108/274/1/2016_Pianos_EEXCESS.pdf;jsessionid=0F463379F0D53A45132B3A585AD08A6A", "len_cl100k_base": 4824, "olmocr-version": "0.1.50", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 29626, "total-output-tokens": 6737, "length": "2e12", "weborganizer": {"__label__adult": 0.0005335807800292969, "__label__art_design": 0.0023822784423828125, "__label__crime_law": 0.0012359619140625, "__label__education_jobs": 0.1185302734375, "__label__entertainment": 0.0004930496215820312, "__label__fashion_beauty": 0.0004074573516845703, "__label__finance_business": 0.0037078857421875, "__label__food_dining": 0.0005450248718261719, "__label__games": 0.0008573532104492188, "__label__hardware": 0.0013380050659179688, "__label__health": 0.0010814666748046875, "__label__history": 0.0027713775634765625, "__label__home_hobbies": 0.0003299713134765625, "__label__industrial": 0.0005202293395996094, "__label__literature": 0.003429412841796875, "__label__politics": 0.0010423660278320312, "__label__religion": 0.0007991790771484375, "__label__science_tech": 0.265380859375, "__label__social_life": 0.0009450912475585938, "__label__software": 0.280517578125, "__label__software_dev": 0.3115234375, "__label__sports_fitness": 0.0002532005310058594, "__label__transportation": 0.0006842613220214844, "__label__travel": 0.000644683837890625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 27521, 0.02453]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 27521, 0.29147]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 27521, 0.87147]], "google_gemma-3-12b-it_contains_pii": [[0, 1717, false], [1717, 2817, null], [2817, 5092, null], [5092, 7538, null], [7538, 9462, null], [9462, 10425, null], [10425, 11112, null], [11112, 12094, null], [12094, 14041, null], [14041, 15530, null], [15530, 17489, null], [17489, 19481, null], [19481, 20883, null], [20883, 22644, null], [22644, 23366, null], [23366, 26126, null], [26126, 27521, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1717, true], [1717, 2817, null], [2817, 5092, null], [5092, 7538, null], [7538, 9462, null], [9462, 10425, null], [10425, 11112, null], [11112, 12094, null], [12094, 14041, null], [14041, 15530, null], [15530, 17489, null], [17489, 19481, null], [19481, 20883, null], [20883, 22644, null], [22644, 23366, null], [23366, 26126, null], [26126, 27521, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 27521, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 27521, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 27521, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 27521, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 27521, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 27521, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 27521, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 27521, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 27521, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 27521, null]], "pdf_page_numbers": [[0, 1717, 1], [1717, 2817, 2], [2817, 5092, 3], [5092, 7538, 4], [7538, 9462, 5], [9462, 10425, 6], [10425, 11112, 7], [11112, 12094, 8], [12094, 14041, 9], [14041, 15530, 10], [15530, 17489, 11], [17489, 19481, 12], [19481, 20883, 13], [20883, 22644, 14], [22644, 23366, 15], [23366, 26126, 16], [26126, 27521, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 27521, 0.0]]}
olmocr_science_pdfs
2024-11-30
2024-11-30
c004be02d7db287f64f69675c2095d7f40bf470b
[REMOVED]
{"Source-Url": "https://hal.archives-ouvertes.fr/hal-00582593/file/ICMS_recint.pdf", "len_cl100k_base": 4942, "olmocr-version": "0.1.43", "pdf-total-pages": 8, "total-fallback-pages": 0, "total-input-tokens": 22359, "total-output-tokens": 6103, "length": "2e12", "weborganizer": {"__label__adult": 0.0004930496215820312, "__label__art_design": 0.0005440711975097656, "__label__crime_law": 0.0006284713745117188, "__label__education_jobs": 0.0009455680847167968, "__label__entertainment": 0.00015497207641601562, "__label__fashion_beauty": 0.00023448467254638672, "__label__finance_business": 0.0003495216369628906, "__label__food_dining": 0.0006394386291503906, "__label__games": 0.0007853507995605469, "__label__hardware": 0.0023975372314453125, "__label__health": 0.0015211105346679688, "__label__history": 0.0005578994750976562, "__label__home_hobbies": 0.00019741058349609375, "__label__industrial": 0.0012941360473632812, "__label__literature": 0.0003066062927246094, "__label__politics": 0.0005340576171875, "__label__religion": 0.0010213851928710938, "__label__science_tech": 0.46875, "__label__social_life": 0.00015783309936523438, "__label__software": 0.00782012939453125, "__label__software_dev": 0.5087890625, "__label__sports_fitness": 0.0005407333374023438, "__label__transportation": 0.0011157989501953125, "__label__travel": 0.0002875328063964844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 21578, 0.05666]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 21578, 0.36561]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 21578, 0.83339]], "google_gemma-3-12b-it_contains_pii": [[0, 2555, false], [2555, 5573, null], [5573, 8345, null], [8345, 10290, null], [10290, 13406, null], [13406, 15458, null], [15458, 18382, null], [18382, 21578, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2555, true], [2555, 5573, null], [5573, 8345, null], [8345, 10290, null], [10290, 13406, null], [13406, 15458, null], [15458, 18382, null], [18382, 21578, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 21578, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 21578, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 21578, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 21578, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 21578, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 21578, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 21578, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 21578, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 21578, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 21578, null]], "pdf_page_numbers": [[0, 2555, 1], [2555, 5573, 2], [5573, 8345, 3], [8345, 10290, 4], [10290, 13406, 5], [13406, 15458, 6], [15458, 18382, 7], [18382, 21578, 8]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 21578, 0.13393]]}
olmocr_science_pdfs
2024-11-22
2024-11-22
5788e568f52f79f29d30b7720d998a16795707fb
PET-to-MLIR Citation for published version (APA): Document license: CC BY-NC-ND DOI: 10.1109/DSD51259.2020.00091 Document status and date: Published: 08/10/2020 Please check the document version of this publication: • A submitted manuscript is the version of the article upon submission and before peer-review. There can be important differences between the submitted version and the official published version of record. People interested in the research are advised to contact the author for the final version of the publication, or visit the DOI to the publisher's website. • The final author version and the galley proof are versions of the publication after peer review. • The final published version features the final layout of the paper including the volume, issue and page numbers. Link to publication General rights Copyright and moral rights for the publications made accessible in the public portal are retained by the authors and/or other copyright owners and it is a condition of accessing publications that users recognise and abide by the legal requirements associated with these rights. • Users may download and print one copy of any publication from the public portal for the purpose of private study or research. • You may not further distribute the material or use it for any profit-making activity or commercial gain • You may freely distribute the URL identifying the publication in the public portal. If the publication is distributed under the terms of Article 25fa of the Dutch Copyright Act, indicated by the "Taverne" license above, please follow below link for the End User Agreement: www.tue.nl/taverne Take down policy If you believe that this document breaches copyright please contact us at: openaccess@tue.nl providing details and we will investigate your claim. PET-to-MLIR: A polyhedral front-end for MLIR Konrad Komisarczyk, Lorenzo Chelini, Kanishkan Vadivel, Roel Jordans, Henk Corporaal Eindhoven University of Technology Abstract—We present PET-to-MLIR, a new tool to enter the MLIR compiler framework from C source. The tool is based on the popular PET and ISL libraries for extracting and manipulating quasi-affine sets and relations, and Loop Tactics, a declarative optimizer. The use of PET brings advanced diagnosis and full support for C by relying on the Clang parser. ISL allows easy manipulation of the polyhedral representation and efficient code generation. Loop Tactics, on the other hand, enable us to detect computational motifs transparently and lift the entry point in MLIR, thus enabling domain-specific optimizations in general-purpose code. We demonstrate our tool using the Polybench/C benchmark suite and show that it can lower most of the benchmarks to the MLIR’s affine dialect successfully. We believe that our tool can benefit research in the compiler community by providing an automatic way to translate C code to the MLIR affine dialect. Index Terms—MLIR, Loop Tactics, polyhedral model I. INTRODUCTION AND MOTIVATION MLIR is a novel and promising approach to build reusable and extensible compiler infrastructures [1]. The design rationale behind MLIR is to provide a non-optioned and fully customizable IR, which allows reducing the cost of building domain-specific compilers and significantly simplify the compilation for heterogeneous hardware. Having a fully customizable IR enables the representation of multiple abstraction levels. High-level IR representations can be lowered to low-level IR by progressive lowering. Dialects in MLIR enable IR extensibility and thus the representation of numerous abstraction levels. Specifically, you can think of a dialect as a namespace of operations, types and attributes. One of the available dialects in MLIR is the affine dialect. The affine dialect is a simplified polyhedral representation that has already been proven to be a powerful abstraction to generate high-performance code [2]. While some front-ends already exist to enter the high-abstraction levels in MLIR and then progressively lower them to affine, to the best of our knowledge, a C front-end is not available yet. As a consequence, developers need to lower C code manually if they want to experiment with the affine dialect and, more broadly, with the MLIR compiler infrastructure, which is a considerable loss in productivity. We advocate that an automatic tool that translates C code automatically would be a preferred solution. In this work, we propose PET-to-MLIR a front-end for a subset of C code based on state-of-the-art polyhedral technology. Besides, using Loop Tactics [3] we show how we can lift the entry point of C code, thus exploiting more aggressive domain-specific optimizations available in MLIR (i.e. replacing code with calls to optimized vendor-libraries). To summarize, our main contributions are: - An automatic tool to enter the MLIR compiler framework at the affine dialect starting from a polyhedral-friendly C code. - A demonstration of the usefulness of our tool by translating most of the Polybench/C benchmarks to MLIR’s affine dialect. In the next sections, we demonstrate the code generation flow and the tooling that we used to build PET-to-MLIR. Finally, we show how PET-to-MLIR can translate most of the Polybench and highlight its current limitations and future research directions. II. BACKGROUND Since PET-to-MLIR is based on PET, ISL, and Loop Tactics we first provide an high-level overview of the projects (Section II-A and Section II-B). Section II-C briefly introduces the MLIR compiler framework. A. ISL and PET PET is a library used to extract the polyhedral model starting from a C code fragment [4]. The extracted code fragment is called static-control part, or ScOP for short. PET is based on the LLVM C front-end (Clang) and ISL. The use of Clang gives PET full support for C99 and variable vector length arrays. Besides, Clang reports useful diagnosis messages that communicate with the user, which part of the input code does not satisfy the requirements of the polyhedral model. On the other hand, ISL allows extensive support for static piecewise quasi-affine expressions and conditions [5]. Such broad support is not available in other polyhedral extractors such as Clan [6]. In short, PET utilizes Clang to obtain a high-level AST and generates a compact, ISL-based, polyhedral representation. On top of creating the expressions typical of the polyhedral model (i.e., schedule and access relations), PET introduces structures containing additional information about the source program (i.e., array names and array extent). Within PET, individual statements are represented by the iteration domain, a set of access relations, and belong to a schedule. The iteration domain assigns to each statement a symbolic name and an integer vector in a k-dimensional space where k is the depth of the surrounding loops. Each point in such a vector represents a particular statement instance. For example, the iteration domain for the statement S1 in the GEMM kernel (Listing 1) is \{S_1(i,j) | 0 \leq i,j < 1024; S_2(i,j,k) | 0 \leq i,j,k < 1024\}. Access relations are represented as piece-wise quasi-affine functions, which map the iteration space with the array space, whose coordinates are the values of the accessed subscripts. For the statement \( S_1 \) in our running example, the accesses are described as: \( \{ S_1(i,j) \rightarrow \text{beta}(); S_1(i,j) \rightarrow \text{C\textsubscript{read}}(i,j); S_1(i,j) \rightarrow \text{C\textsubscript{write}}(i,j) \} \). The order in which the statement instances are executed is defined by the schedule, which maps a point in the iteration space to a point in the time space. The schedule is represented as a tree [7], where each node represents a partial schedule, and the order of loops and statements is determined by the node parent-child relation. The root of the tree is always a domain node, which encodes the iteration domain. Below such node a combination of the following nodes may exist: 1) band which defines the partial schedule of one or multiple loops; 2) filter which restricts the statement instances of the iteration domain; 3) sequence which imposes an order among its children. Figure 1 illustrates the schedule tree for our running example. It uses an outer band node to encapsulate the partial schedule of loop \( i \) and \( j \). The band is followed by a sequence node that establishes the order of executions between statement \( S_1 \) and \( S_2 \). Filter nodes ensure that each branch of the sequence node only executes the statement indicated in the filter node. The innermost band represents the partial schedule for the \( k \) loop. ### B. Loop Tactics Loop Tactics is an optimizer based on the ISL library supporting the declarative specification of affine transformations. Loop Tactics introduces three main concepts: 1) Schedule tree matchers which allow recognizing patterns in the schedule tree. 2) Access relation matchers that allow inspecting access pattern properties, and 3) builders that allow reconstructing a matched subtree, thus applying a given transformation. Essentially, a schedule tree matcher replicates the node type-based structure of the schedule tree to match. It allows additional wildcarding (i.e., anyTree) and filtering (i.e., via \texttt{C++} callback functions). Besides, it allows for capturing specific nodes that can be passed to the builders for optimization purposes. A builder uses a syntax similar to the tree matchers but describes how the tree should be reconstructed. Each tree modification reflects to a transformation in the original input code. Finally, access relation matchers allow testing access pattern properties via \texttt{via placeholder and arrayPlaceholder}. In summary, a loop transformation can be declaratively expressed by specifying a matcher pattern that captures a set of nodes and a builder that rewrites the captured nodes to create a new subtree. As an example, Listing 2 shows how the right-part of the subtree in Listing 1 can be matched. Lines 25 to 30 show the structural matcher. The matcher looks for a sequence node that has as descendant a band node that satisfies the callback \texttt{hasGemmPattern}, which in turn matches for a GEMM-specific access pattern. Such a pattern must have at least three two-dimensional reads to different arrays (line 12 to 15), one write access (line 17), and a permutation of indexes that satisfies the access pattern \( [i, j] \rightarrow [i, k][k, j] \). Finally, the builder (line 33 to 38) rebuilds the subtree by splitting the band node into two nested bands, which reflects the tiling transformations. For each dimension \( i, j \), and \( k \), we use a tile factor of 32. ### C. MLIR Increasingly heterogeneous and complex hardware makes the design of effective code generators difficult. Addressing this issue, the MLIR framework has been recently introduced under the LLVM umbrella. The motivation behind MLIR is to facilitates the design and implementation of code generators by significantly reducing the cost of building domain-specific compilers. MLIR is a non-opinionated, meaning that it comes with a limited set of builtins, leaving most of the intermediate representation customizable. A logical group of operations, types, and attributes make a dialect. The affine is one of them. Figure 2 shows the available dialects in MLIR and their entry points in its compilation pipeline. PET-to-MLIR enables polyhedral friendly C code fragments to enter the affine dialect. ### III. A BIRD’S EYE VIEW OF PET-TO-MLIR Figure 3 shows the high-level view of our tool. We use PET to construct the polyhedral model from a given C code fragment. In the default mode, we require the user to delimit auto hasGemmPattern = [&](schedule_node node) { auto _i = placeholder(); auto _j = placeholder(); auto _k = placeholder(); auto _A = arrayPlaceholder(); auto _B = arrayPlaceholder(); auto _C = arrayPlaceholder(); auto reads = /* get read accesses */; auto writes = /* get write accesses */; auto mRead = allOf( access(_C, _i, _j), access(_A, _i, _k), access(_B, _k, _j)); auto mWrite = allOf(access(_C, _i, _j)); return match(reads, mRead).size() == 1 && match(writes, mWrite).size() == 1; }; return match(reads, mRead).size() == 1 && match(writes, mWrite).size() == 1; }; sequence( filter.band( {body, hasGemmPattern, // filter func. anyTree( // wildcard continuation}}}()); band({%} { return tileSchedule(body, {32,32,32}); }, band({%} { return pointSchedule(body, {32,32,32}); }, subtree(body)); Listing 2: Structural matcher, access relation matcher for the right-most subtree in Listing 1. ### Fig. 2. Dialects available in MLIR and their entry points. PET-to-MLIR enables entering in the affine dialect from C code. The black arrows pointing downward represent MLIR’s progressive lowering (i.e., from high-level of abstractions (Linalg) down to the lowest (LLVM-IR)). is extracted, and the statement look-up in the statement list. We emit the statement operations by walking the parse tree. isl_ast_node_block are handled in the same way as isl_ast_node_user with the difference that they contains multiple statements. isl_ast_node_mark are used to emit BLAS calls. Mark nodes are allowed to be inserted by Loop Tactics only and carry the information on what BLAS pattern has been detected (i.e., GEMM or BATCHED_GEMM). Whenever the PET-to-MLIR code generator hits a mark node, the subtree is replaced with a function call to a BLAS library. Finally, ISL AST nodes of type isl_ast_node_if are not yet handled. A. GEMM kernel Listing 3 shows the generated affine code for our running example (Listing 1) without and with Loop Tactics. Let us start by describing the code snippet on top obtained by running without Loop Tactics and using the following compilation string mlir-pet -I /path gemm.c. In this case, all the inputs are marked as exposed; thus, PET-to-MLIR inserts them as inputs to an MLIR FuncOp ( scop.entry). The two dimensional tensors A, B and C are modelled as memref types where each element is a f32 type. Scalar alpha and beta as f32 types. Line 5 and 6 in the code snippet reflects statement S1 in Listing 1, whereas line 9 to 14, correspond to statement S2. Let us now turn our attention on the code snippet at the bottom obtained by running Loop Tactics with the matcher reported in Listing 2. We can see that a function call has replaced the GEMM pattern. The function call has 7 operands. The first and the second tell us if either the matrix A or B or both are transposed. Arguments 3 to 6 are the matrices and the alpha constant. Finally, argument 7 is the beta constant, which in this case is set to one as we don’t capture the initialization statement in the Loop Tactics’ matcher. The operands are automatically collected by Loop Tactics. IV. EVALUATION In this section, we evaluate the applicability of our tool by lowering to affine different kernels from the Polybench 4.2 benchmarks suite. For GEMM-like kernels (2mm, 3mm, gemm) we additionally run Loop Tactics to lift the entry point and thus exploiting domain-specific optimizations as the invocation of vendor-optimized routines. All the results in this section are in single-precision and report the arithmetic mean of five independent runs. As platform, we use an Intel i9-9900K clocked at 3.60GHZ. We measure the peak performance using an SGEMM routine from the MKL library. PET-to-MLIR reports the performance of the C code lowered with our tool to affine and then just-in-time compiled with the mlir-cpu-runner. PET-to-MLIR + LT, on the other hand, shows the performance achieved by detecting computational motifs and replacing the code with BLAS functions. As Figure 4 shows, we can successfully lower kernels from the linear-algebra and stencil domain. An exception is made for durbin, cholesky, gramschmidt and ludcmp as we currently do not support constant accesses to arrays and operations like division (not reported in the Figure). Although PET-to-MLIR is still a fairly new tool, it is already capable of translating most of the Polybench benchmark suite. The MLIR generated code is first syntactically checked with the mlir-opt tool, thus proving we generate a valid MLIR code. Behavior correctness, on the other hand, was tested by comparing the last ten values of each kernel’s output matrices with the output of the GCC compiler. V. RELATED WORK MLIR front-ends: Flang is the new LLVM front-end for FORTRAN code. It lowers FORTRAN code to the MLIR’s F18 dialect to perform advanced loop optimizations [8]. Teckyl is an MLIR front-end for Tensor Operations. It allows the user to start from a program written in Tensor Comprehension notation and lowers it to the Linalg or the Loop dialect [9], [10]. TensorFlow allows also to enter MLIR via the TensorFlow IR dialect [11], [12]. Polyhedral extractors Perhaps the most well-known polyhedral extractors (and optimizers) are Polly [13] and graphite [14]. The former extracts the polyhedral representation from the intermediate representation of LLVM while the latter from GCC. Several other compilers such as R-Stream and IBM-XL uses polyhedral techniques and thus extractors. But they are proprietary compiler; thus, limited documentation is available. Clan, together with PET is one of the most well-spread polyhedral extractors for source-level code [4], [6]. But it comes with limitations that have been addressed in PET. SUIF is also used to extract polyhedral representation, but it is not maintained anymore and it does not support C99, thus it has fallen out of fashion [15]. PET-to-MLIR fits in such a category of tool, but it is orthogonal to them as it targets the affine dialect in MLIR. VI. LIMITATIONS AND FUTURE WORK Although PET-to-MLIR is already able to handle the majority of the Polybench benchmarks suite, it is still relatively ``` func scop_entry(%arg0: memref<1024x1024xf32>, %arg1: memref<1024x1024xf32>, %arg2: memref<1024x1024xf32>, %arg3: f32, %arg4: f32) { affine.for %arg5 = 0 to 1024 { affine.for %arg6 = 0 to 1024 { %0 = affine.load %arg2[%arg5, %arg6] : memref<1024x1024xf32> %1 = mulf %arg4, %0 : f32 affine.store %1, %arg2[%arg5, %arg6] : memref<1024x1024xf32> } } return } ``` Listing 3: Affine IR emitted for Listing 1 with and without running Loop Tactics. new and under active development. At the time of this writing (git commit: c832a7d), the tool comes with limitations that, however, do not preclude its usage. Perhaps the most prominent limitations are: 1) If and else construct are not yet handled in the code generation. Currently, when an if condition is detected in the code fragment to be translated, the tool exists with a warning. 2) Symbolic bounds are not yet handled, and for now, we require all the loop bounds to be statically known (-DPOLYBENCH_USE_SCALAR_LB in Polybench). 3) External function calls in the code fragment are not allowed, and the tool bails-out if a call is detected. 4) Other operations such as division, as well as, constant accesses to arrays are not handled yet. 5) Line locations are not tracked. Future work will extend the test coverage and make sure the tool is feature complete. We will also work on emitting higher-level of abstraction dialects such as Linalg. Besides, we want to utilize the matchers in Loop Tactics to extract algorithmic information for general-purpose code. By defining structural and access patterns (matchers) for dialect-specific functions like pooling or transpose, we can enable parts of the originally general-purpose code to reach domain-specific dialects, thus allowing exploration of algorithmic-level optimizations. VII. Conclusion By exploiting the strengths of mature polyhedral tools, we have constructed, to the best of our knowledge, the first frontend for MLIR for polyhedral friendly C code. Although the development of the tool is still in progress, it can already handle a subset of the Polybench/C benchmark suite, as demonstrated in our evaluation. Finally, by using Loop Tactics, we provide a way to lift the entry-point in the MLIR compilation pipeline, thus enabling domain-specific optimizations, such as the use of vendor-optimized libraries. This last point also highlights the importance of retaining semantic information in compiler IR, which is the reason why MLIR has been developed in the first place. Acknowledgments This work was partially supported by the European Commission Horizon 2020 programme through the MNEMOSENE grant agreement, id. 780215 and the NeMeCo grant agreement, id. 676240. References
{"Source-Url": "https://pure.tue.nl/ws/files/163190296/Paper_DSD_Pet_to_MLIR.pdf", "len_cl100k_base": 4651, "olmocr-version": "0.1.48", "pdf-total-pages": 7, "total-fallback-pages": 0, "total-input-tokens": 22969, "total-output-tokens": 6272, "length": "2e12", "weborganizer": {"__label__adult": 0.00039458274841308594, "__label__art_design": 0.0002956390380859375, "__label__crime_law": 0.0003330707550048828, "__label__education_jobs": 0.00035500526428222656, "__label__entertainment": 6.103515625e-05, "__label__fashion_beauty": 0.00017333030700683594, "__label__finance_business": 0.00021946430206298828, "__label__food_dining": 0.000396728515625, "__label__games": 0.0004732608795166016, "__label__hardware": 0.0014896392822265625, "__label__health": 0.0005507469177246094, "__label__history": 0.00024020671844482425, "__label__home_hobbies": 9.66787338256836e-05, "__label__industrial": 0.00054168701171875, "__label__literature": 0.00018143653869628904, "__label__politics": 0.00030159950256347656, "__label__religion": 0.0005497932434082031, "__label__science_tech": 0.0267791748046875, "__label__social_life": 8.499622344970703e-05, "__label__software": 0.004688262939453125, "__label__software_dev": 0.96044921875, "__label__sports_fitness": 0.0003690719604492187, "__label__transportation": 0.0006422996520996094, "__label__travel": 0.0002310276031494141}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 23756, 0.03213]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 23756, 0.24797]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 23756, 0.8486]], "google_gemma-3-12b-it_contains_pii": [[0, 2165, false], [2165, 7632, null], [7632, 12118, null], [12118, 13425, null], [13425, 18366, null], [18366, 18844, null], [18844, 23756, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2165, true], [2165, 7632, null], [7632, 12118, null], [12118, 13425, null], [13425, 18366, null], [18366, 18844, null], [18844, 23756, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 23756, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 23756, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 23756, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 23756, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 23756, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 23756, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 23756, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 23756, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 23756, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 23756, null]], "pdf_page_numbers": [[0, 2165, 1], [2165, 7632, 2], [7632, 12118, 3], [12118, 13425, 4], [13425, 18366, 5], [18366, 18844, 6], [18844, 23756, 7]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 23756, 0.0]]}
olmocr_science_pdfs
2024-11-25
2024-11-25
e9cc73bca285a6f5ed4f80a8ec58e6c00ba4d756
Orthogonality regularizer for question answering Chunyang Xiao\textsuperscript{1}, Guillaume Bouchard\textsuperscript{2}, Marc Dymetman\textsuperscript{1}, Claire Gardent\textsuperscript{3} \textsuperscript{1}Xerox Research Centre Europe, Grenoble, France \textsuperscript{2}University College London, United Kingdom \textsuperscript{3}CNRS, LORIA, Nancy, France \textsuperscript{1}chunyang.xiao, marc.dymetman@xerox.com \textsuperscript{2}g.bouchard@cs.ucl.ac.uk \textsuperscript{3}claire.gardent@loria.fr Abstract Learning embeddings of words and knowledge base elements is a promising approach for open domain question answering. Based on the remark that relations and entities are distinct object types lying in the same embedding space, we analyze the benefit of adding a regularizer favoring the embeddings of entities to be orthogonal to those of relations. The main motivation comes from the observation that modifying the embeddings using prior knowledge often helps performance. The experiments show that incorporating the regularizer yields better results on a challenging question answering benchmark. 1 Introduction Having a system which is able to answer questions based on a structured knowledge base is a challenging problem. The problem has been addressed recently by researchers working on large knowledge bases such as Reverb (Fader et al., 2011) and Freebase (Bollacker et al., 2008). The creation of question answering (QA) benchmarks for these knowledge bases (KB) has a significant impact on the domain, as shown by the number of QA systems recently proposed in the literature (Berant and Liang, 2014; Berant et al., 2013; Bordes et al., 2014a; Bordes et al., 2014b; Fader et al., 2013; Fader et al., 2014; Yao and Van Durme, 2014; Yih et al., 2014; Dong et al., 2015). We identify two types of approaches for KB-centric QA systems: parsing-based approaches and information retrieval (IR) based approaches. Parsing-based approaches (Yih et al., 2014; Berant et al., 2013; Berant and Liang, 2014; Reddy et al., 2014) answer factoid questions by learning a structured representation for the sentences, called logical form. This logical form is then used to query the knowledge base and retrieve the answer. IR-based approaches try to identify the best possible match between the knowledge base and the question (Bordes et al., 2014a; Bordes et al., 2014b; Yao and Van Durme, 2014; Dong et al., 2015). In this work, we focus on the second approach, using embedding models, mainly because it is robust to invalid syntax and can exploit information of the answer. We focus on the Wikianswers (Fader et al., 2013) dataset constructed for Reverb. On Wikianswers, the underlying semantics is very simple (just one single triple). However, the task remains challenging due to the large variety of lexicalizations for the same semantics. We follow the approach of Bordes et al. (2014b) which learns the embeddings of words and KB elements. They model the semantics of natural language sentences and KB triples as the sum of the embeddings of the associated words and KB elements respectively. Despite its simplicity, this model performs surprisingly well in practice. Something even more interesting (Bordes et al., 2014b) is that the system can have a good performance even without using a paraphrase corpus. This makes the system very attractive in practice because in many specific domains, we might have a KB but there may be no paraphrase corpus as in Wikianswers. In our work, we push the results further when learning a QA system based only on the KB. Our contribution is to introduce a new orthogonality regularizer which distinguishes entities and relations. We also investigate the tradeoff captured by the orthogonality constraints. With a synthetic example, we show that if entities and relations are independent, orthogonal embeddings generate better results. The orthogonality constraint in the context of question answering is new, although it has been successfully used in other contexts (Yao et al., 2014). Like (Bordes et al., 2014b), we use al- most no linguistic features such as POS tagging, parsing, etc. 2 The ReVerb Question Answering Task The ReVerb question answering task was first introduced in (Fader et al., 2013) as follows. Given a large RDF KB and a natural language (NL) question whose answer is given by a triple contained in that KB, the task is to find a correct triple. For example, a correct answer to the NL question “What is the main language in Hong Kong?” would be the KB triple (cantonese.e, be-major-language-in.r, hong-kong.e) RDF triples are assertions of the form \((e_1, r, e_2)\) where \(r\) is a binary relation from some vocabulary \(R\) and \(e_1, e_2\) are entities from a vocabulary \(E\). The KB used is ReVerb\(^1\), a publicly available set of 15 million extractions (Fader et al., 2011) defined over a vocabulary of approximately 600K relations and 3M entities. The test set used for evaluation includes 698 questions extracted from the website Wikianswers, many of which involve paraphrases. 3 Related Work Fader et al. (2013) present one of the first approaches for dealing with open domain question answering. To map NL questions to KB queries, they first induce a lexicon mapping NL expressions to KB elements using manually defined patterns, alignments and a paraphrase corpus. Using this lexicon, multiple KB queries can be derived from a NL question. These queries are then ranked using a scoring function. Bordes et al. (2014b) introduce a linguistically leaner IR-based approach which identifies the KB triple most similar to the input NL question. In their approach, KB triples and NL questions are represented as sums of embeddings of KB symbols and words respectively. The similarity between a triple and a question is then simply the dot product of their embeddings. Interestingly, Bordes’ (2014b) system performs relatively well (MAP score 0.34) on the Wikianswers dataset even without using the paraphrase corpus. This suggests that the embedding method successfully captures the similarity between NL questions and KB queries. Our work continues this direction by further separating relations with entities. The idea of distinguishing entities and relations in question answering can also be found in (Yih et al., 2014). However, they base their work by supposing that we can cut the sentence into “entity part” and “relation part” and then calculate the matching score. Our model does not need this cut and simply enforces the entity embeddings and relation embeddings (on the KB side) to be different. Orthogonality or near orthogonality is a property which is desired in many embedding techniques. In random indexing (Sahlgren, 2005), a near orthogonality is ensured amongst the embeddings of different contexts. In (Zanzotto and Dell’Arciprete, 2012), to approximate tree kernels in a distributed way, different subtree feature embeddings are also constructed to be near orthogonal. Our work gives yet another motivation for orthogonal embeddings for the special case where the semantics of a sentence is modeled as the sum of its associated word embeddings. In this case, orthogonal word embeddings help to model their independence. 4 Embedding model Word embeddings are generally learned (Deerwester et al., 1990; Mikolov et al., 2013; Lebret and Collobert, 2015; Faruqui et al., 2014) such that words with similar context will naturally share similar embeddings as measured for instance by cosine similarity. The embeddings learned in (Bordes et al., 2014b) also encode context information. They link the embedding of words with the whole triple-answer in their scoring function. By this means, the word embedding carries the information of the whole triple. Our model further distinguishes entities and relations. Noting that entities and relations may have some independence (knowing that ‘a man eats’ doesn’t help to tell ‘which man’), the distinction is done via orthogonality. We show in the toy example that orthogonality helps to capture this independent structure of the data. 4.1 Scoring function The model learns the embedding of each word and KB element by trying to score the correct answers highest. Mathematically, let \(q\) be the query, and \(a\) be the answer-triple to align. Denote the total number of words as \(N_w\) and the number of KB elements as \(N_{kk}\). Then denote by \(\phi(q) \in \{0, 1\}^{N_w}\) Algorithm 1 Training with orthogonality regularizer 1. Sample a positive training pair \((q_i, a_i)\) from \(D\). 2. Create a corrupted triple \(a_i'\). 3. If \(S(q_i, a_i) - S(q_i, a_i') < 0.1\) : make a stochastic gradient ascent on \(S(q_i, a_i) - S(q_i, a_i') - \lambda |E, R|\) 4. Normalize the embedding vector the 1-hot representation indicating the presence or absence of words in the query. Similarly we denote the sparse representation on the KB side as \(\psi(a)\). Let \(M \in R^{d \times N_w}\) be the embedding matrix for words and \(K \in R^{d \times N_kb}\) be the embedding matrix for the elements in the KB. \(d\) is the low dimension chosen by the user. The embedding of the sentence is then calculated as \(M \phi(q)\) and similarly the embedding of the answer-triple as \(K \psi(a)\). We can score the matching of these embeddings: \[ S(q, a) = (M \phi(q))^\top (K \psi(a)) \] which is the dot product between the embedding of the sentence and the embedding of the triple. The model is introduced in (Bordes et al., 2014b) and we use the same scoring function. Note that the model actually sums up each word embedding to form the embedding of the sentence. 4.2 Inference The inference procedure is straightforward. Given a question \(q\) and a set of possible answer triples noted \(A(q)\), the model predicts the answer by returning the triple with the highest score: \[ a' = \arg\max_{a \in A(q)} S(q, a) \] 4.3 Training Originally in (Bordes et al., 2014b), given a question to be answered, training is performed by imposing a margin-constraint between the correct answer and negative ones. More precisely, note \(a'\) a negative answer to the question \(q\) (the correct answer to \(q\) being \(a\)). Then for each question answer pair, the system tries to maximize the following function by performing a gradient ascent step: \[ \min(\epsilon, S(q, a) - S(q, a')) \] with \(\epsilon\) the margin set to 0.1. In addition, the norms of columns in \(M\) and \(K\) are constrained to be inferior to 1. The training is done in a stochastic way by randomly selecting a question answer pair at each step. For each gradient step, the step size is calculated using Adagrad (Duchi et al., 2011). The negative example is created by randomly replacing each element of \((e_1, r, e_2)\) by another one with probability 2/3. 4.4 Enforcing Orthogonal Embeddings In this work, we are especially interested in the additional assumptions we can make on the model in order to cope with data sparsity. Indeed, when the number of training data supporting the computation of embeddings is small, embedding models are brittle and can lead to disappointing results. We noticed that one important assumption that is not discussed in the basic approach is that the embedding space is the same for relations and entities. That approach has a tendency to learn similar embeddings for entities and relations, even if they have different meanings. Intuitively, we would like to balance that tendency by a “prior knowledge” preference towards choosing embeddings of entities and relations which are orthogonal to each other. To justify this assumption, consider a simple case where the underlying semantics is \((e, r)\) as in the sentence “John eats”. We will use the same letter to indicate an entity or relation and their corresponding embeddings. In (Bordes et al., 2014b), the embedding of the semantics is then calculated as \(e + r\) for this very simple case. Now suppose that \(\forall e' \neq e, \|e - e'\|_2 \geq \epsilon\) (i.e John is different from Mary with margin \(\epsilon\)) and that the same kind of constraints also holds for relations. However, even when these constraints are satisfied, it is not guaranteed that \(\|e + r - e' - r'\|_2 \geq \epsilon\), which means that the model may still get confused on the whole semantics even if each part is clear. One obvious and linguistically plausible solution is to say that the entities and relations lie in orthogonal spaces. Indeed, if relations and entities are orthogonal (\(\forall r, e (r \perp e)\)), then if two entities \(e, e'\) and two relations \(r, r'\) are distinct (i.e., \(\|e - e'\|_2 \geq \epsilon\) and \(\|r - r'\|_2 \geq \epsilon\)), it follows that \(\|e + r - e' - r'\|_2 = \|e - e'\|_2 + \|r - r'\|_2 \geq 2\epsilon\) by Pythagorean theorem. That is, two sentences whose semantic representations involve two distinct entities and/or relations will have different values. In real problems, however, posing a hard orthogonality constraint largely reduces the model’s expressive power\(^2\), so we decide to add it as a regularizer. More concretely, let the correct triple be \((e_1, r, e_2)\) and the negative one be \((e'_1, r', e'_2)\). Consider that we are in a case not satisfying the margin constraint, then we will try to maximize the following regularized function \(S(q, a) = S(q, a') - \lambda |E.R|\) with a gradient step. The regularizer \(|E.R| = |e_1.r| + |e_2.r'| + |e'_1.r'| + |e'_2.r|\) is minimized when all the entities and relations live in orthogonal space. The regularization parameter \(\lambda\) is chosen via an automatically constructed development set for which we randomly selected 1/2000 of all the triples in the KB and generate associated questions. We discard these triples from training and choose the \(\lambda\) value based on the score on the development set. The \(\lambda\) value is by this means set to 0.01 with \(\lambda\) in \{0.5,0.1,0.05,0.01,0.005,0.001\}. Once the \(\lambda\) value is chosen, we retrain the whole system. ### 5 Experimental results #### 5.1 Toy example In this section, we illustrate the benefits of orthogonality via a toy example. We construct a KB containing 50 entities (\(E\)) and 50 relations (\(R\)) then generate all their cross products obtaining 2500 fact pairs. In consequence the entities and relations are independent. For every \(e_i \in E\), we suppose that there is a single word lexicalizing the entity noted “\(e_i\)”. Similarly, we note the lexicalization of \(r_j\) “\(r_j\)”. We separate these 2500 pairs into training (2450) and test (50). Notice that similarly to Wikianswers, this toy dataset involves KB entities and relations whose type is known \textit{a priori}. The training corpus is built using one simple generation rule : \((e_i, r_j) \rightarrow “e_i \ r_j”\). Negative examples are created by replacing with probability 1/2 both entity and relation with another one. We embed all the words and KB symbols in a space of 20 dimensions. We compare the model (Bordes et al., 2014b) with the model where we enforce \(E\) and \(R\) (and also “\(E’\)” and “\(R’\)” to be orthogonal. This means that words or KB symbols in fact live in an embedding space of dimension 10. At test time, for a given sentence “\(e_i \ r_j\)”, a set of \((e, r)\) pairs is ranked and we compute the proportion of cases where the first ranked pair is correct. Table 2 shows the results for both systems on two configurations: a configuration (Accuracy(1)) where the number of pairs to be ranked is 1250 and another (Accuracy(2)) with 2500 pairs.\(^3\) In both cases, imposing the orthogonality constraint improves performance by a large margin. #### 5.2 Wikianswers Wikianswers contains a set of possible triples for each question and we re-rank these triples to report our system’s performance. This is the “re-ranking” setting used in (Bordes et al., 2014b). Table 3 compares different systems in this setting. The Embedding scores are taken from (Bordes et al., 2014b) for which we have reimplemented and confirmed the results. <table> <thead> <tr> <th>Method</th> <th>Prec</th> <th>Recall</th> <th>F1</th> <th>MAP</th> </tr> </thead> <tbody> <tr> <td>Embedding</td> <td>0.60</td> <td>0.60</td> <td>0.60</td> <td>0.34</td> </tr> <tr> <td>This work</td> <td>0.63</td> <td>0.63</td> <td>0.63</td> <td>0.36</td> </tr> </tbody> </table> Table 3: Performance for re-ranking question answer pairs of test set for different systems on Wikianswers Table 3 shows that our technique improves the performance also on the larger, non-synthetic, dataset provided by Fader (2013) over the Bordes (2014b)’s method. In addition, Table 1 shows some examples where the two systems differ and where the orthogonality regularized embeddings seem to better support the identification of similar relations. For instance, “is the argument on” is mapped to support.r rather than be-type-of.r and “is the religious celebration of” to be-most-important-holiday.r rather then be-all-about.r. 6 Conclusion This paper introduces an embedding model for question answering with orthogonality regularizer. We show that orthogonality helps to capture the differences between entities and relations and that it helps improve performance on an existing dataset. Acknowledgements We would like to thank the anonymous reviewers for their constructive feedback. References Xuchen Yao and Benjamin Van Durme. 2014. Information extraction over structured data: Question answering with freebase. In Proceedings of ACL.
{"Source-Url": "https://inria.hal.science/hal-01623819/file/orthogonality.pdf", "len_cl100k_base": 4278, "olmocr-version": "0.1.53", "pdf-total-pages": 6, "total-fallback-pages": 0, "total-input-tokens": 20107, "total-output-tokens": 6002, "length": "2e12", "weborganizer": {"__label__adult": 0.0005826950073242188, "__label__art_design": 0.0009489059448242188, "__label__crime_law": 0.0009617805480957032, "__label__education_jobs": 0.004238128662109375, "__label__entertainment": 0.0004458427429199219, "__label__fashion_beauty": 0.0004131793975830078, "__label__finance_business": 0.0005054473876953125, "__label__food_dining": 0.0006356239318847656, "__label__games": 0.0014982223510742188, "__label__hardware": 0.0009636878967285156, "__label__health": 0.0014123916625976562, "__label__history": 0.0005135536193847656, "__label__home_hobbies": 0.00015294551849365234, "__label__industrial": 0.0007166862487792969, "__label__literature": 0.0034580230712890625, "__label__politics": 0.0005884170532226562, "__label__religion": 0.0008063316345214844, "__label__science_tech": 0.453369140625, "__label__social_life": 0.0003070831298828125, "__label__software": 0.0338134765625, "__label__software_dev": 0.4921875, "__label__sports_fitness": 0.0004401206970214844, "__label__transportation": 0.0006785392761230469, "__label__travel": 0.0002841949462890625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 21759, 0.03529]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 21759, 0.49401]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 21759, 0.87984]], "google_gemma-3-12b-it_contains_pii": [[0, 4087, false], [4087, 8448, null], [8448, 13018, null], [13018, 16450, null], [16450, 21031, null], [21031, 21759, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4087, true], [4087, 8448, null], [8448, 13018, null], [13018, 16450, null], [16450, 21031, null], [21031, 21759, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 21759, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 21759, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 21759, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 21759, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 21759, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 21759, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 21759, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 21759, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 21759, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 21759, null]], "pdf_page_numbers": [[0, 4087, 1], [4087, 8448, 2], [8448, 13018, 3], [13018, 16450, 4], [16450, 21031, 5], [21031, 21759, 6]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 21759, 0.04]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
82c0a40af6c79bd4dfe7e16e6207fc3dbbd54233
An article describes the motivation for use of automatic code generators for the development of critical control applications in the aerospace industry. A V-cycle model based design is introduced and its advantages and development practices that leads from design of a MATLAB/Simulink [1] models to a real target application are depicted. Attention is also paid to FAA/EASA certification authorities requirements ([5], [6], [7]) with respect to a certification process of any newly designed aviation equipment. These practices are being used during the entire development cycle of an aircraft engine subsystems for small civil aircraft (category FAR 23 / CS 23). Key words: aircraft, engine, fadec, certification, modelling, V-cycle. Introduction Software (SW) and hardware (HW) that are developed for critical application and have to meet a lot of standards that ensure their quality ([2], [3]). The certification level depends on the target application. Some experiences with certification for embedded systems in aviation are described in [4]. Generally, it can be said, that the software and hardware development and certification is time and cost consumable process. Main effort is to reduce development time and cost and ensure shorter time to market. On this account it is necessary to find new methods and approaches for SW and HW developing. This paper describes certification process and way how to reduce cost connected with the equipment certification; modern approaches for development of control systems using V-cycle and example of a Full Authority Digital Engine Control (FADEC) design cycle. 1 Certification Aspects The main reason for using the Rapid Control Prototyping (RCP) and development tools during the whole development cycle is to reduce time and costs of the development and certification process. We have analyzed COTS based SW and HW development tools which are fully or partially qualified for use in the aerospace industry, or they are in progress to be qualified in the near future. We have also performed an internal study which shown that COTS development tools should shorten the development cycle very effectively. There are many qualified SW tools offered by many vendors. These SW tools cover airborne certification requirements and comply with technical recommendations and standards for safety-critical applications. Available methodologies introduce very effective processes during the SW and HW development cycle. The best way to save resources available for the project is using integrated development tools. It is almost impossible to use only one tool for all activities during the project development, but it is likely to use such tools which can cooperate among each other, as is shown in fig. 1. ![Cooperation among the development tools during the certification process](image-url) An example of a commercial tool chain is shown in Figure 3. These development tools can be fully standardized for creation of higher quality and more reliable software, e.g. C, C++, Ada, Java compilers and automatic code generators, which are usually a part of Integrated Development Environment (IDE), such as SCADE, MATLAB/Simulink, NI LabView, etc. Ability to reuse certified SW parts and artifacts within the software modification process for use in another application (especially RTOS like LynxOS-178, PikeOS, Integrity-178B, etc., see more in [2], [3]) leads to cost reduction and time effective development because SW verification and code tests are then less time consuming processes. Static and dynamic code testing tools are available commercially (CANTATA++, CodeTest, VectroCast, etc.). A certification by FAA/EASA agencies is required for both simple (based on CPU and simple electronic components) and complex hardware architectures (based on PLD, FPGA, ASIC micro-coded technology). Using simple hardware architecture with a standard core CPU (Freescale, ARM, TI, etc.) could simplify the certification process very dramatically because of proven architecture and reference projects that have passed the certification process formerly. The same situation is with COTS bus technologies - these are being used in the automotive industry for a long time and their safety, performance and reliability has been sufficiently proven [6], [7], [8]. Thus, wide enforcement of COTS components and data buses into the aerospace sector is only a matter of time. 1.1 RTCA/DO-178B and RTCA/DO-254 standards The development of every equipment for use in aerospace has to be approved by FAA or EASA certification agencies. The two major standards in the aerospace industry that describe all the requirements and recommendations for successful certification are the RTCA/DO-178B – Software Considerations in Airborne Systems and Equipment Certification [4] and RTCA/DO-254 – Design Assurance Guidance for Airborne Electronic Hardware [5]. These standards expect from developers to describe the whole development cycle in order to assure reliability, data integrity, performance, proper development cycle, system configuration management and continuous airworthiness. As a resulting benefit there is identification of bottlenecks and prevention of fault states. On the other hand, the drawback of these two standards is a necessity to elaborate a comprehensive amount of documentation, both for the SW and HW development. List of the SW development documentation in accordance with DO-178B is given below: - Plan for Software Aspects of Certification (PSAC) - Software Development Plan (SDP) - Software Verification Plan (SVP) - Software Configuration Management Plan (SCMP) - Software Quality Assurance Plan (SQAP) - Software Requirements Standards (SRS) - Software Design Standards (SDS) - Software Code Standards (SCS) - Software Requirements Data (SRD) - Software Design Description (SDD) - Software Verification Cases and Procedures (SVCP) - Software Life Cycle Environment Configuration Index (SECI) - Software Configuration Index (SCI) - Software Accomplishment Summary (SAS) The minimum software life cycle data to be submitted to a certification authority is: - Plan for Software Aspects of Certification (PSAC) - Software Configuration Index (SCI) - Software Accomplishment Summary (SAS) The regulation concerning retrieval and approval of SW life cycle data related to the type design applies to: - Software Requirements Data - Software Design Description - Source Code - Executable Object Code - Software Configuration Index - Software Accomplishment Summary List of HW development documentation in accordance with DO-254: - Plan for Hardware Aspects of Certification (PHAC) - Hardware Development Plan (HDP) - Hardware Verification Plan (HVP) - Hardware Configuration Management Plan (HCMP) • Hardware Process Assurance Plan (HPAP) • Hardware Requirements Standards (HRS) • Hardware Requirements (HR) • Hardware Detailed Design Data: Top, Level Drawings (TLD) • Hardware Detailed Design Data: Assembly Drawings (AD) • Hardware Detailed Design Data: Installation Control Drawings (ICD) • Hardware Traceability Data (HTD) • Hardware Acceptance Test Criteria (HATC) • Hardware Configuration Management Records (HCMR) • Hardware Process Assurance Records (HPAR) • Hardware Accomplishment Summary (HAS) The minimum hardware life cycle data to be submitted to a certification authority is: • Plan for Hardware Aspects of Certification (PHAC) • Hardware Verification Plan (HVP) • Hardware Detailed Design Data: Top, Level Drawings (TLD) • Hardware Accomplishment Summary (HAS) As is shown above, the list of required documentation is really comprehensive and it is together with strict coding practices, test sets and system verification – the most disincentive issue during the development cycle of any new equipment/technology for the aerospace industry, because it requires strong experience, deep know-how and well managed certification practices. 2 Development of Control Systems The development procedures and practices in the aerospace industry have originated on those used in the industry and automotive sector. A process that describes steps and linkages between individual development stages of the project has been established over the time. This process is often called a “V-cycle”. 2.1 V–cycle The V-Cycle is a graphical construct used to communicate a model-based software development methodology. The advantages of V–cycle lies in its inherently intuitive nature, easy reuse of model and portability across multiple platforms. Model-based control design is a time saving and cost-effective approach, allowing engineers to work with a single model in an integrated software environment. The graphical representation of the V-cycle is shown in Fig. 3. The complete design consists of particular steps, such as: control design, rapid control prototyping, target implementation, hardware-in-the-loop testing and calibration. Within the function design stage, the modelling and computer simulations of closed-loop system have been done. A mathematical model of both the controlled system (so called plant model) and a controller (ECU) are necessary at this point. The important thing is that the control algorithms are developed as symbolic models, not in a C-code. When the synthesis of the ECU is finished and the results of simulations are well, the engineers start with verification of ECU’s algorithms in “real-time” on a real-time hardware. This stage is called a rapid control prototyping (RCP). Fig. 3. The V-cycle development process [1] RCP is a process that lets the engineers quickly test and iterate control strategies on a real-time computer with either real or modelled system-under-control. The computer model is used in case where inadequate action of ECU could cause a damage of equipment or endanger lives. The biggest advantage of using the integrated software environment for modelling, simulation and also function prototyping is that the control engineer does not have to be a C-code expert nor have enough skills to port the C-code to a real-time target. By virtue of an automated build process the RCP systems do this work for them. In the next stage, the target code for the ECU is automatically generated by a special software, which reads math model files and generates a compile-able code that replicates the behaviour of the model. This dramatically reduces the implementation time and, in addition, the engineers have systematic consistency between a specification and production stage. Moreover, improvements to the ECU could be easily added, even after implementation of an initial code. The time for hardware-in-the-loop testing is coming on once the ECU is programmed. Hardware-in-the-loop is a form of a real-time simulation that differs from a pure real-time simulation by addition of a “real” component into the loop. This component might be the ECU or the real system-under-control. The current industry definition of the hardware- in-the-loop system is that the plant is simulated and the ECU is real. The model of the plant (and the simulation HW also) is the same like in the stage of RCP. The next step is a calibration, which is a process of optimizing or tuning real control algorithms to get the desired response from the system. A calibration tool is a combination of a hardware interface and a software application that enables the engineer to access and change the “calibration variables” in the ECU. Typical components of control algorithms which need calibration are look-up tables, gains and constants. The structure of the control algorithm is not changed during the calibration process. 2.2 Implementation of the V-cycle The typical V-cycle development process is based on a software development tools such as MATLAB and dSPACE. These tools provide a seamless transition from a block diagram to a real-time and target hardware. Particularly, for function design is mostly used MATLAB, Simulink, Stateflow and other toolboxes for MATLAB. These tools together comprise a complex software package that forms the core environment for mathematical computation, analysis, visualization, algorithm development, etc. MATLAB is a high-level technical computing language and interactive environment that enables performing computationally intensive tasks such as algorithm development, data visualization, data analysis, and numeric computation. Simulink provides an interactive graphical environment and a customizable set of block libraries that let the user to design, simulate, implement and test a variety of time-varying systems. With Stateflow, you can integrate state diagrams into Simulink models. During RCP stage the Real-Time Workshop (RTW) and Stateflow Coder (SC) automatically generate a C code from Simulink block diagrams and Stateflow systems. And here comes into play a dSPACE Real-Time Interface (RTI) which is a link between a dSPACE hardware and the development software from Mathworks. RTW/SC generates the model code, while RTI provides blocks that implement the I/O capabilities of dSPACE systems in Simulink models. Then the real-time model is compiled, downloaded and started automatically on the real-time hardware. The program can now be controlled and instrumented by the GUI application – ControlDesk. This is referred to as an experiment control. The system-under-control could be also simulated on a real time hardware, especially in case of very complicated systems, such as e.g. engines. Many different types of HW simulators that cover all the different requirements (such as computational power, I/O interface, data bus systems, etc.) are provided with the simulations tools. The generated code could be optimized for fixed- or floating-point operations, in accordance to a certain processors. Versatile code configuration options ensure that the produced code copes with all the processor constraints. Hardware-in-the-loop stage is closely connected with the next stage – calibration. 3 FADEC Development Cycle FADEC is the most important control authority on the aircraft. The new and modern approach for designing of the engine control unit brings: - Shorter developing time, - Reducing time for code testing, - Reducing cost for prototypes manufacturing, - Higher quality of the application code, - Effective support of certification, etc. The design cycle of the FADEC will be described on the Complex Power-plant Control System (CP-CS) for small aircraft that is designed in a frame of the project CESAR. Power control system configuration for small aircraft is shown in Fig. 4, its block diagram is shown in Fig. 6. The power of the jet turbine is control by the dual channel FADEC that cooperates with Fuel Control Electrical Interface Device (FCEID) and Propeller Control Electrical Interface Device (PCEID). The FADEC can be back-uped by the manual control system. ![Fig. 4. CP-CS system configuration for small aircraft](image) Generally the FADEC model based development consists of the following steps: - Engine and control system requirements and their decomposition - Mathematical modelling - Model integration and simulation (Model in the loop - MIL) - Automatic code generation and verification 3.1 Mathematical modelling A model formulation of controlled system is an essential part during the stage of its control algorithm design. The model is used for examination and prediction of the behaviour of the real system. Real system could be very expensive. A model of the system is based on the mathematical description. In engineering disciplines the mathematical model is usually described by a set of algebraic, differential equations, the transfer functions or the state matrixes. These relations are mostly derived either by a mathematic-physical analysis of the system’s phenomenon or by an experimental examination of the real system. Within the modelling of very complicated systems both approaches are combined. The aim is to get as precise model as possible, but also as simple as possible. These two requests go unfortunately against each other – the more precise model is more complicated. The CP-CS model is very complex and highly non-linear system. The physical phenomenon involved to cover domains such as solid and fluid mechanics, thermodynamics and electromagnetism. All the model parts are based on the mathematical description of the each part, provided by their designers. 3.2 Model integration and simulation The simulation is a way, how to verify the behaviour of a control system that includes its environment without real hardware. The models were created in MATLAB / Simulink that is a comprehensive software package that form the core environment for mathematical computation, analysis, visualization, algorithm development, model-based design, etc. The schematic drawing implementation of the real hardware and its mathematical models to the Simulink is shown in Fig. 7. The structure of the VTPE model is based on splitting of the whole engine into two basic parts, which can be solved separately. These main parts are: gas-generator (inlet, compressor, combustor and turbine) and power turbine with gearbox and propeller together. There is only thermodynamic power linkage between these two parts, the only hand over variable is the power transmitted from gas-generator to free turbine $P_{FT}$. Due to this fact the complexity of model is markedly decreased. The MATLAB / Simulink representation of the VTPE that is depicted in picture Fig. 6 is shown in Fig. 8. The VTPE model is precise enough to for examination of its behaviour during flight, for different aircraft speeds, heights, power extractions and outside conditions. The start of the engine, reverse mode, taxiing and feathering are not possible to simulate. ![Simulink diagram of VTPE and CP-CS architecture](image) All necessary climatic variables are computed on the basis of International Standard Atmosphere model (ISA). The input blocs of the ISA model could be set to a constant or to any time-dependent curve (e.g. typical flight profile could be simulated). **Propeller Speed Control** This part of FADEC must keep propeller speed at constant speed throughout the whole range of inputs (e.g. for changing value of power transmitted from gas-generator to free turbine and for all possible climatic conditions). System under control is ‘propeller governor’ + ‘free turbine + propeller’ and control signal is control current of ‘propeller governor’ $I_{20}$. The control structure is cascade, with inner $\varphi$ feedback loop and outer $n_P$ feedback loop. Instead of measuring $\varphi$ directly, the value of $u$ is measured, which is directly proportional to $\varphi$. The overall architecture of this structure is shown in Fig. 9. ![Simulink scheme of the propeller speed control](image) **Power Control** Power control should ensure proper power of the engine, particularly proper power on the free-turbine shaft $P_{FT}$, with respect to Power Lever and throughout all possible climatic conditions. It also checks important parameters and doesn’t allow them to overcome secure values. System under control consists of ‘fuel governor’ with ‘gas-generator’, control signal is a control current of ‘fuel governor’ $I_{r}$. The control structure comprises $n_{GG}$ feedback loop with PI controller and some blocs providing limitations. But because measurement of the power (or torque) is not precise enough for using it in the feedback control, the speed of gas-generator is used instead (power of free-turbine is basically proportional to the speed of gas-generator). ![Simulink scheme of the power control](image) 3.3 Automatic code generation and verification Automatic code generation software is an extension tool that can create executable code from a model. Real-Time Workshop (RTW) is a tool that can be used for automatic code generation in MATLAB / Simulink. The RTW generates stand-alone C code for proposed algorithms modelled in Simulink. The resulting code can be used for accelerated simulation which mostly contains software in the loop and hardware in the loop simulations. The code can be tuned and monitored by these simulations. After automatic generation the build-in verification tool can locate and test dangerous parts of the generated code and prevents the possible accidents. The code can be tested by external verification tools like Cantata C/C++/Ada as well as. ![Model in Simulink](image1.png) ![Generated code](image2.png) Fig. 11. Automatic code generation **Note:** The model part that contains algebraic constraint blocks has to be replaced by numerical iterative calculation (showed in 12). ![Example of model with algebraic constraint block](image3.png) Fig. 12. Example of model with algebraic constraint block 3.4 Software in the loop testing (SIL) SIL test is proceed by the MATLAB / Simulink tool. SIL tool is control systems simulator for temporal and functional simulations. The behaviour of a control system depends on the proposed architecture and on the target hardware where the FADEC software is implemented. On this account the results given from the SIL tests can analyse only model behaviour, nevertheless the SIL tests are important step for the finding of model faults before model implementation into the hardware. 3.5 Hardware in the loop testing (HIL) HIL is a kind of testing to validate the interactions between the designed software and the test or real hardware. The HIL tests can reduce the number of expensive prototypes. The HIL test is performed by the dSPACE environment. The HIL testing offers to use following test combination: - Turbine model × ECU model - Real turbine × ECU model - Turbine model × Real ECU All test combination can be realized on the created dSPACE workplace. The dSPACE is used as a development environment that ensures implementation created models and generated C code to the real (evaluation) hardware. Controlling of the test procedures is provided by the Real-Time Interface (RTI) tool. RTI provides tool for controlling panel creation. 3.6 Target platform implementation The proposed and generated FADEC application code will be finally loaded to the target platform. The target platform can run either as a standalone application (without OS) or as a program module in OS or RTOS. For both types of output code representation it is necessary create link interface that allows running the control algorithms. 4 Conclusion Model based design for engine control system was approved. Main advantage of presented approach consists in development time and cost reduction. This approach supports very effectively certification process as well as. Models were created and simulated for a virtual system and will be verified on a real CP-CS. Acknowledgement Development of Complex Power-plant Control System (CP-CS) for small aircraft was supported by the European Union, FP6 IP research project No.: 30 888, "CESAR – Cost Effective Small Aircraft". Requirements, mathematical descriptions of particular sub-systems were provided as know-how by CESAR partners (Ivchenko-Progress, VZLU, Jihostroj, PBS and UNIS). References Поступила в редакцию 28.05.2009 СУЧАСНІ МЕТОДИ РОЗРОБКИ СИСТЕМ АВТОМАТИЧНОГО УПРАВЛІННЯ ДЛЯ АВІАЦІЙНИХ ДВИГУНІВ І ГІХНЯ СЕРТИФІКАЦІЯ P. Axman, T. Kerlin, D. Svачина, V. Opluštil, J. Toman Стаття описує необхідність використання автоматичних генераторів об’єктного коду для розробки систем критичного управління в авіакосмічній промисловості. Представлено базову модель V-циклу, її переваги і зображені методи розробки, які отримані з моделей MATLAB/Simulink [1] для реального цільового застосування. Увага також звернута до сертифікаційних вимог FAA/EASA ([5], [6], [7]) і конкретно процесу сертифікації нового авіаційного обладнання. Ці методи використовуються протягом повного циклу розробки підсистем авіаційного двигуна для малого цивільного літака (категорія FAR 23 / CS-23). Ключові слова: літак, двигун, fadec, сертифікація, моделювання, V-цикл. СОВРЕМЕННЫЕ МЕТОДЫ РАЗРАБОТКИ СИСТЕМ АВТОМАТИЧЕСКОГО УПРАВЛЕНИЯ ДЛЯ АВИАЦИОННЫХ ДВИГАТЕЛЕЙ И ИХ СЕРТИФИКАЦИЯ P. Axman, T. Kerlin, D. Svačina, V. Opluštil, J. Toman Статья описывает необходимость использования автоматических генераторов объектного кода для разработки систем критичного управления в авиакосмической промышленности. Представлена базовая модель V-цикла, ее преимущества и изображены методы разработки, которые получены из моделей MATLAB/Simulink [1] для реального целевого применения. Внимание также обращено к сертификационным требованиям FAA/EASA ([5], [6], [7]) и конкретно процессу сертификации нового авиационного оборудования. Эти методы используются в течение полного цикла разработки подсистем авиационного двигателя для малого гражданского самолета (категория FAR 23 / CS-23). Ключевые слова: самолет, двигатель, fadec, сертификация, моделирование, V-цикл.
{"Source-Url": "https://www.khai.edu/csp/nauchportal/Arhiv/AKTT/2009/AKTT709/Ahman.pdf", "len_cl100k_base": 5501, "olmocr-version": "0.1.53", "pdf-total-pages": 8, "total-fallback-pages": 0, "total-input-tokens": 32184, "total-output-tokens": 6154, "length": "2e12", "weborganizer": {"__label__adult": 0.0011434555053710938, "__label__art_design": 0.0007872581481933594, "__label__crime_law": 0.0009441375732421876, "__label__education_jobs": 0.0019931793212890625, "__label__entertainment": 0.00018167495727539065, "__label__fashion_beauty": 0.0004382133483886719, "__label__finance_business": 0.0006937980651855469, "__label__food_dining": 0.0009021759033203124, "__label__games": 0.002529144287109375, "__label__hardware": 0.01120758056640625, "__label__health": 0.0014867782592773438, "__label__history": 0.0009093284606933594, "__label__home_hobbies": 0.00038313865661621094, "__label__industrial": 0.006015777587890625, "__label__literature": 0.0004601478576660156, "__label__politics": 0.00061798095703125, "__label__religion": 0.0011310577392578125, "__label__science_tech": 0.3408203125, "__label__social_life": 0.00019073486328125, "__label__software": 0.01250457763671875, "__label__software_dev": 0.5751953125, "__label__sports_fitness": 0.0014667510986328125, "__label__transportation": 0.037139892578125, "__label__travel": 0.0007185935974121094}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 26040, 0.01549]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 26040, 0.54277]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 26040, 0.83826]], "google_gemma-3-12b-it_contains_pii": [[0, 3480, false], [3480, 6756, null], [6756, 10953, null], [10953, 15189, null], [15189, 16902, null], [16902, 19634, null], [19634, 22763, null], [22763, 26040, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3480, true], [3480, 6756, null], [6756, 10953, null], [10953, 15189, null], [15189, 16902, null], [16902, 19634, null], [19634, 22763, null], [22763, 26040, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 26040, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 26040, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 26040, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 26040, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 26040, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 26040, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 26040, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 26040, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 26040, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 26040, null]], "pdf_page_numbers": [[0, 3480, 1], [3480, 6756, 2], [6756, 10953, 3], [10953, 15189, 4], [15189, 16902, 5], [16902, 19634, 6], [19634, 22763, 7], [22763, 26040, 8]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 26040, 0.0]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
5658c361d622d7cc6746b4a9b6766291f440d9b1
Caching your application data with MySQL and TokuDB Rick Pizzi & Andrea Ponzo Lastminute.com We are a publicly traded international company, amongst the worldwide leaders in the online travel & leisure industry, and we operate a portfolio of well established European brands: lastminute.com, Bravofly, Rumbo, Volagratis and Jetcost. **Who is lastminute.com group?** - 1200 people in 12 countries - 40 countries - Nearly 5 million APP downloads - Around 10 million passengers handled per year - Offering and services available in 17 languages *Percona Live Santa Clara 2017* Who are Rick & Andrea? Rick - 20+ years as UNIX system administrator - Sr MySQL DBA at PalominoDB - leading Lastminute.com Database Team since 2014 Andrea - 10+ years on MySQL - Sr MySQL DBA at Venere.com (Expedia Inc.) - joined Lastminute.com Database Team in 2015 Caching your application data with MySQL & TokuDB - Agenda - Overview of storage engines - Cache design - InnoDB vs TokuDB - Cache implementation details - Cache management - TokuDB tuning - Caveats - Q&A MySQL storage engines Storage engines are MySQL components that sit below the SQL layer and handle the actual I/O to/from the tablespaces. Let’s have a quick look at some of the most commonly used and/or known engines: - MyISAM - InnoDB - TokuDB - RocksDB MySQL storage engines: MYISAM - First storage engine to come with MySQL, since 3.23 bundled with server - BTREE based - Very fast MyISAM drawbacks: - Table level locking granularity only - no row locking, hence big penalty for concurrent access - No support for transactions and referential integrity - No crash recovery ("table is marked as crashed" anyone?) - data loss happens frequently Not suitable for production use, except in very particular situations and with read only workloads MySQL storage engines: INNODB - very mature and full featured engine - B+TREE based (improved range scans, amongst other things) - reasonably fast in most cases - foreign keys support - fully ACID compliant - crash safe - has row level locking supporting a certain degree of concurrency InnoDB drawbacks: - INSERT performance degrades as dataset size increases - B+TREE performance suboptimal with random INSERTs (when INSERTs are not in primary key order) MySQL storage engines: TOKUDB - based on Fractal Tree technology (PerconaFT) - better performance when inserting keys out of order - uses “message injection” for updates when page not in memory (defers I/O to a later time) - optimized for compression (although we are not leveraging it this time!) - reduced I/O compared to InnoDB (also due to larger block size) - SSD friendly! - transactions, ACID compliant, crash safe, row level locking TokuDB drawbacks: - cannot be a replacement for InnoDB in all situations (e.g. lack of foreign keys support) - although mature, is not as mature as InnoDB - often slower than InnoDB for read workloads Mysql storage engines: ROCKSDB - relatively new engine, not yet included in Percona Server (but will be soon) - developed by Facebook - almost production ready (Facebook uses it in production since some time already) - based on LSM (Log Structured Merge) - optimized for writes and compression, reduces I/O enormously - very SSD friendly! RocksDB drawbacks: - still very young, and under heavy development (not yet GA) - some features not yet supported, and there are other limitations (e.g. “bin” collation) - Foreign Key and FullText Index are not supported - ROW based binary logging MUST be used Cache design There are dozens of persistent caches out there, why use MySQL for caching? - leverage existing technology (MySQL heavily used throughout the company) - leverage existing knowledge (developing, deploying and maintaining) - reduce cost of ownership (no need for dedicated skills on other tech) - we love MySQL! Cache design (cont’d) We have several MySQL based cache servers used for caching different types of objects, across different applications. What we cache: - data fetched by calls to external providers (where we pay by # of requests, or when it’s expensive to reach the provider) - temporary object storage for applications that need short lived persistence, eg. application needs to reuse previously generated data Cache design: workflow CREATE TABLE `BIG_STORAGE_00` ( `HASH_ID` char(64) NOT NULL, `SERIALIZATION_TYPE` enum('JAVA','PROTOSTUFF') NOT NULL, `COMPRESSION_TYPE` enum('DEFLATE','LZ4','NONE','GZIP') NOT NULL, `RAW_DATA` mediumblob NOT NULL, `LAST_UPDATE` datetime NOT NULL, `EXPIRE_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, KEY `HASH_ID_IX` (`HASH_ID`), KEY `EXPIRE_DATE_IX` (`EXPIRE_DATE`) ) ENGINE=TokuDB DEFAULT CHARSET=latin1 ROW_FORMAT=TOKUDB_UNCOMPRESSED In order to be able to scale out, our application caching library contains sharding capabilities. We can: - shard across any number of tables on same database server - shard across multiple database servers by using multiple connection pools Based on [CACHE_KEY % 10] BIG_STORAGE_00|04 ➔ CACHE01 (cname) BIG_STORAGE_05|09 ➔ CACHE02 (cname) Change cache02 DNS Although TokuDB is really good at compression, we decided to compress the data at the application layer; type of compression used for the payload is saved into COMPRESSION_TYPE column. Benefits: - compression methods can be easily added or changed (not limited to what’s available at the DB layer) - reduced network bandwidth usage between application and database layer - reduced CPU usage on DB server - faster query response time (no compression/decompression overhead) InnoDB vs TokuDB or why we chose Toku for our cache servers InnoDB vs. TokuDB: benchmark details We ran some benchmarks to compare the two engines - based on sysbench 0.5 - using our cache table definition for the benchmarks - inserting and reading random rows to/from a single partitioned table - each row had a randomly variable payload between 0 and 16384 bytes - each row is inserted into a random partition (partitions spanning 10 days) InnoDB vs. TokuDB: why we wanted an InnoDB alternative - it’s known that InnoDB doesn’t perform well with random primary keys - we have observed InnoDB insert performance degradation when dataset becomes large in size - unfortunately we initially found out that TokuDB didn’t perform well either... actually, it’s worse than InnoDB at inserting, when PK is really random... ![Graph showing transactions per second (tps) for TokuDB and InnoDB with AVG Payload 16K and Random PK over time.] InnoDB vs. TokuDB: INSERT benchmark 45 minutes sysbench benchmark run, 40 threads, 8kb avg blob size, 56x Intel Xeon E5-2660 v4 @ 2.00GHz, 2x800G Intel SSD DC P3608 - # InnoDB - innodb_flush_method = O_DIRECT - innodb_log_files_in_group = 2 - innodb_log_file_size = 512M - innodb_flush_log_at_trx_commit = 2 - innodb_file_per_table = 1 - innodb_buffer_pool_size = 2G - innodb_file_format=barracuda - innodb_write_io_threads=8 - innodb_read_io_threads=8 - innodb_io_capacity = 600 - # TokuDB - tokudb_commit_sync=OFF - tokudb_fsync_log_period=5000 - tokudb_checkpointing_period=15 - tokudb_cleaner_iterations=10000 - tokudb_disable_prefetching=ON - tokudb_directio=ON - tokudb_cache_size=2G - tokudb_row_format=tokudb_uncompressed - tokudb_empty_scan=disabled InnoDB inserted 10,707,190 rows TokuDB inserted 7,489,946 rows :-( LastMinute.com Group Percona Live Santa Clara 2017 InnoDB vs. TokuDB: do we really need a primary key? InnoDB vs. TokuDB: INSERT benchmark, without Primary Key 45 minutes sysbench benchmark run, 40 threads, 8kb avg blob size, 56x Intel Xeon E5-2660 v4 @ 2.00GHz, 2 x800G Intel SSD DC P3608 InnoDB inserted 20,902,852 rows TokuDB inserted 70,302,791 rows :-) # InnoDB innodb_flush_method = O_DIRECT innodb_log_files_in_group = 2 innodb_log_file_size = 512M innodb_flush_log_at_trx_commit = 2 innodb_file_per_table = 1 innodb_buffer_pool_size = 2G innodb_file_format=barracuda innodb_write_io_threads=8 innodb_read_io_threads=8 innodb_io_capacity = 600 # TokuDB tokudb_commit_sync=OFF tokudb_fsync_log_period=5000 tokudb_checkpointing_period=15 tokudb_cleaner_iterations=10000 tokudb_disable_prefetching=ON tokudb_directio=ON tokudb_cache_size=2G tokudb_row_format=tokudb_uncompressed tokudb_empty_scan=disabled InnoDB vs TokuDB: more benchmarks without a primary key 2 hours sysbench benchmark, random key INSERT with 2K avg payload, workload not in memory, SSD - TokuDB is able to perform 3x better than InnoDB (~45k QPS vs ~15k) - it does so using less I/O! - throughput is stable over time, there is no degradation Benefits of not using a primary key - not having to look up keys when inserting saves lots of read I/O - TokuDB is very good at inserting rows when there is no primary key defined, much better than InnoDB Cache implementation details Access from application to caches happens through a common library nicknamed “Big Storage”. Key facts: - cache consists in key/value pairs - key is always a SHA-256 hash (64 bytes) - very random - payload is a compressed BLOB of variable size (avg size depends on cache type, ranging from 4k to 512m) - number of objects varies wildly depending on cache type and retention policy Here’s our standard table definition for caches. Note that there is no Primary Key defined :-) CREATE TABLE `BIG_STORAGE_00` ( `HASH_ID` char(64) NOT NULL, `SERIALIZATION_TYPE` enum('JAVA','PROTOSTUFF') NOT NULL, `COMPRESSION_TYPE` enum('DEFLATE','LZ4','NONE','GZIP') NOT NULL, `RAW_DATA` mediumblob NOT NULL, `LAST_UPDATE` datetime NOT NULL, `EXPIRE_DATE` datetime NOT NULL, KEY `HASH_ID_IX` (`HASH_ID`), KEY `EXPIRE_DATE_IX` (`EXPIRE_DATE`) ) ENGINE=TokuDB DEFAULT CHARSET=latin1 ROW_FORMAT=TOKUDB_UNCOMPRESSED (partitioning info omitted for the purpose of this slide) InnoDB vs. TokuDB: real use case - add object to cache* 1 hour sysbench benchmark run, 64 threads, 8kb avg blob size, 56x Intel Xeon E5-2660 v4 @ 2.00GHz, 2 x800G Intel SSD DC P3608 # InnoDB innodb_flush_method = O_DIRECT innodb_log_files_in_group = 2 innodb_log_file_size = 512M innodb_flush_log_at_trx_commit = 2 innodb_flush_log_at_timeout = 5 innodb_file_per_table = 1 innodb_buffer_pool_size = 10G innodb_file_format = barracuda innodb_write_io_threads = 8 innodb_read_io_threads = 8 innodb_io_capacity = 600 # TokuDB tokudb_commit_sync = OFF tokudb_fsync_log_period = 5000 tokudb_checkpointing_period = 15 tokudb_cleaner_iterations = 10000 tokudb_disable_prefetching = ON tokudb_directio = ON tokudb_cache_size = 10G tokudb_row_format = tokudb_uncompressed tokudb_empty_scan = disabled tokudb_enable_partial_eviction = ON tokudb_read_block_size = 16384 (*) InnoDB purge thread lags terribly behind in this test local s1 = sb_rand_str("#######") db_query("BEGIN"); db_query("DELETE FROM BIG_STORAGE_INNO WHERE HASH_ID = SHA2(" .. s1 .. ", 256) AND EXPIRE_DATE > NOW()"); db_query("INSERT INTO BIG_STORAGE_INNO VALUES(SHA2(" .. s1 .. ", 256), 'PROTOSTUFF', 'GZIP', REPEAT(CHAR(FLOOR(RAND()*96)+32), FLOOR(RAND()*16384)), NOW(), DATE_ADD(NOW(), INTERVAL FLOOR(RAND()*(96)+32), FLOOR(RAND()*(16384)), NOW()), DATE_ADD(NOW(), INTERVAL FLOOR(RAND()*(10)+1 day))"); db_query("COMMIT"); Percona Live Santa Clara 2017 InnoDB vs. TokuDB: real use case - fetch object from cache 1 hour sysbench benchmark run, 64 threads, 8kb avg blob size, 56x Intel Xeon E5-2660 v4 @ 2.00GHz, 2x800G Intel SSD DC P3608 # InnoDB innodb_flush_method = O_DIRECT innodb_log_files_in_group = 2 innodb_log_file_size = 512M innodb_flush_log_at_trx_commit = 2 innodb_flush_log_at_timeout = 5 innodb_file_per_table = 1 innodb_buffer_pool_size = 10G innodb_file_format = barracuda innodb_write_io_threads = 8 innodb_read_io_threads = 8 innodb_io_capacity = 600 # TokuDB tokudb_commit_sync = OFF tokudb_fsync_log_period = 5000 tokudb_checkpointing_period = 15 tokudb_cleaner_iterations = 10000 tokudb_disable_prefetching = ON tokudb_directio = ON tokudb_cache_size = 10G tokudb_row_format = tokudb_uncompressed tokudb_empty_scan = disabled tokudb_enable_partial_eviction = ON tokudb_read_block_size = 16384 (after filling table with approx 7M rows as per previous benchmark) local s1 = sb_rand_str("#####") db_query("SELECT RAW_DATA FROM BIG_STORAGE_TOKU WHERE HASH_ID = SHA2("..s1 ..", 256) AND EXPIRE_DATE > NOW()"); Cache management Cache management is done through MySQL range partitioning. Normally partitioned by day, partitions are created in advance, and every night we drop previous day’s partition to keep cache footprint small. Partitions are dropped at night when traffic is low, although TokuDB is pretty good at doing that in background, without noticeable impact. For special caches that have very short expiration and high volumes of traffic, we partition by the hour and drop old partitions hourly. A partition management script is needed to create new partitions and drop old ones. PalominoDB created a small yet powerful perl script for partition management as part of their data management tools. It’s called pdb-parted and can be found on GitHub at this link: We are using pdb-parted to handle the whole partition management across our clusters, including caches, since many years now. Cache management (cont’d) Example usage of pdb-parted Adding partitions for next 31 days: ``` /usr/local/dba/sbin/pdb-parted --add --interval d +31d h=10.10.10.10,D=thiscache,t=BIG_STORAGE_00,u=partman,p=****** ``` Dropping yesterday’s partition: ``` /usr/local/dba/sbin/pdb-parted --drop -0d h=10.10.10.10,D=thiscache,t=BIG_STORAGE_00,u=partman,p=****** ``` TokuDB tuning TokuDB tuning Here is the relevant part of the MySQL configuration we use in production on SSD based servers... tokudb_commit_sync=OFF tokudb_fsync_log_period=5000 tokudb_row_format=tokudb_uncompressed tokudb_checkpointing_period=15 tokudb_disable_prefetching=ON tokudb_cleaner_iterations=10000 tokudb_enable_partial_eviction=ON tokudb_read_block_size=16384 Rule of thumb for Toku memory and I/O: keep the defaults as per Percona recommendation :-) - TokuDB is very happy when Toku files can be cached by the O.S. - cache will default to 50% of memory that will be used for FT cachetable, remaining memory will be used to map in memory Toku data and indexes for faster access - a small cache size (e.g. 1G) will seriously penalize TokuDB for SELECTs (creates cache access contention) Since our cache data can be rebuilt in case of a crash, we do not enforce durability and are more interested in performance and overall response time. Hence: - tokudb_commit_sync=OFF (similar to InnoDB innodb_flush_log_at_trx_commit=2) - tokudb_fsync_log_period=5000: redo log is flushed to disk every 5 seconds (in case of crash lose last 5 seconds of data, but we do not really care, could be set higher) TokuDB tuning: checkpointing TokuDB checkpointing will impact your performance (QPS) by introducing a lot of variance if left to the default of 60 seconds or set higher. We keep it running continuously by setting `tokudb_checkpointing_period=15` Continuous checkpointing will yield a more homogeneous response time and QPS rate. There are two variables that control size of nodes in PerconaFT: - `tokudb_block_size` *(default 4M, size of intermediate FT nodes)* - `tokudb_read_block_size` *(default 64K, size of basement FT nodes)* Defaults are meant for old spinning disks, not really proper for SSD. - a 16K value for `tokudb_read_block_size` brought us big performance gain both for read and write on SSD based server - best thing is to experiment (but don’t set cache memory too low) Caveats when using TokuDB in production TokuDB has many moving parts... Unlike InnoDB, there are many moving parts in TokuDB that if tweaked can have an huge impact on your workload. Most notably ones listed below: - `tokudb_cache_size` - `tokudb_checkpointing_period` - `tokudb_cleaner_iterations` - `tokudb_cleaner_period` - `tokudb_fsync_log_period` (if `tokudb_commit_sync OFF`) - `tokudb_block_size` - `tokudb_read_block_size` - `tokudb_fanout` Beware of important TokuDB performance bugs! - Implement tree map file block allocation strategy - TokuDB ::info uses bad/lengthy function to provide table status* - tokudb does not use index even if cardinality is good* Bugs fixed in: - Percona Server release 5.6.35-81.0 - Percona Server release 5.7.17-12 * reported by us Beware of unresolved MySQL optimizer bugs... Statistics for partitioned tables in MySQL are only computed on largest partition (see https://bugs.mysql.com/bug.php?id=44059). If largest partition is in the past, where all rows have EXPIRE_DATE < NOW(), we are in trouble as both indexes (on HASH_ID and EXPIRE_DATE) have same cost and the optimizer can randomly pick the wrong one and scan all partitions. Workaround: make sure the index on HASH_ID comes *before* the one on EXPIRE_DATE to avoid production downtime! See: https://bugs.mysql.com/bug.php?id=85126 In any case don’t keep stale partitions around - drop them! Q & A Let’s keep in touch riccardo.pizzi@lastminute.com andrea.ponzo@lastminute.com https://mysqlnoob.blogspot.com [ Rick’s blog ] THANKS www.lastminute.comgroup.com
{"Source-Url": "https://www.percona.com/live/17/sites/default/files/slides/PL17-4541.pdf", "len_cl100k_base": 4595, "olmocr-version": "0.1.53", "pdf-total-pages": 45, "total-fallback-pages": 0, "total-input-tokens": 51482, "total-output-tokens": 6538, "length": "2e12", "weborganizer": {"__label__adult": 0.00034689903259277344, "__label__art_design": 0.00020694732666015625, "__label__crime_law": 0.0002689361572265625, "__label__education_jobs": 0.0005955696105957031, "__label__entertainment": 9.679794311523438e-05, "__label__fashion_beauty": 0.00012946128845214844, "__label__finance_business": 0.0028095245361328125, "__label__food_dining": 0.00028967857360839844, "__label__games": 0.0008249282836914062, "__label__hardware": 0.0017871856689453125, "__label__health": 0.0002894401550292969, "__label__history": 0.00017642974853515625, "__label__home_hobbies": 9.387731552124023e-05, "__label__industrial": 0.0006589889526367188, "__label__literature": 0.0001062154769897461, "__label__politics": 0.0001404285430908203, "__label__religion": 0.0002493858337402344, "__label__science_tech": 0.0240020751953125, "__label__social_life": 7.218122482299805e-05, "__label__software": 0.1292724609375, "__label__software_dev": 0.83642578125, "__label__sports_fitness": 0.0002313852310180664, "__label__transportation": 0.0005884170532226562, "__label__travel": 0.00026679039001464844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 17288, 0.02814]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 17288, 0.48841]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 17288, 0.77731]], "google_gemma-3-12b-it_contains_pii": [[0, 94, false], [94, 578, null], [578, 848, null], [848, 1054, null], [1054, 1313, null], [1313, 1807, null], [1807, 2267, null], [2267, 2912, null], [2912, 3515, null], [3515, 3528, null], [3528, 3839, null], [3839, 4257, null], [4257, 4746, null], [4746, 4989, null], [4989, 5107, null], [5107, 5582, null], [5582, 5643, null], [5643, 6027, null], [6027, 6518, null], [6518, 7440, null], [7440, 7492, null], [7492, 8304, null], [8304, 8613, null], [8613, 8819, null], [8819, 9231, null], [9231, 9836, null], [9836, 11257, null], [11257, 12335, null], [12335, 12352, null], [12352, 12835, null], [12835, 13336, null], [13336, 13700, null], [13700, 13714, null], [13714, 14074, null], [14074, 14504, null], [14504, 14914, null], [14914, 15246, null], [15246, 15708, null], [15708, 15748, null], [15748, 16160, null], [16160, 16495, null], [16495, 17120, null], [17120, 17126, null], [17126, 17253, null], [17253, 17288, null]], "google_gemma-3-12b-it_is_public_document": [[0, 94, true], [94, 578, null], [578, 848, null], [848, 1054, null], [1054, 1313, null], [1313, 1807, null], [1807, 2267, null], [2267, 2912, null], [2912, 3515, null], [3515, 3528, null], [3528, 3839, null], [3839, 4257, null], [4257, 4746, null], [4746, 4989, null], [4989, 5107, null], [5107, 5582, null], [5582, 5643, null], [5643, 6027, null], [6027, 6518, null], [6518, 7440, null], [7440, 7492, null], [7492, 8304, null], [8304, 8613, null], [8613, 8819, null], [8819, 9231, null], [9231, 9836, null], [9836, 11257, null], [11257, 12335, null], [12335, 12352, null], [12352, 12835, null], [12835, 13336, null], [13336, 13700, null], [13700, 13714, null], [13714, 14074, null], [14074, 14504, null], [14504, 14914, null], [14914, 15246, null], [15246, 15708, null], [15708, 15748, null], [15748, 16160, null], [16160, 16495, null], [16495, 17120, null], [17120, 17126, null], [17126, 17253, null], [17253, 17288, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 17288, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 17288, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 17288, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 17288, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 17288, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 17288, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 17288, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 17288, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 17288, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 17288, null]], "pdf_page_numbers": [[0, 94, 1], [94, 578, 2], [578, 848, 3], [848, 1054, 4], [1054, 1313, 5], [1313, 1807, 6], [1807, 2267, 7], [2267, 2912, 8], [2912, 3515, 9], [3515, 3528, 10], [3528, 3839, 11], [3839, 4257, 12], [4257, 4746, 13], [4746, 4989, 14], [4989, 5107, 15], [5107, 5582, 16], [5582, 5643, 17], [5643, 6027, 18], [6027, 6518, 19], [6518, 7440, 20], [7440, 7492, 21], [7492, 8304, 22], [8304, 8613, 23], [8613, 8819, 24], [8819, 9231, 25], [9231, 9836, 26], [9836, 11257, 27], [11257, 12335, 28], [12335, 12352, 29], [12352, 12835, 30], [12835, 13336, 31], [13336, 13700, 32], [13700, 13714, 33], [13714, 14074, 34], [14074, 14504, 35], [14504, 14914, 36], [14914, 15246, 37], [15246, 15708, 38], [15708, 15748, 39], [15748, 16160, 40], [16160, 16495, 41], [16495, 17120, 42], [17120, 17126, 43], [17126, 17253, 44], [17253, 17288, 45]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 17288, 0.0]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
1fbf6f888183592c07d3a68d74306e941c7bc2c4
Software Solutions Symposium 2017 March 20–23, 2017 Improvements in Safety Analysis for Safety-critical Software Systems Peter Feiler Software Engineering Institute Carnegie Mellon University Pittsburgh, PA 15213 Challenges in Existing System Safety Practices Current Reliance on Engineering Process Guidelines for Robust & Reliable Aircraft - DO-178B-Software Considerations in Airborne Systems and Equipment Certification - DO-248B-Final Report for the Clarification of DO-178B - DO-278-Guidelines for Communications, Navigation, Surveillance, and Air Traffic Management - DO-254-Design Assurance Guidance for Airborne Electronic Hardware - DO-297-Integrated Modular Avionics (IMA) Development Guidance and Certification Considerations - SAE-ARP4754-Certification Consideration for Highly Integrated or Complex Aircraft Systems - SAE-ARP4671- Guidelines for Airworthiness - FAA Advisory Circular AC 27-1B-Certification of Normal Category Rotorcraft - FAA Advisory Circular AC 29-2C-Certification of Transport Category Rotorcraft - ISO/IEC 12207-Software Life Cycle Processes - ARINC 653-Specification Standard for Time and System Partitioning - MIL-STD-882D-DoD System Safety - ADS-51-HDBK-Rotorcraft and Aircraft Qualification Handbook - AR-70-62-Airworthiness Release Standard - ADS-75-SS-Army Aviation System Safety Assessments and Analyses - ADS-48-PRF-Performance Specification for Airworthiness Qualification Requirements for Civil Aircraft in Instrument Meteorological Conditions and Civil Instrument Flight Rules - ADS-64-SP-Airworthiness Requirements for Military Rotorcraft Current methods explicitly depend on: - standards and regulations - rigorous examination of whole finished system and implicitly depend on: - conservative practices and safety culture (Rushby) Safety Practice in Development Process Context - Labor-intensive - Early in system engineering - Largely ignores software as a hazard source - Rarely repeated due to cost Leveson (MIT) Socio-technical Control Framework based on Rasmussen (NASA) model of risk management - Multiple hazard contributors in development and operational context We Rely on Software for Safe Aircraft Operation Quantas Airbus A330-300 Forced to make Emergency Landing - 36 Injured Thirty-six passengers and crew had to be evacuated from a mid-air emergency event that left three people injured, according to Qantas newspapers. Oct. 15 (Bloomberg) -- Airbus SAS issued an alert to airlines after Australian investigators said a computer fault on a Qantas Ltd. flight switched off the autopilot and generated false data for the jet to nosedive. The Airbus A330-300 was cruising at 37,000 feet (11,277 meters) when a computer fed incorrect information to the flight control system, the Australian Transport Safety Bureau said yesterday. The jet nosedived into the ocean 650 feet within seconds, slamming passengers and crew against the ceiling, before the pilots regained control. "This appears to be a unique event," the bureau said, adding that Airbus had not confronted similar issues before. The company is based in Toulouse, France. The Federal Aviation Administration says a software problem with Boeing 787 Dreamliners could lead to one of the advanced jetliners losing electrical power in flight, which could lead to loss of control. The FAA notified operators of the airplane Friday that if a 787 is powered continuously for 248 days, the plane will automatically shut down its alternating current (AC) electrical power. Safety Critical Software System Challenges 80% of faults discovered post unit test Post-unit test software rework cost 50% of total system development cost & growing Recertification cost is not proportional to system changes Sources: Critical Code; NIST, NASA, INCOSE, and Aircraft Industry Studies Mismatches in Assumptions in Safety-Critical System Interactions Why do system level failures still occur despite fault tolerance techniques being deployed in systems? Embedded software system as major source of hazards Software Reliability Observations • Software reliability does not adhere to the bathtub failure rate curve for hardware ![Bathtub curve for hardware reliability](image1.png) ![Revised bathtub curve for software reliability](image2.png) Lifespan of single design and physical product Multi-release error rate of operating systems • Software errors are design errors • Software is not perfectable (unreasonable Zero defect assumption) • Software is sensitive to operational context; testing has limited effectiveness In a given use scenario the software defect is triggered every time Improve Quality Analytical verification Coverage of exceptional conditions Resilience to software defects Software Solutions Symposium 2017 Operator Error Statistics 80% of accidents identified as due to pilot/operator errors - References: http://www.vtol.org/safety.html (AF, Army), Leveson & other studies - Result of single root cause event chain & focus on blame - Operational procedures are not always in line with actual system operation - Up to 75% of time dealing with operational work-around procedures instead of correcting the problem in software Need for re-certification cost reduction Challenges in Safety-Critical Digital Systems Embedded software system as major hazard source • High interaction complexity, mismatched assumptions, mode confusion • Accidents due to combinations of major and minor hazard contributors System safety analysis • Safety engineering largely viewed as a system engineering practice • Safety analysis processes are labor-intensive • Consistency between evolving architecture design and safety analysis models Virtual System Integration and Verification ## Reliability & Qualification Improvement Strategy ### 2010 SEI Study for AMRDEC Aviation Engineering Directorate <table> <thead> <tr> <th></th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td><strong>Mission Requirements</strong></td> <td><strong>Model Repository</strong></td> <td><strong>Operational &amp; failure modes</strong></td> <td></td> </tr> <tr> <td>Function</td> <td>Architecture Model</td> <td>Resource, Timing &amp; Performance Analysis</td> <td></td> </tr> <tr> <td>Behavior</td> <td>Component Models</td> <td>Reliability, Safety, Security Analysis</td> <td></td> </tr> <tr> <td>Performance</td> <td>System Implementation</td> <td></td> <td></td> </tr> <tr> <td>Survivability Requirements</td> <td>System configuration</td> <td></td> <td></td> </tr> <tr> <td>Reliability</td> <td></td> <td></td> <td></td> </tr> <tr> <td>Safety</td> <td></td> <td></td> <td></td> </tr> <tr> <td>Security</td> <td></td> <td></td> <td></td> </tr> </tbody> </table> ### Four pillars for Improving Quality of Critical Software-reliant Systems - Architecture-led Requirement Specification - Architecture-centric Virtual System Integration - Static Analysis & Compositional Verification - Incremental Assurance Plans & Cases throughout Life Cycle Software for Dependable Systems: Sufficient Evidence? (National Research Council Study) Testing is indispensable **BUT** - “A rigorous development process in which testing and code review are the only verification techniques cannot justify claims of extraordinarily high levels of dependability” - “Execution of even a large set of end-to-end tests, even with high levels of code coverage, in itself says little about the dependability of the system as a whole.” - “For testing to be a credible component of a [case for dependability], the relation between testing and properties claimed will need to be explicitly justified” - “Credible claims of dependability are usually impossible or impractically expensive to demonstrate after design and development are complete” Assurance that a system is dependable requires the construction and evaluation of a “dependability case” - Claims, arguments, evidence, expertise SAE Architecture Analysis & Design Language (AADL) Standard Suite The Physical System - Aircraft, Car, Train Command & Control The Software System - Embedded Operational Avionics & Mission Software - SW Design & Runtime Architecture Physical Interface Platform Component The Computer System - Computer System Hardware & OS Deployed on Utilizes Basis for Virtual System Integration and Analysis SAE AS5506 International Standard Suite Analysis of AADL models results in early discovery of mismatched interaction assumptions and system level problems Analyzable Architecture Models Discover System Level Issues Early in Development Generation of analysis models propagates architecture changes - **RESOURCE CONSUMPTION** - Bandwidth - CPU Time - Power Consumption - **REAL-TIME PERFORMANCE** - Deadlock/Starvation - Latency - Execution Time/Deadline - **DATA QUALITY** - Temporal Correctness - Data Precision/Accuracy - Confidence - **SAFETY & RELIABILITY** - MTBF - FMEA - Hazard Analysis - **SECURITY** - Intrusion - Integrity - Confidentiality SAE AS5506 AADL Three Dimensions of Requirement Coverage System interactions, state, behavior Environment Constraints/Controls System Input Behavior State Output Resources Guarantees Assumptions Invariants Implementation constraints Design & operational quality attributes Performance Transaction New products Change COTS Modifiability Utility Availability COTS S/W failures Security Data confidentiality Data integrity Exceptional conditions Invariants Fault impact & contributors Fault Propagation Ontology Omission errors Commission errors Value errors Sequence errors Timing errors Replication errors Rate errors Concurrency errors Authentication errors Authorization errors Behavior Output Control System State Input Behavior System Under Control State Actuator Sensor Automation of Safety Analysis Why Safety & Reliability Analysis Automation Current process is • Labor-intensive, years between repetition • Prone to inconsistencies with evolving architecture and other analyses • Requires knowledge of Markov, Petri net, and other notations Early automation experiments with AADL Steven Vestal, Honeywell, MetaH, Error Model, AADL committee, Avionics system trade studies during bidding (1999-) Myron Hecht, Aerospace Corp., member of AADL & DO-178C committee, Automated safety analysis of several satellite systems for JPL (2009-) FMEA with 26,000 failure modes and 25 levels of effects Thomas Noll, University of Aachen, COMPASS project, Automated safety analysis and verification of satellite systems for ESA (2008-) AADL Error Model Scope and Purpose System safety process uses many individual methods and analyses, e.g. - hazard analysis - failure modes and effects analysis - fault trees - Markov processes Goal: a general facility for modeling fault/error/failure behaviors that can be used for several modeling and analysis activities. Annotated architecture model permits checking for consistency and completeness between these various declarations. Related analyses are also useful for other purposes, e.g. - maintainability - availability - Integrity - Security Error Model Annex can be adapted to other ADLs Automation of Safety Analysis Practice (SAVI) A public Aircraft Wheel Brake System model Use of Error-Model and ARINC653 annexes Relevance for the avionics community Comparative study Federated vs. Integrated Modular Avionics (IMA) architecture Support of SAE ARP 4761 System Safety Assessment Practice Hazards (FHA), Fault Trees (FTA), Fault Impact (FMEA) Reliability/Availability (Markov Chain/Dependence Diagram) Error Model V2 Annotations of AADL Model Three levels of abstraction expressed by EMV2 • Focus on fault propagation across components - Probabilistic error sources, sinks, paths and transformations - Fault propagation and Transformation Calculus (FPTC) from York U. • Focus on fault behavior of components - Probabilistic typed error events, error states, propagations - Voting logic, error detection, recovery, repair • Focus on fault behavior in terms of subcomponent fault behaviors - Composite error behavior state logic maps states of parts into (abstracted) states of composite Fault tree generated from EMV2 annotations and propagation paths inferred from AADL model Coverage of Fault Propagation Taxonomy Fault Propagation Taxonomy Service errors - Omission - Commission Omission: $\forall i, (ts_i \in ST_i) \lor (\forall j \geq i, ts_j = \lnot)$ Value errors - Sequence errors - Replication errors - Concurrency errors Extensions to Powell/Vasiliades Ontologies Fault Lattice for Data streams - Value errors - Timing errors Control System - Behavior - State Output Input Actuator System Under Control - Behavior - State Cmd Input Sensor Output Improvements in Safety Analysis for Safety-critical Software Systems March 20–23, 2017 © 2017 Carnegie Mellon University Software Engineering Institute | Carnegie Mellon University Functional and System Architecture Consistency of Functional and System Fault Models Function Mappings Imply System Components as Common Error Source Software Induced Flight Safety Issue Original Preliminary System Safety Analysis (PSSA) System engineering activity with focus on failing components. Unhandled Hazard Discovery through Virtual Integration Virtual integration of architecture fault models recording SIL test observations detects unhandled fault. Corrupted data shows airspeed of 2000 knots Vibration causes data corruption through touching boards Response to corrupted airspeed causes stall Automated Fault Tree and Common Cause Analysis Automated Fault Tree Analysis from AADL Models Fault tree generation from annotated AADL model • AADL focuses on embedded software systems • Error Model V2 Annex specifies error behavior at three levels of abstraction • Architecture design changes are consistently reflected in fault tree Use of fault propagation taxonomy • Bounded set of failure effect types • Taxonomy coverage • Error propagation contracts and unhandled faults Common cause failure contributors • Identification of fan-out in propagation paths • Transformation of generated fault graph to eliminate/reduce dependent fault tree events Propagation and Recovery Dependency Graph AADL core model provides propagation paths - Port connections, access connections, remote service calls - Deployment binding of SW to HW Abstracted dependency graph Example: Petri net OSATE2 uses compact propagation graph derived from instance model Example System: GPS Dual redundant satellite signal receivers • One is sufficient for less precise location output Single power supply • Common cause failure source Error Propagation Specification ```plaintext abstract GPSProcessing features inSensor1: in data port; inSensor2: in data port; location: out data port; annex EMV2 {** use types ErrorLibrary, GPSErrorLibrary; error propagations inSensor1 : in propagation {ServiceOmission}; inSensor2 : in propagation {ServiceOmission}; location : out propagation {ServiceOmission, LowPrecisionData, IncorrectData}; processor: in propagation {ServiceOmission}; flows s1toloc: error path inSensor1{ServiceOmission} -> location{ServiceOmission}; s2toloc: error path inSensor2{ServiceOmission} -> location{ServiceOmission}; ptoloc: error path processor{ServiceOmission} -> location{ServiceOmission}; gpssrc: error source location{LowPrecisionData, IncorrectData}; end propagations; **}; end GPSProcessing; ``` Out propagation of different error types Error paths include propagation from processor binding Component Error Behavior Specification abstract GPSProcessing_computeError extends GPSProcessing annex EMV2 {** use types ErrorLibrary, GPSERRORLibrary; use behavior GPSERRORLibrary::GPSProcessingFailed; component error behavior events computeError: error Event; transitions internal: Operational -[computeError]-> Incorrect; lowPrecision: Operational -[inSensor1{ServiceOmission}] or inSensor2{ServiceOmission}]-> LowPrecision; inputNoService: all -[inSensor1{ServiceOmission}] and inSensor2{ServiceOmission}]-> NoService; CPUNoService: all -[processor {ServiceOmission}]-> NoService; propagations outNoService: NoService-[]-> location{ServiceOmission}; outLowPrecision: LowPrecision-[]-> location{LowPrecisionData}; outComputeErrorEffect: Incorrect-[]-> location{IncorrectData}; end component; properties emv2::OccurrenceDistribution => [ ProbabilityValue => 7.5e-4 ; Distribution => Poisson; ] applies to computeError; **}; end GPSProcessing_computeError; Handling Common Cause Failure Source - Propagation path fan out identifies common cause source Transformations on common cause elements Move common event up - (SSR1 or PS) and (SSR2 or PS) - => PS or (SSR1 and SSR2) Absorb subgate with common event - (SSR1 or PS) and PS => PS Eliminate replicate events - PS or PS => PS Flatten nested gates - E1 or (E2 or E3) => or{E1, E2, E3} Elimination of dependent events simplifies occurrence probability calculation Fault Tree for Degraded Mode Condition: only one receiver fails - Cannot include common cause contributors Scalability and Incremental Safety Analysis Abstract and Composite Error Model Specification at each architecture layer Reduce state-space through layered abstraction Consistency of abstract specification compositional specification and implementation fault models Abstraction across one or more architecture layers/tiers Understanding the Cause of Faults Through model-based analysis identify architecture induced unhandled, testable, and untestable faults and understand root causes, contributing factors, impact, and potential mitigation options. Root Cause of Data Loss Is Non-deterministic Temporal Buffer Read/Write Ordering Fault propagation Effects Engine Control Mode to Issue Shut Down Engine Sequence Reachability Analysis Of Unsafe States Fault Impact Analysis Detection of Unhandled Data Loss Fault Model validation Requirements Faults that can be tested Decision coverage Faults that cannot be tested Race conditions Faults that are unhandled Transient data loss in protocol Improved documentation & design Demonstrated in COMPASS project Use of text templates as formalism frontend From PSSA to SSA Model Validation Requirements Faults that can be tested Decision coverage Faults that cannot be tested Race conditions Faults that are unhandled Transient data loss in protocol Improved documentation & design Demonstrated in COMPASS project Use of text templates as formalism frontend From PSSA to SSA Benefits of Safety Analysis Automation Automation allows for - Early identification of potential problems - Single points of failure - Unanticipated effects - Larger set of failure modes and combinations - More levels of effects - Safety analysis of system and software architecture - More frequent re-analysis - Architecture trade studies - Consistency across analysis results Benefits of Virtual System Integration & Incremental Lifecycle Assurance Increased Confidence Through Verification And Testing Build the System Assure the System Reduced Cost through Early Discovery 80% Post Unit Test Discovery Increased Confidence Through Verification And Testing References Website [www.aadl.info](http://www.aadl.info) Public Wiki [https://wiki.sei.cmu.edu/aadl](https://wiki.sei.cmu.edu/aadl) Contact Information Peter Feiler SEI Fellow Telephone: +1 412.268.7790 Email: phf@sei.cmu.edu U.S. Mail: Software Engineering Institute Carnegie Mellon University 4500 Fifth Avenue Pittsburgh, PA 15213-3890 World Wide Web: http://www.sei.cmu.edu/architecture/research/model-based-engineering/ www.aadl.info www.aadl.info/wiki osate.org www.github.org/osate
{"Source-Url": "https://resources.sei.cmu.edu/asset_files/Presentation/2017_017_001_495811.pdf", "len_cl100k_base": 4336, "olmocr-version": "0.1.53", "pdf-total-pages": 40, "total-fallback-pages": 0, "total-input-tokens": 60567, "total-output-tokens": 6221, "length": "2e12", "weborganizer": {"__label__adult": 0.0004596710205078125, "__label__art_design": 0.0004253387451171875, "__label__crime_law": 0.0006341934204101562, "__label__education_jobs": 0.0009474754333496094, "__label__entertainment": 8.249282836914062e-05, "__label__fashion_beauty": 0.0001958608627319336, "__label__finance_business": 0.0003757476806640625, "__label__food_dining": 0.0003902912139892578, "__label__games": 0.0010709762573242188, "__label__hardware": 0.00295257568359375, "__label__health": 0.00047850608825683594, "__label__history": 0.0003185272216796875, "__label__home_hobbies": 0.00011533498764038086, "__label__industrial": 0.0010900497436523438, "__label__literature": 0.00022804737091064453, "__label__politics": 0.0003426074981689453, "__label__religion": 0.00040984153747558594, "__label__science_tech": 0.037506103515625, "__label__social_life": 0.0001016855239868164, "__label__software": 0.0096893310546875, "__label__software_dev": 0.9375, "__label__sports_fitness": 0.0004239082336425781, "__label__transportation": 0.00408935546875, "__label__travel": 0.0002770423889160156}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 21847, 0.01423]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 21847, 0.29301]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 21847, 0.81005]], "google_gemma-3-12b-it_contains_pii": [[0, 216, false], [216, 216, null], [216, 263, null], [263, 1903, null], [1903, 2245, null], [2245, 3616, null], [3616, 3919, null], [3919, 4141, null], [4141, 4883, null], [4883, 5345, null], [5345, 5810, null], [5810, 5854, null], [5854, 8219, null], [8219, 9139, null], [9139, 9697, null], [9697, 10246, null], [10246, 11053, null], [11053, 11083, null], [11083, 11812, null], [11812, 12417, null], [12417, 12837, null], [12837, 13526, null], [13526, 14020, null], [14020, 14356, null], [14356, 14507, null], [14507, 14817, null], [14817, 14864, null], [14864, 15475, null], [15475, 15770, null], [15770, 15941, null], [15941, 16851, null], [16851, 17900, null], [17900, 18368, null], [18368, 18477, null], [18477, 18803, null], [18803, 19920, null], [19920, 20304, null], [20304, 20592, null], [20592, 21489, null], [21489, 21847, null]], "google_gemma-3-12b-it_is_public_document": [[0, 216, true], [216, 216, null], [216, 263, null], [263, 1903, null], [1903, 2245, null], [2245, 3616, null], [3616, 3919, null], [3919, 4141, null], [4141, 4883, null], [4883, 5345, null], [5345, 5810, null], [5810, 5854, null], [5854, 8219, null], [8219, 9139, null], [9139, 9697, null], [9697, 10246, null], [10246, 11053, null], [11053, 11083, null], [11083, 11812, null], [11812, 12417, null], [12417, 12837, null], [12837, 13526, null], [13526, 14020, null], [14020, 14356, null], [14356, 14507, null], [14507, 14817, null], [14817, 14864, null], [14864, 15475, null], [15475, 15770, null], [15770, 15941, null], [15941, 16851, null], [16851, 17900, null], [17900, 18368, null], [18368, 18477, null], [18477, 18803, null], [18803, 19920, null], [19920, 20304, null], [20304, 20592, null], [20592, 21489, null], [21489, 21847, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 21847, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 21847, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 21847, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 21847, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 21847, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 21847, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 21847, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 21847, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 21847, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 21847, null]], "pdf_page_numbers": [[0, 216, 1], [216, 216, 2], [216, 263, 3], [263, 1903, 4], [1903, 2245, 5], [2245, 3616, 6], [3616, 3919, 7], [3919, 4141, 8], [4141, 4883, 9], [4883, 5345, 10], [5345, 5810, 11], [5810, 5854, 12], [5854, 8219, 13], [8219, 9139, 14], [9139, 9697, 15], [9697, 10246, 16], [10246, 11053, 17], [11053, 11083, 18], [11083, 11812, 19], [11812, 12417, 20], [12417, 12837, 21], [12837, 13526, 22], [13526, 14020, 23], [14020, 14356, 24], [14356, 14507, 25], [14507, 14817, 26], [14817, 14864, 27], [14864, 15475, 28], [15475, 15770, 29], [15770, 15941, 30], [15941, 16851, 31], [16851, 17900, 32], [17900, 18368, 33], [18368, 18477, 34], [18477, 18803, 35], [18803, 19920, 36], [19920, 20304, 37], [20304, 20592, 38], [20592, 21489, 39], [21489, 21847, 40]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 21847, 0.02212]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
cc766eba7df1cb5c60f90a59f204d7b37e2a400f
<table> <thead> <tr> <th>Title</th> <th>Path-analytic distributed object prefetching</th> </tr> </thead> <tbody> <tr> <td>Author(s)</td> <td>Luo, Y; Lam, KT; Wang, CL</td> </tr> <tr> <td>Citation</td> <td>The 10th International Symposium on Pervasive Systems, Algorithms and Networks (I-SPAN 2009), Kaohsiung, Taiwan, 14-16 December 2009. In International Symposium on Parallel Architectures, Algorithms, and Networks, 2009, p. 98-103</td> </tr> <tr> <td>Issued Date</td> <td>2009</td> </tr> <tr> <td>URL</td> <td><a href="http://hdl.handle.net/10722/125695">http://hdl.handle.net/10722/125695</a></td> </tr> <tr> <td>Rights</td> <td>International Symposium on Parallel Architectures, Algorithms, and Networks. Copyright © IEEE.; ©2009 IEEE. Personal use of this material is permitted. However, permission to reprint/republish this material for advertising or promotional purposes or for creating new collective works for resale or redistribution to servers or lists, or to reuse any copyrighted component of this work in other works must be obtained from the IEEE.; This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.</td> </tr> </tbody> </table> Path-Analytic Distributed Object Prefetching Yang Luo, King Tin Lam, Cho-Li Wang Department of Computer Science The University of Hong Kong Hong Kong {yloo, ktlam, clwang}@cs.hku.hk Abstract—This paper presents our studies on the connectivity between objects and traversal behavior over the access paths among objects in order to devise profitable prefetching policies for object-based distributed systems. We propose a profiling strategy that can classify classes and fields into a handful of generic types exhibiting distinctive and exploitable access patterns during the runtime. Based on the classifications, we propose an improved algorithm of object prefetching to select best candidates to prefetch under practical message size limits. We implement the methodology into our JESSICA2 distributed Java virtual machine and evaluate its effectiveness. Our experimental results show that our prefetching policies are able to eliminate over 93% cache coherence protocol messages and halve the execution time for fine-grained applications. Keywords—object sharing; prefetching; object access patterns; distributed Java virtual machine; distributed shared memory I. INTRODUCTION In most distributed systems, prefetching is a canonically useful technique to reduce data access latency by aggregating more data units into a single round-trip. If the amount of prefetched data sustains good spatial or temporal locality, the speculation will be positive and give lower amortized access cost. The usual data unit is a memory page or an object. Page-based prefetching has been well-studied in previous work including [1, 2, 3, 4]. In this paper, we focus on object prefetching techniques. Generally, there are two approaches to determining which objects to prefetch: static (by compiler-based analysis [5]) or dynamic (by exploiting connectivity between objects online [6]). With runtime information accessible, the latter is usually more flexible and accurate. For object-based distributed shared memory (DSM) systems, prefetching shared objects for reducing data misses is critical to performance since the network latency involved in fetching an object from remote memory is much more costly than local heap access. As future accesses on prefetched objects are not all guaranteed to happen, we need to strike a balance on the prefetching amount to reduce the negative impact of sending unneeded objects. Prefetching accuracy can be calculated by accessed bytes over the total bytes of data prefetched (we consider all bytes of an object accessed if a single read/write on any of its fields is performed). Significant speed improvement in recent years [12, 13] has enabled the unlocking of Java for high-performance computing over heterogeneous platforms. The distributed Java virtual machine (JVM) is a design of middleware platform that aims to provide multithreaded Java applications with transparent clustering support. Our previous work [6, 7] has built a virtual shared heap, the global object space (GOS), to hide JVM boundaries from object access. Connectivity-based prefetching is known to be good in accuracy for the distributed JVM since objects in Java cannot be accessed without following reference fields. On top of a home-based cache coherence protocol, we proposed object pushing to prefetch objects in close proximity to the current or root object being accessed. In one implementation [6], upon receiving an object access request, the home node uses a breadth-first search to collect the reachable objects to push into the message buffer until its size reaches an optimal length. Another implementation [8] is to fetch only objects at the next immediate level under the current object graph without message length limit but carry out compression on the outgoing message to save network bandwidth. However, we find that these rather conservative policies are still far from ideal for fine-grained applications that need more careful design on prefetching to achieve good aggregation effect while not worsening accuracy. In a heap comprising home and cache objects, problems could arise from stale cache or unstable connectivity among shared objects. Capturing correct interrelations between objects in such an environment to aid prefetching has to consider various issues including access locality, message size limit, search orientations (depth or breadth of traversal) and other system dynamics like home migrations [6]. This paper studies more advanced techniques to do object pushing based on path analysis. To be specific, an object is prefetching via following a reference field of another object, and we recognize the field a specific path of access. By recording access counts along different paths, we classify the relevant fields and classes into a few generic types with tailor-made policies. Our new prefetching can adapt in traversal order, breadth and depth of reachability for the best candidates to prefetch under practical message size limits. We implement the proposed methodology in an upgraded version of our JESSICA2 distributed JVM with a vastly revamped GOS that runs a more efficient protocol enforcing home-based lazy release consistency (HLRC) [11]. In our protocol, only home objects holding the latest copy can be prefetched along to the requester. Our system adopts a per-thread cache storage model that avoids the arrival of prefetched objects from overwriting dirty cache objects. By proper invalidation and flushing updates to homes across lock/unlock bounda- ries, cache coherence is maintained regardless of our prefetching mechanism introduced. The system is tested with medium- to fine-grained applications, seeing promising performance gain after applying the path-analytic policies. For the rest of this paper, Section 2 explains the difficult issues involved in object prefetching. Section 3 and 4 present our observed access patterns and the path-analytic prefetching algorithm respectively. Section 5 evaluates our implementation experimentally. We review the related work in Section 6 and conclude this paper in Section 7. II. CHALLENGES AND PROBLEMS In this section, we will explain several interrelated issues posing stern difficulty to distributed object prefetching. 1) Excessively fine granularity: fine-grained and object-intensive applications generally make prefetching harsher to work effectively. Taking Barnes-Hut, one of our tested benchmark programs, as an example: its basic data unit, the Body object, is composed of a few small-sized objects with a total size less than 100 bytes only. This implies at least 10-100 objects need to be packed in a single message if we are to achieve good aggregation effect on communication. For this application, our earlier scheme in [8] which prefetches only a single level deeper into the current object graph seems too conservative although it can maintain quite good accuracy. However, the dilemma is aggressive prefetching can benefit this case but hurt performance in another due to the negative impact of prefetching unneeded objects, which is equivalent to paying multiple times of access cost for a single memory location as well as network bandwidth. If the thread in execution will not access the prefetched objects eventually, this will on the contrary slow down the system. So we need more intelligent prefetching that can guarantee accuracy while going beyond conservative policies. 2) Biased paths: Different paths of access often indicate different usage in application-specific logics. It is a natural phenomenon that some paths are followed less frequently than others. A good example is that in many recursive data structures like trees and linked lists, some paths acting as “backlinks” (such as fields regularly named node.parent, item.prev, etc) are seldom accessed. Without analysis on path usage, we would hurt performance by following and prefetching along these rarely used paths. Apparently, we cannot make a guess at path usage based on field names and require a profiling method to discover such biasness to give more weight to those more frequently used objects. 3) Fragmentation effect: As mentioned, using a breadth-first search (BFS) to pack objects until hitting the message length limit is a rational policy to do prefetching. However, if the BFS stops immediately at a certain buffer threshold, this can leave many objects isolated, which have not been prefetched but their parents have been. These orphans have to be fetched individually later, in short messages, making the communication largely fragmented. Fig. 1 illustrates this problem. At the beginning (see (a)), thread T1 only has a reference to object A. When it accesses A, it asks the home of A for its latest copy. With simple buffer-limit prefetching, the home packs objects A, B and C altogether for T1, with references of D, E, F and G left behind. Later (see (b)), T1 accesses D, E, F and G in turn and sees they have to be fetched separately from the home because there is no more connectivity between them. Missing to include D to G in the first prefetch message creates four short-length but long-latency fetching round-trips over the cluster network. III. OBJECT PATH TRAVERSAL PATTERNS This section describes our classification scheme over classes and reference fields to characterize access behavior. A. Class-Level Types (Object Types) An object type or class can be broadly classified into the below generic types to characterize their access behavior. 1) Recursive class: a class is recursive if and only if it contains at least one reference field forming a recursive path. In other words, a recursive class would have self-referential pointers and most likely corresponds to common recursive data structures like trees and linked lists. 2) Terminal class: a class is terminal if and only if it has no outgoing paths of reference fields or all outgoing paths are either terminal or backward (to be explained). 3) Normal class: refer to simply all other object types. B. Field-Level Types (Path Types) A prefetching path, i.e. reference field, can be characterized into a few different types as follows. 1) Recursive field: a field is recursive if and only if its enclosing class and the target class it points to are the same or share a non-trivial common base (parent or super-) class, and it is not a backward field. Here a non-trivial common base class means classes other than java.lang.Object. 2) Backward field: a field is identified (by the system) as backward if most prefetched objects through that path are found duplicate. As mentioned in Section 2, some fields like Figure 1. Orphaned objects causing fragmented communication nodes.parent and item.prev acting as “backlinks” are rarely followed by threads. A simple unbiased scheme prefetching these paths as well within the same HLRC interval will see many duplicate objects prefetched from these “backward” paths. Our definition of backward fields is not given by a path’s function which is difficult to guess. Instead, they are discovered by the system which observes paths’ prefetching behavior. Backward paths receive the lowest priority during prefetching unless there are no other choices. 3) Terminal field: a field is terminal if and only if it points to a terminal class. Since terminal class cannot be fetched except via a single specific field, the default policy is to always follow it unless we encounter some very large objects (normally arrays in Java) as aggressively prefetching them usually impacts performance when there is no absolute guarantee on accuracy. Terminal paths are usually reached near the end of the prefetch traversal or search process. 4) Normal field: simply refer to all other fields. Table I shows a real example of object and path types from a typical molecule dynamics application. The use of terminal classes like Vector3D is very common in Java as composite value type is not supported by the language application. Notice that at the very beginning there is no backward path. All backward paths are identified at runtime. Since the definition of terminal class depends on backward paths, once we detect a backward path, we need to search over the JVM’s internal class graph to mark all class and path type changes. In this example, detecting Molecule.parent to be backward will change Molecule to be a terminal class (since outgoing paths no longer exist) and Link.mol to be a terminal path. ### Table I. Example of Object and Path Types <table> <thead> <tr> <th>Class</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>Link</td> <td>class</td> <td>RECURSIVE class</td> </tr> <tr> <td></td> <td>Molecule</td> <td>TERMINAL path (was NORMAL path)</td> </tr> <tr> <td></td> <td>Vector3D position</td> <td>BACKWARD path (was RECURSIVE path)</td> </tr> <tr> <td></td> <td>double mass</td> <td>TERMINAL class (was NORMAL class)</td> </tr> <tr> <td></td> <td>Vector3D velocity</td> <td>BACKWARD path (was NORMAL path)</td> </tr> </tbody> </table> Table II shows the pseudo-code of our object prefetching algorithm. A queue is used to maintain candidate objects for path analysis. Prefetching begins with putting the root object into the queue (START_PREFETCH(root)). A BSF loop keeps consuming items from the queue (DEQUEUE()) and calls the PREFETCH_OBJ routine on the dequeued object. The routine will find for every reference field of the object the path data structure (GET_PATH) maintaining metadata like the field’s class, path type, and profiling counts for backward path discovery. By checking lines 18, 21, the algorithm can tell if the current field would contribute a good path to continue the prefetching (ENQUEUE(cand)) if yes. The whole process is aided by the following designs of policy. 1) Priorities of paths: Priority is given to terminal paths, recursive paths and then normal paths. Backward paths will only be used as a last resort. The traversal order on fields in PREFETCH_OBJ() is adjusted according to their path types. 2) Forcing terminal: If we find a terminal path during prefetching, we will always prefetch the target object if it is not too big even if the termination condition (TERM_COND()) at line 21 has been reached. This is because if we do not prefetch it at this moment, we would have no chances and they will become orphans to be separately fetched later. Since the cost of creating one extra message is much more than just including some more bytes in the current message, this speculation is usually profitable. 3) Discovering backward paths: For an HLRC protocol, each object only needs to be fetched at most once within the same interval. So we can maintain a simple hashed lookup-set on which objects have been prefetched for which thread during its current interval, so that objects will never be fetched twice. This doesn’t take much space overhead since hash entries for past intervals can simply be discarded, and a thread only has to append its current interval number to an object request. Based on this mechanism, we can discover backward paths dynamically by computing their duplicate rates online (obtained by comparing counts of successful prefetching and attempted but duplicate prefetching). We detect backward paths in PREFETCHED(), which checks if the object has been prefetched before (from the same thread’s same HLRC interval), and updates our per-path statistics of successful and failed (duplicate) prefetch attempts. When the duplicate rate is exceedingly high, the path is changed to backward (i.e. calling CHANGE_TO_BACKWARD(path)). 4) Traversal order of terminal objects: Even with limit on message length, a straightforward BFS traversal could still make the outgoing buffer greatly overflow because of our terminal-forcing policy. For example, Fig. 2 shows a tree-like object graph composed of terminal and non-terminal objects. If we use a BFS-only policy, we first prefetch non-terminal objects A, B and C, then terminal objects D, E, F and G which are found near the end of traversal. When we have prefetched D, the size limit is already hit, but we have to force E, F, and G into the buffer to avoid orphans; such overflow is too much to be acceptable. To make our limit meaningful, we alter the original BFS policy to be a global BFS with a local DFS (depth-first search). In this policy, if we discover a subgraph with terminal paths, we use a DFS to prefetch all these objects immediately (by the recursive call PACK_OBJ_WITH_DFS()). As prefetching goes on, if we hit the message size limit, the worst-case overflow would be the extra bytes for finishing our current terminal subgraph. In realistic fine-grain applications, such terminal subgraph is usually quite small (within several hundreds bytes). We will evaluate in the next section whether it is true that message size overflow is reasonably close to the predefined limit. Fig. 2 also shows how our revised policy works. We first prefetch object A, then B. When we are prefetching B, we find its terminal paths towards D and E, so we change to use a local DFS to prefetch them immediately. Now the size limit has been hit, so we stop and leave C, F, G to the next message. The rationale behind this “global BFS; local DFS” policy is that a subgraph with terminal paths often indicates a logical aggregation of objects that should be fetched together. This policy achieves a balanced situation depicted by Fig. 3 (b) between serious fragmentation (Fig. 3 (a)) and poor accuracy with excessive bytes prefetched (Fig. 3 (c)). V. PERFORMANCE EVALUATION A. Experimental Platform and Benchmarks Our experiments are conducted in the HKU Gideon 300 Cluster [9] which consists of 300 PCs interconnected by a 312-port 100BASE-T Fast Ethernet switch. Each PC is of the following hardware configuration: an Intel Pentium 4 2GHz processor, 512MB DDR RAM and a 40GB-IDE hard disk. A segment of 8 nodes is used for all the experiments. We evaluate our prefetching policies with two benchmark programs ported from the SPLASH-2 suite [10] to Java, namely Barnes-Hut and Water-Spatial, which belong to fine- and medium-grained applications respectively. Barnes-Hut is an N-Body simulation using hierarchical methods in which basic elements (i.e. bodies) are organized into a hierarchy, in our case an octree, to speed up computations. Such a hierarchy often involves a fine-grained recursive data structure that is difficult to support efficiently in early DSM systems without a careful prefetching scheme. Barnes-Hut also shows an irregular fine-grained object sharing pattern (each terminal body is of size less than 100 bytes) with some locality and moderate compute-intensiveness. Water-Spatial is a molecule dynamics application, simulating interactions between groups of water molecules. Each molecule is of at most a few hundreds bytes. Molecules within the same 3D box are put into a linked list to allow fast adding or removal of molecules. To sum up, runtime properties of Water-Spatial include near-neighbor 3D-box sharing patterns with medium granularity and intensive computations. For large problem sizes (sufficient room for JIT optimization), the raw speed of our ported Java version when running in server VM mode (tested with Sun JDK 1.6) is highly comparable to the C version (compiled with -O3 option). Barnes-Hut in Java runs even faster than the C code by 8-10% while Water-Spatial in Java is about 10% slower than its C counterpart. B. Testing Methodology We evaluate our implementation in the following aspects: 1) Effect of policies: To test the effectiveness of each of our policies, they are enabled incrementally and compared to no prefetching and the simple policy (used in our earlier work [6]). In each configuration, we measure the execution time, message count and volume in bytes for each program. 2) Accuracy of different message size limits: As we’ve discussed, choosing an optimal message size limit is vital to strike a balance between accuracy and aggregation effect. To check this out, we do the benchmarking with different trials of message size limits and measure each configuration’s accuracy and real performance (total execution time). To measure prefetching accuracy, we compare message volume for different configurations with and without prefetching. If we do not enable prefetching and fetch a single object every time, it is guaranteed that each fetched object will be accessed. Therefore, we can use the measured message volume without prefetching as a reference of how many bytes a perfectly accurate prefetching scheme should prefetch, thus deducing prefetching accuracy by comparing with our prefetching schemes. This measurement is also more meaningful than calculating accuracy by object count, because object size can vary a lot in real-life applications. 3) Message length distribution: From the viewpoint of load balancing, we need to ensure short messages are as few as possible and most messages are uniform in size. To test for this, we log each protocol message’s size for different policies, and draw a distribution graph. We also check whether the “global BFS; local DFS” policy is effective to avoid too much overflow of our buffer size limit. C. Experimental Results Table III-IV show the effect of our object prefetching policies for each application. Our scheme does prefetch more bytes but the reduction on total execution time and message count is phenomenal. Skipping backward paths is useful to both applications. Forcing terminal objects by a local DFS is very effective for finer granularity. We can see Barnes-Hut is more sensitive to the policies than Water-Spatial since it is not only more fine-grained but also having a recursive data structure (octree) with a much larger fan-out (8 vs. 1). Table V-VI show the effect of different size limits on object prefetching (Note: raw execution times in Table V-VI do not reconcile with those in Table III-IV which were taken with some other profiling options, out of the scope of this work, enabled). Configurations of small limits (256B-1KB) are inferior to larger limits (4KB-16KB) in terms of message count and execution time. Lifting up the limit doesn’t affect accuracy and generally improves speedup due to less fragmentation. Barnes-Hut shows an abnormal increase of message count with 64KB size limit, slightly extending the execution time. After close inspection, we attribute this to the application’s inherent fragmentation so that prefetching a too large object graph leaves many smaller object graphs behind that need be fetched individually. Thus, we consider 4K a fairly appropriate size limit parameter although other sizes close to it may behave equally well. Again, Barnes-Hut reacts more readily towards the effect than Water-Spatial. Fig. 4 displays the size distribution of some real message samples collected using 2KB size limit. Water-Spatial undergoes regular behavior with high accuracy under all policies. By application nature, the objects are larger and there is no complex data structure. Therefore, incrementally enabling more advanced policies won’t help much in further regulat- ing communications and shortening execution since the simpler policy stack is already good enough, though enabling all policies won’t make things worse too. The case of Barnes-Hut is more complex, but we can observe two things. First, the two policies with terminal forcing induce much fewer small messages, i.e. less fragmentation. Second, if we do not enforce the local DFS policy (i.e. Backward + Terminal - DFS), there could be significantly more messages that exceed much our size limit. To sum up, our best policy (Backward + Terminal + local DFS) works pretty well to regulate message sizes, eliminating most small messages while ensuring message overflow is bounded. VI. RELATED WORK Remote page prefetching has been studied in a number of page-based DSMs. In [2, 3], history prefetching and aggregate prefetching, which exploit temporal and spatial locality respectively, are studied and compared. Their work also did evaluation on Barnes and Water but showed no practical speedup. Page-based prefetching is found not effective for fine-grained applications. Our work belongs to dynamic or runtime prefetching at per-object granularity. Previously, we have studied connectivity-based prefetching at a basic level [6]. The work of this paper discusses a more advanced prefetching strategy that analyzes access paths with their behavior learnt. Compared to [6], this work shows an extra 34% improvement in execution time in the best case. Jackal [5] employs object-graph aggregation techniques to reduce access checks and network roundtrips needed to fault in relevant objects. Their compiler detects regions that contain susceptible cache misses, and replaces access checks on the individual objects in the object graph with a single access check on the graph’s root object. Object fault will bring in the entire graph. This improves both sequential and parallel performance. While Jackal uses the compiler to recognize a local aggregation of objects, our system detects it by more general and less conservative runtime methods of access tracking and path analysis. VII. CONCLUSION AND FUTURE WORK This paper has described a new method to prefetch objects more effectively in a distributed object sharing system. By means of access path tracking and analysis, we classify fields and classes into a handful of types providing clues on how likely they will be needed by the requester. Our prefetching scheme can learn about the weights of paths and balance between accuracy and aggregation effect. It would be interesting to see if any other generic access patterns are worth being analyzed during the prefetch process. ACKNOWLEDGMENT This research is supported by Hong Kong RGC grant HKU7176/06E and China 863 grant 2006AA01A111. REFERENCES <table> <thead> <tr> <th>Size Limit</th> <th>Execution Time Raw (sec.)</th> <th>Change (%)</th> <th>Message Count Raw</th> <th>Change (%)</th> <th>Message Volume (KB)</th> <th>Accuracy (%)</th> </tr> </thead> <tbody> <tr> <td>No Pre.</td> <td>40.00</td> <td>N/A</td> <td>384,155</td> <td>N/A</td> <td>37,833</td> <td>N/A</td> </tr> <tr> <td>256B</td> <td>24.72 -38.20</td> <td>91,000</td> <td>-76.31</td> <td>59,567</td> <td>63.51</td> <td></td> </tr> <tr> <td>1KB</td> <td>20.83 -47.91</td> <td>33,690</td> <td>-91.23</td> <td>59,692</td> <td>63.38</td> <td></td> </tr> <tr> <td>4KB</td> <td>19.47 -51.31</td> <td>16,923</td> <td>-95.59</td> <td>59,745</td> <td>63.32</td> <td></td> </tr> <tr> <td>16KB</td> <td>19.76 -50.60</td> <td>10,666</td> <td>-97.22</td> <td>59,617</td> <td>63.46</td> <td></td> </tr> <tr> <td>64KB</td> <td>21.41 -46.48</td> <td>15,487</td> <td>-95.97</td> <td>59,282</td> <td>63.82</td> <td></td> </tr> </tbody> </table> <table> <thead> <tr> <th>Size Limit</th> <th>Execution Time Raw (sec.)</th> <th>Change (%)</th> <th>Message Count Raw</th> <th>Change (%)</th> <th>Message Volume (KB)</th> </tr> </thead> <tbody> <tr> <td>No Pre.</td> <td>12.30</td> <td>N/A</td> <td>144,061</td> <td>N/A</td> <td>31,087</td> </tr> <tr> <td>256B</td> <td>8.79 -28.53%</td> <td>36,499</td> <td>-74.66%</td> <td>32,098</td> <td>96.85%</td> </tr> <tr> <td>1KB</td> <td>8.41 -31.62%</td> <td>23,060</td> <td>-83.99%</td> <td>31,988</td> <td>97.18%</td> </tr> <tr> <td>4KB</td> <td>7.61 -38.11%</td> <td>14,098</td> <td>-90.21%</td> <td>31,227</td> <td>99.55%</td> </tr> <tr> <td>16KB</td> <td>7.44 -39.46%</td> <td>5,138</td> <td>-96.43%</td> <td>31,218</td> <td>99.58%</td> </tr> <tr> <td>64KB</td> <td>7.41 -39.72%</td> <td>5,116</td> <td>-96.45%</td> <td>31,204</td> <td>99.63%</td> </tr> </tbody> </table> TABLE V. EFFECT OF MESSAGE SIZE LIMIT ON BARNES-HUT TABLE VI. EFFECT OF MESSAGE SIZE LIMIT ON WATER-SPATIAL
{"Source-Url": "http://hub.hku.hk/bitstream/10722/125695/1/Content.pdf", "len_cl100k_base": 6415, "olmocr-version": "0.1.49", "pdf-total-pages": 7, "total-fallback-pages": 0, "total-input-tokens": 25827, "total-output-tokens": 7365, "length": "2e12", "weborganizer": {"__label__adult": 0.00035500526428222656, "__label__art_design": 0.0003070831298828125, "__label__crime_law": 0.00038552284240722656, "__label__education_jobs": 0.0007205009460449219, "__label__entertainment": 9.810924530029296e-05, "__label__fashion_beauty": 0.0001852512359619141, "__label__finance_business": 0.00025773048400878906, "__label__food_dining": 0.0003573894500732422, "__label__games": 0.0007114410400390625, "__label__hardware": 0.0020618438720703125, "__label__health": 0.0006532669067382812, "__label__history": 0.0003812313079833984, "__label__home_hobbies": 0.0001145005226135254, "__label__industrial": 0.00052642822265625, "__label__literature": 0.0003001689910888672, "__label__politics": 0.0003032684326171875, "__label__religion": 0.0005316734313964844, "__label__science_tech": 0.1402587890625, "__label__social_life": 0.00011414289474487303, "__label__software": 0.01446533203125, "__label__software_dev": 0.83544921875, "__label__sports_fitness": 0.0003628730773925781, "__label__transportation": 0.0006794929504394531, "__label__travel": 0.00026154518127441406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 31432, 0.03665]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 31432, 0.30712]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 31432, 0.89201]], "google_gemma-3-12b-it_contains_pii": [[0, 1202, false], [1202, 6716, null], [6716, 11885, null], [11885, 15565, null], [15565, 20590, null], [20590, 24277, null], [24277, 31432, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1202, true], [1202, 6716, null], [6716, 11885, null], [11885, 15565, null], [15565, 20590, null], [20590, 24277, null], [24277, 31432, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 31432, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 31432, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 31432, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 31432, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 31432, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 31432, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 31432, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 31432, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 31432, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 31432, null]], "pdf_page_numbers": [[0, 1202, 1], [1202, 6716, 2], [6716, 11885, 3], [11885, 15565, 4], [15565, 20590, 5], [20590, 24277, 6], [24277, 31432, 7]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 31432, 0.27027]]}
olmocr_science_pdfs
2024-11-25
2024-11-25
32232c5104d19cca143e153390f19340b85d6321
[REMOVED]
{"Source-Url": "http://du.diva-portal.org/smash/get/diva2:1817536/FULLTEXT01.pdf", "len_cl100k_base": 4472, "olmocr-version": "0.1.48", "pdf-total-pages": 8, "total-fallback-pages": 0, "total-input-tokens": 23208, "total-output-tokens": 6211, "length": "2e12", "weborganizer": {"__label__adult": 0.00042819976806640625, "__label__art_design": 0.0004239082336425781, "__label__crime_law": 0.000370025634765625, "__label__education_jobs": 0.001922607421875, "__label__entertainment": 0.00010019540786743164, "__label__fashion_beauty": 0.00019931793212890625, "__label__finance_business": 0.0007271766662597656, "__label__food_dining": 0.0004291534423828125, "__label__games": 0.0007071495056152344, "__label__hardware": 0.0009179115295410156, "__label__health": 0.0007810592651367188, "__label__history": 0.00030040740966796875, "__label__home_hobbies": 0.00015223026275634766, "__label__industrial": 0.0006265640258789062, "__label__literature": 0.00042128562927246094, "__label__politics": 0.0002313852310180664, "__label__religion": 0.00041294097900390625, "__label__science_tech": 0.06903076171875, "__label__social_life": 0.00016319751739501953, "__label__software": 0.007205963134765625, "__label__software_dev": 0.9130859375, "__label__sports_fitness": 0.0003829002380371094, "__label__transportation": 0.0008006095886230469, "__label__travel": 0.00024020671844482425}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 21814, 0.09127]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 21814, 0.23253]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 21814, 0.87703]], "google_gemma-3-12b-it_contains_pii": [[0, 2444, false], [2444, 5486, null], [5486, 8525, null], [8525, 11404, null], [11404, 14468, null], [14468, 16033, null], [16033, 18775, null], [18775, 21814, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2444, true], [2444, 5486, null], [5486, 8525, null], [8525, 11404, null], [11404, 14468, null], [14468, 16033, null], [16033, 18775, null], [18775, 21814, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 21814, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 21814, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 21814, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 21814, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 21814, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 21814, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 21814, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 21814, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 21814, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 21814, null]], "pdf_page_numbers": [[0, 2444, 1], [2444, 5486, 2], [5486, 8525, 3], [8525, 11404, 4], [11404, 14468, 5], [14468, 16033, 6], [16033, 18775, 7], [18775, 21814, 8]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 21814, 0.0]]}
olmocr_science_pdfs
2024-11-25
2024-11-25
b18ee2f97012f00d13f71f14d5e120dc424ceef5
What’s in a Theorem Name? (Rough Diamond) David Aspinall\(^1\) and Cezary Kaliszyk\(^2\) \(^1\) LFCS, School of Informatics, University of Edinburgh, UK. \(^2\) Institut für Informatik, University of Innsbruck, Austria. Abstract. ITPs use names for proved theorems. Good names are either widely known or descriptive, corresponding to a theorem’s statement. Good names should be consistent with conventions, and be easy to remember. But thinking of names like this for every intermediate result is a burden: some developers avoid this by using consecutive integers or random hashes instead. We ask: is it possible to relieve the naming burden and automatically suggest sensible theorem names? We present a method to do this. It works by learning associations between existing theorem names in a large library and the names of defined objects and term patterns occurring in their corresponding statements. 1 Introduction How do we name theorems? Science has a tradition of historical reference, attaching names by attribution to their discoverer. HOL Light contains fine examples such as RIEMANN_MAPPING_THEOREM: \[ \forall s. \text{open } s \land \text{simply-connected } s \iff s = \{\} \lor s = (\mathbb{R}^2) \lor \\ \exists f, g. \text{holomorphic_on } s \land g \text{holomorphic_on } \text{ball}(0, 1) \land \\ (\forall z. z \text{IN } s \implies f z \text{IN } \text{ball}((0, 1) \land \\ (\exists y, z. z \text{IN } s \implies f z = z) \land \\ (\forall z. z \text{IN } \text{ball}((0, 1) \implies g z \text{IN } s \land f(g z) = z) \] Mere lemmas are seldom honoured with proper names. Papers and textbooks use localised index numbers instead (“see Lemma 5.7 on p.312”) which is succinct but unhelpful. For practical proof engineering, working with large developments and libraries, we are quickly swamped with intermediate lemmas. Despite search facilities in some ITPs, users still need to name statements, leading to the proliferation of less profound descriptive names such as: \[ \text{ADD_ASSOC : } \forall m n p. m + (n + p) = (m + n) + p \\ \text{REAL_MIN_ASSOC : } \forall x y z. \text{min } x (\text{min } y z) = \text{min } (\text{min } x y) z \\ \text{SUC_GT_ZERO : } \forall x. \text{Suc } x > 0 \] Descriptive names are convenient and mnemonic, based on the statement of a theorem, and following conventions due to the author, library or system. But inventing names requires thought, and remembering them exactly later can be tricky. Unsurprisingly, people complain about the burden of naming, even inventing schemes that generate automatic names like (in Flyspeck [4]): Such (fuzzy) hashes of theorem statements or sequential numbers give no clue of content, and we are back to old-fashioned indices. Some readers may be happy, accepting that names should have “denotation but not connotation” (as Kripke recalled the position of Mill [6]). But like Kripke, we see value in connotation: after all, a name is the handle for a potentially much longer statement. So we wonder: is it possible to relieve theorem naming burden by automatically naming theorems following established conventions? Given that we have large corpora of carefully named theorems, it is natural to try a learning approach. 2 Parts of names and theorems To start, we examine the form of human-generated descriptive theorem names. These are compound with separators: $l_0 \ldots l_m$, where the $l_i$ are commonly used stem words (labels). Examples like REAL_MIN_ASSOC show a connection between names of constants (MIN), their types (REAL), and the structure of the statement (ASSOC). Using previous work on features for learning-assisted automated reasoning [5], we extract three characterizations of theorem statements: - **Symbols**: constant and type names (including function names); - **Subterms**: parts of the statement term where no logical operators appear; - **Patterns**: subterms, with abstraction over names of defined objects. Patterns allow us to model certain theorem shapes, such as commutativity, associativity, or distributivity, without the actual constants these properties talk about [2]. For examples like SUC_GT_ZERO, we see that where the name parts occur is important. So we also collect: - **Positions**: for each feature $f$, a position $p(f)$, normalised so that $0 \leq p(f) \leq 1$, given by the position of $f$ in the print order of the statement. The leftmost feature has position 0 and the rightmost 1; if only a single feature is found, it has position $\frac{1}{2}$. Names are treated correspondingly: for $l_0 \ldots l_m$, the stems are assigned equidistant positions $p(l_0) = 0, \ldots, p(l_m) = 1$. 3 Learning associations between names and statements We investigate two schemes for associating theorem statements with their names: - **Consistent**: builds an association between symbols (e.g., constant and type names) and parts of theorem names; - **Abstract**: uses patterns to abstract from concrete symbols, building a matching between positions in statements and name parts. We hypothesise that the first scheme might be the more successful when used within a specific development, (hopefully) consistently re-using the same sub-components of relevant names, whereas the second may do better across different developments (perhaps ultimately, even across different provers). To try these schemes out, we implement a k-Nearest Neighbours (kNN) multi-label classifier. A proposed label is computed together with a weighted average of positions. The algorithm first finds a fixed number $k$ of training examples (named theorem statements), which are most similar to a set of features being considered. The stems and positions from the training examples are used to estimate the relevance of stems and proposed positions for the currently evaluated statement. The nearness of two statements $s_1, s_2$ is given by $$n(s_1, s_2) = \sqrt{\sum_{f \in T(s_1) \cap T(s_2)} w(f)^2}$$ where $w(f)$ is the IDF (inverse document frequency) weight of a feature $f$. To efficiently find nearest neighbours, we index the training examples by features, so we can ignore examples that have no features in common with the currently considered statement. Given the set of $k$ training examples nearest to the current statement, we evaluate the relevance of a label as follows: $$R(l) = \sum_{s_1 \in N \cap T(s_1)} \frac{n(s_1, s_2)}{||T(s_1)||}$$ We propose positions for a stem using the weighted average of the positions in the recommendations; weights are the corresponding nearness values. <table> <thead> <tr> <th>Feature</th> <th>Frequency</th> <th>Position</th> <th>IDF</th> </tr> </thead> <tbody> <tr> <td>$(V_0 + (V_1 + V_2)) = (V_0 + V_1) + V_2$</td> <td>1</td> <td>0.37</td> <td>7.82</td> </tr> <tr> <td>$((V_0 + V_1) + V_2)$</td> <td>1</td> <td>0.75</td> <td>7.13</td> </tr> <tr> <td>$(V_0 + V_1) + V_2$</td> <td>4</td> <td>0.72</td> <td>2.62</td> </tr> <tr> <td>$\forall$num.($\forall$num.($\forall$num.$((V_0 + (V_1 + V_2)) = ((V_0 + V_1) + V_2))))$</td> <td>3</td> <td>0.21</td> <td>1.15</td> </tr> <tr> <td>$=$</td> <td>1</td> <td>0.43</td> <td>0.23</td> </tr> <tr> <td>$\forall$</td> <td>3</td> <td>0.15</td> <td>0.03</td> </tr> </tbody> </table> **Table 1.** Selected features extracted from the statement of ADD_ASSOC. As an example, we examine how the process works with the consistent naming scheme and the ADD_ASSOC statement shown previously. Our algorithm uses the statement in a fully-parenthesised form with types attached to binders: $\forall$num.($\forall$num.($\forall$num.$(((V_0 + V_1) + V_2)) = (((V_0 + (V_1 + V_2))))$)) From this statement, features are extracted, computing their frequency, average position and then IDF across the statement. A total of 46 features are extracted; Table 2. Nearest neighbours found for \texttt{ADD\_ASSOC}. Table 1 shows a selection ordered by rarity (IDF). The highest IDF value is for the feature most specific to the overall statement: it captures associativity of \(+\). Next, Table 2 shows the nearest neighbours for the features of \texttt{ADD\_ASSOC} among the HOL Light named theorems, discounting \texttt{ADD\_ASSOC} itself. Most of these are associativity statements. The stem \texttt{AC} is commonly used in HOL to denote associative-commutative properties. Finally, the first predicted stems with their predicted positions are presented in Table 3. With \texttt{ASSOC} and \texttt{ADD} being the first two suggested stems, taking into account their positions, \texttt{ADD\_ASSOC} is indeed the top prediction for the theorem name. The following predictions are reasonable too: \texttt{AC\_ADD\_ASSOC}, \texttt{AC\_NUM\_ADD\_ASSOC}, \texttt{AC\_ADD}, \texttt{NUM\_ADD\_ASSOC}. <table> <thead> <tr> <th>Theorem name</th> <th>Statement</th> <th>Nearness</th> </tr> </thead> <tbody> <tr> <td>MULT_ASSOC</td> <td>((V0 * (V1 * V2)) = ((V0 * V1) * V2))</td> <td>553</td> </tr> <tr> <td>ADD_AC_i</td> <td>((V0 + V1) + V2) = (V0 + (V1 + V2)))</td> <td>264</td> </tr> <tr> <td>EXP_MULT</td> <td>((\text{EXP} V0 (V1 * V2)) = (\text{EXP} (\text{EXP} V0 V1) V2))</td> <td>247</td> </tr> <tr> <td>HREAL_ADD_ASSOC</td> <td>((V0 +_h (V1 +_h V2)) = ((V0 +_h V1) +_h V2))</td> <td>246</td> </tr> <tr> <td>HREAL_MUL_ASSOC</td> <td>((V0 *_h (V1 *_h V2)) = ((V0 *_h V1) *_h V2))</td> <td>246</td> </tr> <tr> <td>REAL_ADD_ASSOC</td> <td>((V0 +_r (V1 +_r V2)) = ((V0 +_r V1) +_r V2))</td> <td>246</td> </tr> <tr> <td>REAL_MUL_ASSOC</td> <td>((V0 *_r (V1 *_r V2)) = ((V0 *_r V1) *_r V2))</td> <td>246</td> </tr> <tr> <td>REAL_MAX_ASSOC</td> <td>(\text{MAX}_r V0 (\text{MAX}_r V1 V2)) = (\text{MAX}_r (\text{MAX}_r V0 V1) V2))</td> <td>246</td> </tr> <tr> <td>INT_ADD_ASSOC</td> <td>((V0 +_l (V1 +_l V2)) = ((V0 +_l V1) +_l V2))</td> <td>246</td> </tr> <tr> <td>REAL_MIN_ASSOC</td> <td>(\text{MIN}_r V0 (\text{MIN}_r V1 V2)) = (\text{MIN}_r (\text{MIN}_r V0 V1) V2))</td> <td>246</td> </tr> </tbody> </table> Table 3. Stems and positions suggested by our algorithm, sorted by relevance measure. Unsurprisingly, the consistent scheme performs less well in situations where new defined objects appear in a statement, it can only suggest stems it has seen before. The abstract scheme addresses this. For this, we first gather all symbol names in the training examples and order them by decreasing frequency. Next, for every training example we find the non-logical objects that appear, and replace their occurrences by object placeholders, with the constants numbered in the order of their global frequencies. For example, a name like \texttt{DIV\_EQ\_0} becomes \texttt{C0\_EQ\_C3}, and the theorem statement is abstracted similarly. For the statement of the theorem ADD_ASSOC the first three names predicted by the abstract naming scheme are: +_ASSOC, num_+, and num+_ASSOC. The use of the stem ADD is only predicted with \( k > 20 \). 4 Preliminary evaluation We perform a standard leave-one-out cross-validation to evaluate how good names predicted on a single dataset are. The predictor is trained on all the examples apart from the current one to evaluate, and is tested on the features of the current one. For 2298 statements in the HOL Light core library, the results are presented in Table 4. We explored four different options for the algorithm: - Upper: names are canonicalised to upper case. - AbsN: we use the abstraction scheme described above for naming. - AbsT: we use abstraction in statements before training. - Stem: we use a stemming operation to break down names. The first option is useful in the libraries of HOL Light and HOL4 where the capitalization is mostly uniform, but may not be desired in proof assistant libraries where this is not the case. For example \texttt{min} and \texttt{Min} are used with different semantics in Isabelle/HOL. The last option allows us to model the naming convention in HOL Light where a statement is relative to a type, but the type name does not get repeated. For example, a theorem that relates the constants \texttt{REAL_ABS} and \texttt{REAL_NEG} can be given the name \texttt{REAL_ABS_NEG} rather than \texttt{REAL_ABS_REAL_NEG}. Each row in Table 4 is a combination of options. Results are split in the columns: the number of statements for which the top prediction is the same as the human-given name (First Choice); the number where the human name is in place 2-10 (Later Choice); one of the ten names is correct modulo stem order (Same Stems); the number where the human-used stems are predicted but not combined correctly (All Stems); and the number for which at least part of the prediction is correct (Stem Overlap). Altogether, the human-generated names are among the top ten predictions by some instance of the algorithm in over 50% of cases; 40% for the best performing version based on the abstract scheme. The abstract scheme beats the consistent mechanism even in the same library. The final column shows the number of cases that fail completely. These include cases with familiar (historical) names such as: - \texttt{EXCLUDED_MIDDLE} (proposed reasonable name: \texttt{DISJ_THM}) - \texttt{INFINITY_AX} (proposed reasonable name: \texttt{ONTO_ONE}). We would not expect to predict these names, unless they are already given in the training data. In other cases, failure might indicate inconsistency: the human names may not always be “correct”. We uncovered some cases of inconsistency such as where multiplication was occasionally called \texttt{MULT} rather than \texttt{MUL}, for example. <table> <thead> <tr> <th>Setup Options</th> <th>First Choice</th> <th>Later Choice</th> <th>Same Stems</th> <th>All Stems</th> <th>Stem Overlap</th> <th>Fail</th> </tr> </thead> <tbody> <tr> <td>-</td> <td>118</td> <td>533</td> <td>180</td> <td>911</td> <td>516</td> <td>40</td> </tr> <tr> <td>Upper</td> <td>134</td> <td>583</td> <td>182</td> <td>901</td> <td>474</td> <td>24</td> </tr> <tr> <td>AbsN</td> <td>187</td> <td>517</td> <td>222</td> <td>849</td> <td>474</td> <td>49</td> </tr> <tr> <td>AbsN+Stem</td> <td>218</td> <td>530</td> <td>208</td> <td>849</td> <td>460</td> <td>33</td> </tr> <tr> <td>AbsN+Upper</td> <td>203</td> <td>461</td> <td>250</td> <td>888</td> <td>478</td> <td>18</td> </tr> <tr> <td>AbsN+AbsT</td> <td>172</td> <td>243</td> <td>125</td> <td>919</td> <td>755</td> <td>84</td> </tr> <tr> <td>AbsN+AbsT+Upper</td> <td>206</td> <td>387</td> <td>211</td> <td>771</td> <td>680</td> <td>43</td> </tr> <tr> <td>AbsN+AbsT+Stem</td> <td>214</td> <td>455</td> <td>178</td> <td>881</td> <td>532</td> <td>38</td> </tr> <tr> <td>AbsN+Stem+Upper</td> <td>238</td> <td>491</td> <td>299</td> <td>835</td> <td>418</td> <td>17</td> </tr> <tr> <td>AbsN+AbsT+Stem+Upper</td> <td>273</td> <td>501</td> <td>291</td> <td>757</td> <td>459</td> <td>17</td> </tr> <tr> <td>Combined</td> <td>336</td> <td>728</td> <td>271</td> <td>632</td> <td>321</td> <td>10</td> </tr> </tbody> </table> Table 4. Leave-one-out cross-validation on the HOL Light core dataset. 5 Conclusions The initial results are encouraging and suggest foundations for name-recommender systems that might be built into ITP interfaces. Even if the perfect name is not proposed, suggestions may spark an idea for the user. We plan to go further and look at case studies such as renaming Flyspeck, or using naming maps as a bridge between different ITPs. Moreover, more advanced machine learning schemes could be used to distinguish the use of the same symbol for different operators. Related work. This appears to be the first attempt to mine named theorems and produce a recommender system for naming new theorems in a meaningful way. There have been a number of non-meaningful proposals, e.g., Flyspeck’s random 8-character identifiers [4]; Mizar’s naming scheme of theory names and numbers (examples like WAYBEL34.67 [3]); the use of MD5 recursive statement hashes [8]. Identifier naming has been studied in software engineering. Lawrie et al [7] investigated name consistency in large developments. Deissenboeck and Pizka [1] build a recommender similar to our consistent scheme (but using different methods). They note that programming style guides say identifiers should be “self-describing” to aid comprehension. Indeed, program obfuscators, intended to hinder comprehension, randomize identifiers, producing names like those in Flyspeck. Acknowledgments. This work has been supported by UK EPSRC (EP/J001058/1) and the Austrian Science Fund FWF (P26201). References
{"Source-Url": "https://www.research.ed.ac.uk/portal/files/25410118/namespark_short_1.pdf", "len_cl100k_base": 4648, "olmocr-version": "0.1.53", "pdf-total-pages": 8, "total-fallback-pages": 0, "total-input-tokens": 20247, "total-output-tokens": 5257, "length": "2e12", "weborganizer": {"__label__adult": 0.00042057037353515625, "__label__art_design": 0.0007681846618652344, "__label__crime_law": 0.0004887580871582031, "__label__education_jobs": 0.0032291412353515625, "__label__entertainment": 0.00014698505401611328, "__label__fashion_beauty": 0.0002474784851074219, "__label__finance_business": 0.0003504753112792969, "__label__food_dining": 0.0004696846008300781, "__label__games": 0.0007715225219726562, "__label__hardware": 0.0008268356323242188, "__label__health": 0.0007700920104980469, "__label__history": 0.0004892349243164062, "__label__home_hobbies": 0.00018596649169921875, "__label__industrial": 0.0006833076477050781, "__label__literature": 0.0010843276977539062, "__label__politics": 0.0004405975341796875, "__label__religion": 0.0007696151733398438, "__label__science_tech": 0.202392578125, "__label__social_life": 0.00023949146270751953, "__label__software": 0.014404296875, "__label__software_dev": 0.76953125, "__label__sports_fitness": 0.0003485679626464844, "__label__transportation": 0.0006051063537597656, "__label__travel": 0.0002503395080566406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 16863, 0.05137]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 16863, 0.34497]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 16863, 0.83499]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 2603, false], [2603, 5034, null], [5034, 7640, null], [7640, 10220, null], [10220, 13067, null], [13067, 15846, null], [15846, 16863, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 2603, true], [2603, 5034, null], [5034, 7640, null], [7640, 10220, null], [10220, 13067, null], [13067, 15846, null], [15846, 16863, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 16863, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 16863, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 16863, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 16863, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 16863, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 16863, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 16863, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 16863, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 16863, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 16863, null]], "pdf_page_numbers": [[0, 0, 1], [0, 2603, 2], [2603, 5034, 3], [5034, 7640, 4], [7640, 10220, 5], [10220, 13067, 6], [13067, 15846, 7], [15846, 16863, 8]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 16863, 0.28448]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
d029d9e597caa40a88bbe3c29aeb70c83303f310
Introduction to Multi-Agent Programming 3. Fundamental Agent Architectures Logic-Based, Reactive, and Hybrid Architectures, CS-Freiburg Case Study Alexander Kleiner, Bernhard Nebel Contents - Introduction - Logic-Based Architectures - Reactive Architectures - Subsumption Architecture - Behavior Networks - Hybrid Architectures - Case Study: Action Selection of the CS-Freiburg soccer team - Conclusion Introduction History of development 1956-1985: Originally agents were mainly based on symbolic reasoning - Researches concluded the weakness of this approach for time-constrained domains 1985-present: Research on reactive agents - Decision making based on syntactic manipulation of the representation - The idea that intelligent behavior is seen as innately linked to the environment an agent occupies - intelligent behavior is not disembodied, but is a product of the interaction the agent maintains with its environment - the idea that intelligent behavior emerges from the interaction of various simpler behaviors From 1990-present: a number of alternatives proposed: hybrid architectures, which attempt to combine the best of reasoning and reactive architectures Logic-Based Architectures Introduction • Traditional approach of building AI systems, known as { symbolic AI} – Contains an explicitly represented, { symbolic} model of the world – The state of the world is represented by a database of predicates • Open(valve221) • Temperature(reactor4726,321) – Makes decisions about what actions to perform via symbolic reasoning, e.g., { logical deduction} or theorem proving – Idea that intelligent behavior can be generated by such representation and manipulation of { symbols} Logic-Based Architectures Formal Model • Action selection by using theorem proving • Basic idea is to use logic to encode a theory stating the best action to perform in any given situation • Let: – $\rho$ be this theory (typically a set of rules) – $\Delta$ be a logical database that describes the current state of the world – $A$ be the set of actions the agent can perform – $\Delta, \rho \models \phi$ mean that $\phi$ can be proven from $\Delta$ using $\rho$ • We assume the automatic execution of the functions – $see(s)$, which returns percepts according to the current world state (not one-to-one!) – $next(\Delta, p)$, which updates the database according to new percepts Logic-Based Architectures Action Selection Algorithm ```plaintext function action (Δ∈D): A { // try to find an action explicitly prescribed for each a∈A do { if Δ, ρ ├ Do(a) then return a } // try to find an action not excluded for each a∈A do { if Δ, ρ \( \not\) Do(a) then return a } return NULL } ``` Logic-Based Architectures Example: Vacuum World (1) - **Cleaning robot** with - percepts $P = \{\text{dirt, } X, Y, \theta\}$ - Actions $A = \{\text{turnRight, forward, suck}\}$ - **Start**: $(0,0,\text{North})$ - **Goal**: searching and cleaning dirt Use of domain predicates to solve problem: - $In(x,y)$: agent is at $(x, y)$ - $Dirt(x,y)$: there is dirt at $(x, y)$ - $Facing(d)$: the agent is facing direction $d$ Logic-Based Architectures Example: Vacuum World (2) • Set of rules $p$ for solving the problem: - $\text{In}(x,y) \land \text{Dirt}(x,y) \rightarrow \text{Do(suck)}$ - $\text{In}(0,0) \land \text{Facing(north)} \land \neg\text{Dirt}(0,0) \rightarrow \text{Do(forward)}$ - $\text{In}(0,1) \land \text{Facing(north)} \land \neg\text{Dirt}(0,1) \rightarrow \text{Do(forward)}$ - $\text{In}(0,2) \land \text{Facing(north)} \land \neg\text{Dirt}(0,2) \rightarrow \text{Do(turn)}$ - $\text{In}(0,2) \land \text{Facing(east)} \rightarrow \text{Do(forward)}$ - ... • In order to ensure always one single action, $\neg\text{Dirt}(X,Y)$ has to be explicitly checked Logic-Based Architectures Example: Vacuum World (3) • Advantages – Pro-active behavior (deliberation) – Elegant logical semantics • Problems: – How to convert video camera input to $Dirt(0, 1)$? – Time complexity of reasoning • Time of reasoning can be non-instantaneous • During computation, the dynamic world might change and thus the solution not valid anymore! • How to represent temporal information, e.g., how a situation changes over time? Plan-based Architectures • A variation of logic-based architectures • A planning system is responsible for generating action sequences in order to reach the goals • Special-purpose reasoning system geared towards generating plans and based on that selecting the right action • First system: STRIPS (in the 70’s) • These days: Numerous systems (e.g. our system Fast Downward and extensions) BDI Architectures - Motivated from philosophy: theory of practical reasoning requires belief, desire, and intention (BDI) - **Beliefs** represent the informational state of the agent - Beliefs can also include inference rules - what an agent believes may not necessarily be true (and may change in the future) - stored in database - **Desires** represent the motivational state of the agent - Objectives or situations that the agent would like to accomplish (e.g. find the best price, go to the party or become rich) - **Goals** are desires that have been adopted for active pursuit by the agent. - Goals must be consistent, e.g., one should not have concurrent goals to go to a party and to stay at home - **Intentions** represent the deliberative state of the agent - what the agent has chosen to do. - Are desires to which the agent has to some extent committed. - In implemented systems, this means the agent has begun executing a plan. - **Successful example:** Procedural Reasoning System (PRS) (Georgeff & Lansky 1987) Reactive Architectures Brooks: Subsumption Architecture • Brooks’ Vision: – Intelligent behaviour can be generated *without* explicit representations of the kind that symbolic AI proposes – Intelligent behaviour can be generated *without* explicit abstract reasoning of the kind that symbolic AI proposes – Intelligence is an *emergent* property of certain complex systems • Two key ideas: – *Situatedness and embodiment*. 'Real' intelligence is situated in the world, not in disembodied systems such as theorem provers or expert systems. – *Intelligence and emergence*. 'Intelligent' behaviour arises as a result of an agent's interaction with its environment. Also, intelligence is 'in the eye of the beholder' - it is not an innate, isolated property. Subsumption Architecture Brooks’ Vision (1) The traditional model: cognition intermediates between perception and action Subsumption Architecture Brooks’ Vision (2) The new model: perception and action is all there is. Cognition is only in the eye of the observer. Original slides from R. Brooks held at the seminar “From Pixels to Predicates” (1983) Subsumption Architecture Behaviors and Layered control - Decision making by a set of task accomplishing behaviors - Behaviors are direct mappings from observations to actions - Processing of raw sensor data - Direct coupling between observation and action, e.g. light switch pressed → light on - Behaviors implemented as asynchronous finite state machines - Multiple behaviors can “fire” simultaneously - mechanism for action selection: subsumption hierarchy - Behaviors organized in layers - Higher layer behaviors inhibit lower level ones - E.g., “Avoid obstacles“ lower layer (higher priority) than “drive to goal“ - Note behaviors are acting independently and communicate asynchronously, however are not pro-active as in MAS Subsumption Architecture Layered Control From Brooks, “A Robust Layered Control System for a Mobile Robot”, 1985 For Example: • **Level0**: Avoid Obstacles • **Level1**: Wander aimlessly around • **Level2**: Heading towards goals points • **Level3**: Select unexplored locations as goals **Subsumption Architecture** **Formal Model** - A behavior $b \in \text{Beh}$ is $(c, a)$ with $c \subseteq P, a \in A$, where $P$ is the set of percepts and $A$ the set of actions. - A behavior fires if the environment is in state $s \in S$ and iff $\text{see}(s) \in c$. - The subsumption hierarchy is implemented by the inhibition relation $b_1 \prec b_2$, denoting “$b_1$ inhibits $b_2$.” Subsumption Architecture Action Selection Algorithm ```plaintext function action (s ∈ S): A { // Compute the set of firing behaviors FB = {(c, a) | (c, a) ∈ Beh ∧ see(s) ∈ c} // find action with highest priority for each (c, a) ∈ FB do { if ¬∃(c', a') ∈ FB such that (c', a') ⪯ (c, a) then return a } return NULL } → Time complexity: O(n^2) ``` Subsumption Architecture Steels’ Mars Explorer Experiment (1) • Steels 1990: Task of exploring a distant planet, more concretely, to collect samples of a particular type of precious rock. – The location of the rock samples is not known in advance, but they are typically clustered in certain spots. – A number of autonomous vehicles are available that can drive around the planet collecting samples and later reenter a mother ship spacecraft to go back to Earth. – There is no detailed map of the planet available – No communication between the vehicles due to obstacles, such as hills, valleys, etc. • Solution idea – Gradient field: Direction and distance to the mother ship can be computed from an emitted radio signal – Indirect communication: Robots release “radioactive crumbs” that can be detected by others (enables emergent behavior) Subsumption Architecture Steels’ Mars Explorer Experiment (2) Individual agent’s (goal-directed) behavior: \[ \begin{align*} \text{obstacle} & \rightarrow \text{changeDirection} & & (1) \\ \text{carryingSamples} \land \text{atTheBase} & \rightarrow \text{dropSamples} & & (2) \\ \text{carrying Samples} \land \neg \text{atTheBase} & \rightarrow \text{travelUpGradient} & & (3) \\ \text{detectSample} & \rightarrow \text{pickUpSample} & & (4) \\ \text{TRUE} & \rightarrow \text{moveRandomly} & & (5) \end{align*} \] Subsumption hierarchy: \((1) \prec (2) \prec (3) \prec (4) \prec (5)\) Modification: **Collaborative behavior**: If sample is found, drop „crumb trail“ while returning to ship (as guide for other agents (special rocks appear in clusters!). Other agents will weaken trail on way to samples. If sample cluster is empty \(\rightarrow\) no trail reinforcement \(\rightarrow\) trail „dies“. Subsumption Architecture Steels’ Mars Explorer Experiment (3) Modification: Collaborative behavior: - obstacle $\rightarrow$ changeDirection - carryingSamples $\land$ atTheBase $\rightarrow$ dropSamples - carrying Samples $\land$ $\neg$ atTheBase $\rightarrow$ drop_2_Crumbs $\land$ travelUpGradient - detectSample $\rightarrow$ pickUpSample - senseCrumbs $\rightarrow$ PickUp_1_Crumb $\land$ travelDownGradient - TRUE $\rightarrow$ moveRandomly subsumption hierarchy: (1) $\prec$ (2) $\prec$ (3') $\prec$ (4) $\prec$ (6) $\prec$ (5) Subsumption Architecture Pros and Cons (1) • Pro – Simplicity, i.e. modules have high expressiveness – Computational tractability – Robustness against failure, i.e. possibility of modeling redundancies – Overall behavior emerges from interactions • Cons – Behaviors are hard-coded with respect to the environment – Behavior emerges from interactions → How to engineer the system in the general case? – How to model long-term decisions? – How to implemented varying goals? – Design approach does no scale-up for large systems Subsumption Architecture Pros and Cons (2) • In practice, the subsumption architecture is not sufficiently modular: ... Because the upper layers interfere with the internal functions of lower-level behaviors, they cannot be designed independently and become increasingly complex. This also means that even small changes to low-level behaviors or to the vehicle itself cannot be made without redesigning the whole system.... Hartley „Experiments with the Subsumption Architecture“, ICRA 1991 Subsumption Architecture Pros and Cons (3) • Is it here possible using the subsumption architecture for reaching the mother ship? Behavior Networks Introduction • Composed of a set of *competence modules* (*Maes 1989*) • Each module resembles *behaviors* like in the subsumption architecture • Modules are defined – in terms of pre- and post-conditions (similar to STRIPS formalisms) – A real-value *activation level* (giving the relevance within particular situations) • Modules are compiled into a *spreading network* accordingly Behavior Networks Definition - $P$ is a set of propositional atoms generated from the world state - Behavior networks are tuples $(P, G, M, \Pi)$, where - $G \subseteq P$ is the goal specification - $M$ is a finite set of competence modules, where $m \in M$ is a tuple $(\text{pre}, \text{eff}^+, \text{eff}^-, \text{beh})$ with - $\text{pre} \subseteq P$ denoting the preconditions - $\text{eff}^+, \text{eff}^- \subseteq P$ denoting the positive and negative effects (with $\text{eff}^+ \cap \text{eff}^- = \emptyset$) - $\text{beh}$ an executable behavior Behavior Networks Definition • Competence modules are connected in a network; “activation energy” goes from goals to modules • A *positive effect link* connects a positive effect $p$ of a competence module to the precondition $p$ of another competence module • A *negative effect link* connects a negative effect $p$ of one competence module to the precondition $p$ of another competence module. Behavior Networks Activation flow Module activation from situation Activation of module $k$ by satisfied preconditions $\text{pre}_k \cap S^t$, where $M_p$ is the set of modules activated by $p$ and $|\text{pre}_k|$ the number of $k$’s inputs. $$\alpha_{k,e}^t = \phi \sum_{p \in \text{pre}_k \cap S^t} \frac{1}{|M_p| \cdot |\text{pre}_k|}$$ Fan effect Input normalization Module activation from goals Activation by goals $G_t$ satisfying positive effects $\text{eff}^+$ (or suppression from negative effects $\text{eff}^-$ deleting goal propositions $R^t$ that are already active), where $N_e$ is the set of modules generating effect $e$. $$\alpha_{k, gp}^t = \gamma \sum_{e \in \text{eff}^+_t \cap G^t} \frac{1}{|N_e| \cdot |\text{eff}^+_t|}$$ $$\alpha_{k, gn}^t = -\delta \sum_{e \in \text{eff}^-_t \cap R^t} \frac{1}{|N_e| \cdot |\text{eff}^-_t|}$$ Behavior Networks Activation flow Module activation from predecessors Activation of module $k$ from activated modules $E$, where $p$ is input of $k$ and also positive effect of predecessor $l$ $$\alpha_{k,p}^t = \frac{\phi}{\gamma} \sum_{l \in E \setminus \{k\}} \sum_{p \in (pre_k \cap ef_i^+)} S^t M_{p \mid \text{pre}_k} \frac{1}{|pre_k|}$$ Module activation from successors Activation of module $k$ from effect $e$ that satisfy precondition of successor $l$ $$\alpha_{k,s}^t = \sum_{l \in K \setminus \{k\}} \sum_{e \in (ef_i \cap pre_i)} S^t N_{e \mid \text{pre}_k} \frac{\alpha_{k}^{t-1}}{|pre_k|}$$ Overall activation of module $k$: $$\alpha_{k,\Sigma}^t = \alpha_{k,e}^t + \alpha_{k,gp}^t + \alpha_{k,gn}^t + \alpha_{k,p}^t + \alpha_{k,s}^t$$ Behavior Networks Action selection 1. Calculation of activation from goals end situation 2. Computation of inter-module activation 3. Uniform reduction of activation of each module to keep $\Sigma a_k$ constant 4. Select module with highest activation $a_{\text{best}}$ 5. If $a_{\text{best}} > \theta$ then execute behavior 6. If not, reduce $\theta$ by 10%, restart at 1.) Behavior Networks Network example Legend: - Competence module - Proposition - Goal with importance - Negated (right) and non-negated (left) preconditions (bottom) and effects (top) with probability - Conjunction of relevance conditions - Disjunction of relevance conditions Hybrid Architectures Introduction • Neither completely deliberative nor completely reactive approaches are suitable for building agents – Researchers concluded using hybrid systems, which attempt to combine classical and alternative approaches • An obvious approach is to build agents out of two (or more) subsystems: – a deliberative one, containing a symbolic world model, which develops plans and makes decisions in the way proposed by symbolic AI – a reactive one, which is capable of reacting to events without complex reasoning • The combination of reactive and proactive behavior leads to a class of architectures in which the various subsystems are arranged into a hierarchy of interacting layers Hybrid Architectures Types of layers - **Horizontal layering** Layers are each directly connected to the sensory input and action output. In effect, each layer itself acts like an agent, producing suggestions as to what action to perform. - **Vertical layering** Sensory input and action output are each dealt with by at most one layer each (mostly used nowadays) Hybrid Architectures Example Horizontal Layering: “TouringMachines” (1) (Ferguson 1992) Hybrid Architectures Example Horizontal Layering: “TouringMachines” (2) - **Reactive Layer.** Subsumption-Architecture rules, e.g.: rule-1: kerb-avoidance if is-in-front(Kerb, Observer) and speed(Observer) > 0 and separation(Kerb, Observer) < KerbThreshold then change-orientation(KerbAvoidanceAngle) - **Planning Layer.** Long-term behavior, e.g. plans trajectories (paths) to goals - **Modeling layer.** Keeps and modifies environment model; selects new goals for planning layer - **Control subsystem.** Exceeds control (e.g. by suppressing information input to certain layers („censorship“) censor-rule-1: if entity(obstacle-6) in perception-buffer then remove-sensory-record(layer-R, entity(obstacle-6)) Hybrid Architectures Example Vertical Layering: “InteRRaP” - **Bottom-Up-Activation:** If lower level layer is not competent for situation → pass control to higher level - **Top-Down-Execution:** Higher level layers make use of “facilities” provided by lower level layer (Mueller 1995) Case study: CS Freiburg Action Selection Player architecture Case study: CS Freiburg Action Selection Skill example: Dribbling - Consider points on arc around the robot’s location - Compute utility according to - Distance to obstacles (+) - Heading angle difference (-) - Remaining angle to goal (-) - Select best angle Case study: CS Freiburg Action Selection Skill example: Inbound-shot - Consider possible shoot directions with predicted reflections - Compute utility based on - Distance to obstacles (-) - Heading angle difference (-) - Distance to goal at end of line (-) Case study: CS Freiburg Action Selection Some basic skills • The state of the environment, as it is perceived by the agent, is described via a number of continuously valued propositions $p_i \in [0..1]$ • Competence modules are connected with goals if they are able to influence goal conditions and also with each other, if a competence module has an effect that is a precondition of another • Goals are the source of activation. An action is selected by considering each competence module’s executability and received activation • The relevance condition *role active* (player has *active role*) ensures that only one of these goals is relevant at a time depending on the player’s current role Case study: CS Freiburg Action Selection Propositions - Are either binary \( p \in \{ \text{true}, \text{false} \} \) or continuous \( p \in [0..1] \) - Continuous propositions are generated by simple fuzzification - Some examples: - Ball_present \([0,1]\) true ball position is known ```java double StraightUp(double x, double min, double max) { if(max == min) return 0.0; if(x < min) return 0.0; if(x > max) return 1.0; return ((x - min) / (max - min)); } ``` Case study: CS Freiburg Action Selection Propositions - Only non-conflicting goals; depending on role of player (e.g. active/support): - soccergoal - cooperate - Propositions - ball_present $[0,1]$ true ball position is known - ball_near_own_goal as more active as ball is close to goal - ... - Reflex behaviors - Some simple but important functionality can easier be realized by reactive situation-action rules - Robot gets stuck $\rightarrow$ FreeFromStall - 10 seconds rule $\rightarrow$ GoToPos(FieldCenter) - Flexibility vs. Persistent - Persistence is necessary for successful soccer playing! - Achieved by intentionally disallowing undesired action sequences, such as ShootGoal $\rightarrow$ TribbleBall (see network slide) Case Study CS-Freiburg architecture • Network has basically non-conflicting goals – Goal depends on role of player, e.g. support or active – Difference to Dorer: Conflicting goal “have stamina” and “shoot goal” • Reflex behaviors – Situation-Action rules for urgent situations • Robot gets stuck: FreeFromStall • 10 seconds rule: GoToPos(FieldCenter) Case study: CS Freiburg Action Selection The complete network Summary • Logic-based (plan-based) systems can be slow and it is not obvious how to generate symbols from observations • Behavior-based approaches work bottom up, directly coupling observations to behaviors • Subsumption architectures are more reactive and more robust, but hard to engineer and it is not obvious how to scale up • Hybrid architectures combine both approaches – behavior-based for low-level/time-critical activities – logic-based for high-level mission planning Literature • K. Müller **Roboterfußball: Multiagentensystem CS Freiburg, Univ. Freiburg**, 2001 • K. Dorer **Behavior Networks for Continuous Domains using Situation-Dependent Motivations** *Proceedings of the 16th International Joint Conference on Artificial Intelligence (IJCAI'99)*, p. 1233-1238, Morgan Kaufmann, Stockholm www.cs-freiburg.de
{"Source-Url": "http://gki.informatik.uni-freiburg.de/teaching/ws1011/imap/03_FundamentalAgentArchitectures.pdf", "len_cl100k_base": 5565, "olmocr-version": "0.1.53", "pdf-total-pages": 46, "total-fallback-pages": 0, "total-input-tokens": 65991, "total-output-tokens": 7476, "length": "2e12", "weborganizer": {"__label__adult": 0.00041294097900390625, "__label__art_design": 0.000904560089111328, "__label__crime_law": 0.00083160400390625, "__label__education_jobs": 0.0020599365234375, "__label__entertainment": 0.00014340877532958984, "__label__fashion_beauty": 0.00023746490478515625, "__label__finance_business": 0.0004608631134033203, "__label__food_dining": 0.0005121231079101562, "__label__games": 0.0017099380493164062, "__label__hardware": 0.0016431808471679688, "__label__health": 0.0008273124694824219, "__label__history": 0.0005970001220703125, "__label__home_hobbies": 0.00027942657470703125, "__label__industrial": 0.0012912750244140625, "__label__literature": 0.0004649162292480469, "__label__politics": 0.0005617141723632812, "__label__religion": 0.000530242919921875, "__label__science_tech": 0.3251953125, "__label__social_life": 0.00017154216766357422, "__label__software": 0.00911712646484375, "__label__software_dev": 0.6494140625, "__label__sports_fitness": 0.000903606414794922, "__label__transportation": 0.0013751983642578125, "__label__travel": 0.0002562999725341797}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 22139, 0.0093]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 22139, 0.74457]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 22139, 0.81419]], "google_gemma-3-12b-it_contains_pii": [[0, 184, false], [184, 411, null], [411, 1189, null], [1189, 1723, null], [1723, 2417, null], [2417, 2793, null], [2793, 3219, null], [3219, 3889, null], [3889, 4358, null], [4358, 4749, null], [4749, 5819, null], [5819, 6586, null], [6586, 6708, null], [6708, 6940, null], [6940, 7696, null], [7696, 7986, null], [7986, 8383, null], [8383, 8767, null], [8767, 9624, null], [9624, 10529, null], [10529, 11066, null], [11066, 11611, null], [11611, 12109, null], [12109, 12240, null], [12240, 12650, null], [12650, 13227, null], [13227, 13626, null], [13626, 14489, null], [14489, 15246, null], [15246, 15622, null], [15622, 15897, null], [15897, 16609, null], [16609, 16979, null], [16979, 17068, null], [17068, 17832, null], [17832, 18120, null], [18120, 18181, null], [18181, 18447, null], [18447, 18711, null], [18711, 19410, null], [19410, 19919, null], [19919, 20679, null], [20679, 21046, null], [21046, 21108, null], [21108, 21594, null], [21594, 22139, null]], "google_gemma-3-12b-it_is_public_document": [[0, 184, true], [184, 411, null], [411, 1189, null], [1189, 1723, null], [1723, 2417, null], [2417, 2793, null], [2793, 3219, null], [3219, 3889, null], [3889, 4358, null], [4358, 4749, null], [4749, 5819, null], [5819, 6586, null], [6586, 6708, null], [6708, 6940, null], [6940, 7696, null], [7696, 7986, null], [7986, 8383, null], [8383, 8767, null], [8767, 9624, null], [9624, 10529, null], [10529, 11066, null], [11066, 11611, null], [11611, 12109, null], [12109, 12240, null], [12240, 12650, null], [12650, 13227, null], [13227, 13626, null], [13626, 14489, null], [14489, 15246, null], [15246, 15622, null], [15622, 15897, null], [15897, 16609, null], [16609, 16979, null], [16979, 17068, null], [17068, 17832, null], [17832, 18120, null], [18120, 18181, null], [18181, 18447, null], [18447, 18711, null], [18711, 19410, null], [19410, 19919, null], [19919, 20679, null], [20679, 21046, null], [21046, 21108, null], [21108, 21594, null], [21594, 22139, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 22139, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 22139, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 22139, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 22139, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 22139, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 22139, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 22139, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 22139, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 22139, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, true], [5000, 22139, null]], "pdf_page_numbers": [[0, 184, 1], [184, 411, 2], [411, 1189, 3], [1189, 1723, 4], [1723, 2417, 5], [2417, 2793, 6], [2793, 3219, 7], [3219, 3889, 8], [3889, 4358, 9], [4358, 4749, 10], [4749, 5819, 11], [5819, 6586, 12], [6586, 6708, 13], [6708, 6940, 14], [6940, 7696, 15], [7696, 7986, 16], [7986, 8383, 17], [8383, 8767, 18], [8767, 9624, 19], [9624, 10529, 20], [10529, 11066, 21], [11066, 11611, 22], [11611, 12109, 23], [12109, 12240, 24], [12240, 12650, 25], [12650, 13227, 26], [13227, 13626, 27], [13626, 14489, 28], [14489, 15246, 29], [15246, 15622, 30], [15622, 15897, 31], [15897, 16609, 32], [16609, 16979, 33], [16979, 17068, 34], [17068, 17832, 35], [17832, 18120, 36], [18120, 18181, 37], [18181, 18447, 38], [18447, 18711, 39], [18711, 19410, 40], [19410, 19919, 41], [19919, 20679, 42], [20679, 21046, 43], [21046, 21108, 44], [21108, 21594, 45], [21594, 22139, 46]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 22139, 0.0]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
da9f8e63ec0eb672d11ce0ccef0d542cca117809
Models Of Computation for reactive systems • Main MOCs: – Communicating Finite State Machines – Dataflow Process Networks – Petri Nets – Discrete Event – (Abstract) Codesign Finite State Machines • Main languages: – StateCharts – Esterel – Dataflow networks Finite State Machines • Functional decomposition into states of operation • Typical domains of application: – control functions – protocols (telecom, computers, ...) • Different communication mechanisms: – synchronous – (classical FSMs, Moore ‘64, Kurshan ‘90) – asynchronous – (CCS, Milner ‘80; CSP, Hoare ‘85) FSM Example • Informal specification: – If the driver – turns on the key, and – does not fasten the seat belt within 5 seconds – then an alarm beeps – for 5 seconds, or – until the driver fastens the seat belt, or – until the driver turns off the key FSM Example If no condition is satisfied, implicit self-loop in the current state FSM Definition - FSM = (I, O, S, r, δ, λ) - I = {KEY_ON, KEY_OFF, BELT_ON, END_TIMER_5, END_TIMER_10} - O = {START_TIMER, ALARM_ON, ALARM_OFF} - S = {OFF, WAIT, ALARM} - r = OFF δ : 2^I × S → S e.g. δ( {KEY_OFF}, WAIT ) = OFF Set of all subsets of I (implicit “and”) λ : 2^I × S → 2^O set all other inputs are implicitly absent e.g. λ( {KEY_ON}, OFF ) = {START_TIMER} Non-deterministic FSMs - $\delta$ and $\lambda$ may be *relations* instead of *functions*: \[ \delta \subseteq 2^I \times S \times S \] \[ e.g. \quad \delta(\{\text{KEY\_OFF, END\_TIMER\_5}\}, \text{WAIT}) = \{\text{OFF}, \{\text{ALARM}\}\} \] \[ \lambda \subseteq 2^I \times S \times 2^O \] - Non-determinism can be used to describe: - an unspecified behavior (incomplete specification) - an unknown behavior (environment modeling) NDFSM: incomplete specification - E.g. error checking first partially specified: 0 \rightarrow 1 \rightarrow 7 \rightarrow 8 BIT or not BIT => BIT or not BIT => BIT or not BIT => ERR - Then completed as even parity: 0 \rightarrow p1 \rightarrow p7 \rightarrow 8 BIT or not BIT => ERR 0 \rightarrow d1 \rightarrow d7 \rightarrow 8 BIT or not BIT => ERR NDFSM: unknown behavior • Modeling the environment • Useful to: – optimize (don’t care conditions) – verify (exclude impossible cases) • E.g. driver model: \[ \text{s0} \Rightarrow \text{KEY_ON or KEY_OFF or BELT_ON} \] • Can be refined – E.g. introduce timing constraints – (minimum reaction time 0.1 s) NDFSM: time range • Special case of unspecified/unknown behavior, but so common to deserve special treatment for efficiency • E.g. delay between 6 and 10 s NDFSMs and FSMs • Formally FSMs and NDFSMs are equivalent – (Rabin-Scott construction, Rabin ‘59) • In practice, NDFSMs are often more compact – (exponential blowup for determinization) Finite State Machines • Advantages: – Easy to use (graphical languages) – Powerful algorithms for – synthesis (SW and HW) – verification • Disadvantages: – Sometimes over-specify implementation – (sequencing is fully specified) – Number of states can be unmanageable – Numerical computations cannot be specified compactly (need Extended FSMs) Modeling Concurrency • Need to compose parts described by FSMs • Describe the system using a number of FSMs and interconnect them • How do the interconnected FSMs talk to each other? FSM Composition • Bridle complexity via hierarchy: FSM product yields an FSM • Fundamental hypothesis: – all the FSMs change state together (synchronicity) • System state = Cartesian product of component states – (state explosion may be a problem...) • E.g. seat belt control + timer **FSM Composition** - **OFF, 0** - KEY_ON and START_TIMER => START_TIMER - not SEC and (KEY_OFF or BELT_ON) => - not SEC and (KEY_OFF or BELT_ON) => - **WAIT, 1** - SEC and not (KEY_OFF or BELT_ON) => - SEC and (KEY_OFF or BELT_ON) => - **OFF, 1** - SEC and (KEY_OFF or BELT_ON) => - **OFF, 2** - SEC and (KEY_OFF or BELT_ON) => **Diagram Notes** - START_TIMER must be coherent **Boxes** - Timer - Belt Control Given \[ M_1 = (I_1, O_1, S_1, r_1, \delta_1, \lambda_1) \] and \[ M_2 = (I_2, O_2, S_2, r_2, \delta_2, \lambda_2) \] Find the composition \[ M = (I, O, S, r, \delta, \lambda) \] given a set of constraints of the form: \[ C = \{ (o, i_1, \ldots, i_n) : o \text{ is connected to } i_1, \ldots, i_n \} \] FSM Composition - Unconditional product $M' = ( I', O', S', r', \delta', \lambda' )$ - $I' = I_1 \cup I_2$ - $O' = O_1 \cup O_2$ - $S' = S_1 \times S_2$ - $r' = r_1 \times r_2$ $\delta' = \{ ( A_1, A_2, s_1, s_2, t_1, t_2 ) : ( A_1, s_1, t_1 ) \in \delta_1 \quad \text{and} \quad ( A_2, s_2, t_2 ) \in \delta_2 \} $ $\lambda' = \{ ( A_1, A_2, s_1, s_2, B_1, B_2 ) : ( A_1, s_1, B_1 ) \in \lambda_1 \quad \text{and} \quad ( A_2, s_2, B_2 ) \in \lambda_2 \} $ - Note: - $A_1 \subseteq I_1, \ A_2 \subseteq I_2, \ B_1 \subseteq O_1, \ B_2 \subseteq O_2$ - $2^X \cup Y = 2^X \times 2^Y$ FSM Composition • Constraint application \[ \lambda = \{ ( A_1, A_2, s_1, s_2, B_1, B_2 ) \in \lambda' : \text{for all } ( o, i_1, \ldots, i_n ) \in C \quad o \in B_1 \cup B_2 \quad \text{if and only if } \quad i_j \in A_1 \cup A_2 \quad \text{for all } j \} \] • The application of the constraint rules out the cases where the connected input and output have different values (present/absent). FSM Composition \[ I = I_1 \cup I_2 \] \[ O = O_1 \cup O_2 \] \[ S = S_1 \times S_2 \] Assume that \[ o_1 \in O_1, i_3 \in I_2, o_1 = i_3 \text{ (communication)} \] \( \delta \) and \( \lambda \) are such that, e.g., for each pair: \[ \delta_1( \{ i_1 \}, s_1 ) = t_1, \quad \lambda_1( \{ i_1 \}, s_1 ) = \{ o_1 \} \] \[ \delta_2( \{ i_2, i_3 \}, s_2 ) = t_2, \quad \lambda_2( \{ i_2, i_3 \}, s_2 ) = \{ o_2 \} \] we have: \[ \delta( \{ i_1, i_2, i_3 \}, ( s_1, s_2 ) ) = ( t_1, t_2 ) \] \[ \lambda( \{ i_1, i_2, i_3 \}, ( s_1, s_2 ) ) = \{ o_1, o_2 \} \] i.e. \( i_3 \) is in input pattern iff \( o_2 \) is in output pattern • Problem: what if there is a cycle? – Moore machine: \( \delta \) depends on input and state, \( \lambda \) only on state composition is always well-defined – Mealy machine: \( \delta \) and \( \lambda \) depend on input and state composition may be undefined what if \( \lambda_1(\{i_1\}, s_1) = \{o_1\} \) but \( o_2 \not\in \lambda_2(\{i_3\}, s_2) \)? • Causality analysis in Mealy FSMs (Berry ‘98) Moore vs. Mealy - Theoretically, same computational power (almost) - In practice, different characteristics - Moore machines: - non-reactive (response delayed by 1 cycle) - easy to compose (always well-defined) - good for implementation - software is always “slow” - hardware is better when I/O is latched Moore vs. Mealy - Mealy machines: - reactive (0 response time) - hard to compose (problem with combinational cycles) - problematic for implementation - software must be “fast enough” (synchronous hypothesis) - may be needed in hardware, for speed Hierarchical FSM models - Problem: how to reduce the size of the representation? - Harel’s classical papers on StateCharts (language) and bounded concurrency (model): 3 orthogonal exponential reductions - Hierarchy: - state a “encloses” an FSM - being in a means FSM in a is active - states of a are called OR states - used to model pre-emption and exceptions - Concurrency: - two or more FSMs are simultaneously active - states are called AND states - Non-determinism: - used to abstract behavior The vending machine • A machine that sells coffee – Accepts one dollar (d1) bills – Maximum two dollars – Quarters change – Sells two products – Small coffee for $1 – Large coffee for $1.25 The Nokia 3120 User Interface Keypad Events Controller Control software Controller description: Denotational - The controller is denoted by a set of traces of symbols from an alphabet - Non all-capital letters names belong to the alphabet of a process - Capital letters names denote processes (CTRL is the controller process) - A process is a letter followed by a process: P = x → Q - SKIP is a process that successfully completes execution (it does nothing, it just completes the execution) - If P and Q are processes then Z = P ; Q is a process that behaves like P until it completes and then like Q - *P is a finite number of repetition of process P Controller description: Denotational To lock or unlock a Nokia phone press “Menu” followed by the Star key \[ LKUNLK = Menu \rightarrow Star \rightarrow SKIP \] Process Letter of the alphabet Successful Once unlocked, pick something from the menu and perform some action (for instance, choose “Contacts->Find->Alberto) and perform the action “Call” \[ SELECTION = Menu \rightarrow (CHOICE; ACTION) \] Sequential composition \[ CHOICE = (1 \rightarrow SKIP)\|(2 \rightarrow SKIP)\|... \] A complete operation is an unlock followed by a selection followed by a lock \[ OP = LKUNLK; SELECTION; LKUNLK \] A controller is a finite (the phone breaks at some point) sequences of operations \[ CTRL = *OP \] Controller description: Denotational Implicit A tuple is the mathematical object that denotes the controller \[(I, O, S, \delta, \lambda, s_0)\] \[I = (Menu, Star, 1, 2...)\] \[O = (Call, SMS, ...)\] \[S = (Lk, Lk\_Menu, UnLk, MainMenu, Contacts, ...)\] These two functions encode the possible traces \[\delta : 2^I \times S \rightarrow S\] \[\lambda : 2^I \times S \rightarrow O\] Example: To describe the unlock sequence \[\delta(Menu, Lk) = Lk\_Menu\] \[\delta(Star, Lk\_Menu) = UnLk\] Controller Description: Operational An operational description is “explicit” in the sense that it defines: - The meaning of enabled transitions, events etc. - What happens when a transition is enabled - How a state transition is accomplished Composition with synchronization labels The Lock/Unlock FSM The Phone is executing the requested service Event notification An example of service The Select Contacts FSM In service: the phone cannot be locked Coming from The lock/unlock FSM Communication by synchronization Transitions with same synchronization labels must happen “simultaneously” StateCharts: a Language to Capture FSMs • An extension of conventional FSMs • Conventional FSMs are inappropriate for the behavioral description of complex control – flat and unstructured – inherently sequential in nature • StateCharts supports repeated decomposition of states into sub-states in an AND/OR fashion, combined with a synchronous (instantaneous broadcast) communication mechanism State Decomposition - **OR-States** have sub-states that are related to each other by exclusive-or. - **AND-States** have orthogonal state components (synchronous FSM composition) - AND-decomposition can be carried out on any level of states (more convenient than allowing only one level of communicating FSMs). - **Basic States** have no sub-states (bottom of hierarchy). - **Root State** : no parent states (top of hierarchy). To be in state U the system must be either in state S or in state T. To be in state U the system must be both in states S and T. StateCharts Syntax - The general syntax of an expression labeling a transition in a StateChart is \( e[c]/a \), where - \( e \) is the event that triggers the transition - \( c \) is the condition that guards the transition (cannot be taken unless \( c \) is true when \( e \) occurs) - \( a \) is the action that is carried out if and when the transition is taken - For each transition label: - event condition and action are optional - an event can be the changing of a value - standard comparisons are allowed as conditions and assignment statements as actions StateCharts Actions and Events • An action \( a \) on the edge leaving a state may also appear as an event triggering a transition going into an orthogonal state: – a state transition broadcasts an event visible immediately to all other FSMs, that can make transitions immediately and so on – executing the first transition will immediately cause the second transition to be taken \textit{simultaneously} • Actions and events may be associated to the execution of orthogonal components: \( start(A), \ stopped(B) \) Graphical Hierarchical FSM Languages - Multitude of commercial and non-commercial variants: - StateCharts, UML, StateFlow, … - Easy to use for control-dominated systems - Simulation (animated), SW and HW synthesis - Original StateCharts have problems with causality loops and instantaneous events: - circular dependencies can lead to paradoxes - behavior is implementation-dependent - not a truly synchronous language - Hierarchical states necessary for complex reactive system specification Synchronous vs. Asynchronous FSMs - **Synchronous (Esterel, StateCharts):** - communication by shared variables that are read and written in zero time - communication and computation happens instantaneously at discrete time instants - all FSMs make a transition simultaneously (lock-step) - may be difficult to implement - multi-rate specifications - distributed/heterogeneous architectures Synchronous vs. Asynchronous FSMs • A-synchronous FSMs: – free to proceed independently – do not execute a transition at the same time (except for CSP rendezvous) – may need to share notion of time: synchronization – easy to implement Asynchronous communication • Blocking vs. non-Blocking – Blocking read – process can not test for emptiness of input – must wait for input to arrive before proceed – Blocking write – process must wait for successful write before continue – blocking write/blocking read (CSP, CCS) – non-blocking write/blocking read (FIFO, CFSMs, SDL) – non-blocking write/non-blocking read (shared variables) Asynchronous communication • Buffers used to adapt when sender and receiver have different rate – what size? • Lossless vs. lossy – events/tokens may be lost – bounded memory: overflow or overwriting – need to block the sender • Single vs. multiple read – result of each write can be read at most once or several times Communication Mechanisms • Rendez-Vous (CSP) – No space is allocated for the data, processes need to synchronize in some specific points to exchange data – Read and write occur simultaneously • FIFO – Bounded (ECFSMs, CFSMs) – Unbounded (SDL, ACFSMs, Kahn Process Networks, Petri Nets) • Shared memory – Multiple non-destructive reads are possible – Writes delete previously stored data # Communication models <table> <thead> <tr> <th>Model</th> <th>Transmitters</th> <th>Receivers</th> <th>Buffer Size</th> <th>Blocking Reads</th> <th>Blocking Writes</th> <th>Single Reads</th> </tr> </thead> <tbody> <tr> <td>Unsynchronized</td> <td>many</td> <td>many</td> <td>one</td> <td>no</td> <td>no</td> <td>no</td> </tr> <tr> <td>Read-Modify-write</td> <td>many</td> <td>many</td> <td>one</td> <td>yes</td> <td>yes</td> <td>no</td> </tr> <tr> <td>Unbounded FIFO</td> <td>one</td> <td>one</td> <td>unbounded</td> <td>yes</td> <td>no</td> <td>yes</td> </tr> <tr> <td>Bounded FIFO</td> <td>one</td> <td>one</td> <td>bounded</td> <td>no</td> <td>maybe</td> <td>yes</td> </tr> <tr> <td>Single Rendezvous</td> <td>one</td> <td>one</td> <td>one</td> <td>yes</td> <td>yes</td> <td>yes</td> </tr> <tr> <td>Multiple Rendezvous</td> <td>many</td> <td>many</td> <td>one</td> <td>no</td> <td>no</td> <td>yes</td> </tr> </tbody> </table> Outline • Part 3: Models of Computation - FSMs - Discrete Event Systems - CFSMs - Data Flow Models - Petri Nets - The Tagged Signal Model Discrete Event - Explicit notion of time (global order…) - Events can happen at any time asynchronously - As soon as an input appears at a block, it may be executed - The execution may take non zero time, the output is marked with a time that is the sum of the arrival time plus the execution time - Time determines the order with which events are processed - DE simulator maintains a global event queue (Verilog and VHDL) - **Drawbacks** - global event queue => tight coordination between parts - Simultaneous events => non-deterministic behavior - Some simulators use delta delay to prevent non-determinacy Simultaneous Events in DE - **A** → **B** → **C** **Fire B or C?** - **B** has 0 delay - **A** → **B** → **C** - **Fire C once? or twice?** - **B** has delay - **A** → **B** → **C** - **Fire C twice.** Can be refined: - E.g. introduce timing constraints (minimum reaction time 0.1 s) Still have problem with 0-delay (causality) loop Outline • Part 3: Models of Computation - FSMs - Discrete Event Systems - CFSMs - Data Flow Models - Petri Nets - The Tagged Signal Model Co-Design Finite State Machines: Combining FSM and Discrete Event - Synchrony and asynchrony - CFSM definitions - Signals & networks - Timing behavior - Functional behavior - CFSM & process networks - Example of CFSM behaviors - Equivalent classes Codesign Finite State Machine • Underlying MOC of Polis and VCC • Combine aspects from several other MOCs • Preserve formality and efficiency in implementation • Mix – synchronicity – zero and infinite time – asynchronicity – non-zero, finite, and bounded time • Embedded systems often contain both aspects Synchrony: Basic Operation • Synchrony is often implemented with clocks • At clock ticks – Module reads inputs, computes, and produce output – All synchronous events happen simultaneously – Zero-delay computations • Between clock ticks – Infinite amount of time passed Synchrony: Basic Operation (2) - Practical implementation of synchrony - Impossible to get zero or infinite delay - Require: computation time $\ll$ clock period - Computation time $= 0$, w.r.t. reaction time of environment - Features of synchrony - Functional behavior independent of timing - Simplify verification - Cyclic dependencies may cause problem - Among (simultaneous) synchronous events Synchrony: System Solution • System solution – Output reaction to a set of inputs • Well-designed system: – Is completely specified and functional – Has an unique solution at each clock tick – Is equivalent to a single FSM – Allows efficient analysis and verification • Well-designed-ness – May need to be checked for each design (Esterel) – Problematic when cyclic dependency among simultaneous events Synchrony: Implementation Cost - Must verify synchronous assumption on final design - May be expensive - Examples: - Hardware - Clock cycle > maximum computation time - Inefficient for average case - Software - Process must finish computation before - New input arrival - Another process needs to start computation Pure Asynchrony: Basic Operation - Events are never simultaneous - No two events with different labels occur at the same time - Computation starts at a change of the input - Delays are arbitrary, but bounded - Each module is triggered to run at a change of input - No a priori ordering among triggered modules - May be imposed by scheduling at implementation Asynchrony: System Solution • Behavior strongly dependent on input timing • At the implementation level: – Events may “appear” simultaneous – Difficult/expensive to maintain total ordering – Ordering at implementation decides behavior – Becomes DE, with the same pitfalls Asynchrony: Implementation Cost • Achieve low computation time (average) – Different parts of the system compute at different rates • Analysis is difficult – Behavior depends on timing – Maybe be easier for designs that are insensitive to – Internal delay – External timing Asynchrony vs. Synchrony in System Design - They are different at least in terms of - Event buffering - Timing of event read/write - Asynchrony - Explicit buffering of events for each module - Buffer size may be unknown at start-time - Synchrony - One global copy of event - Same start time for all modules Combining Synchrony and Asynchrony • Wants to combine – Flexibility of asynchrony – Verifiability of synchrony • Asynchrony – Globally, a timing independent style of thinking • Synchrony – Local portion of design are often tightly synchronized • Globally asynchronous, locally synchronous – CFSM networks CFSM Overview • CFSM is FSM extended with – Support for data handling – Asynchronous communication • CFSM has – FSM part – Inputs, outputs, states, transition and output relation – Data computation part – External, instantaneous functions CFSM Overview (2) • CFSM has: – Locally synchronous behavior – CFSM executes based on snap-shot input assignment – Synchronous from its own perspective – Globally asynchronous behavior – CFSM executes in non-zero, finite amount of time – Asynchronous from system perspective • GALS model – Globally: Scheduling mechanism – Locally: CFSMs Network of CFSMs: Depth-1 Buffers - Globally Asynchronous, Locally Synchronous (GALS) model Introducing a CFSM • A Finite State Machine • Input events, output events and *state* events • Initial values (for state events) • A transition function → Transitions may involve *complex, memory-less, instantaneous* arithmetic and/or Boolean functions → All the state of the system is under form of events • Need rules that define the CFSM behavior CFSM Rules: phases • Four-phase cycle: ★ Idle ○ Detect input events ▶ Execute one transition □ Emit output events • Discrete time – Sufficiently accurate for synchronous systems – Feasible formal verification • Model semantics: *Timed Traces* i.e. sequences of events labeled by time of occurrence CFSM Rules: phases - Implicit *unbounded delay* between phases - *Non-zero* reaction time (avoid *inconsistencies* when interconnected) - *Causal* model based on *partial order* (*global asynchronicity*) – potential verification speed-up - Phases *may not overlap* - Transitions always *clear input buffers* (*local synchronicity*) Conclusion • CFSM – Delay, and hence detailed behavior, is defined by implementation – Local synchrony – Relatively large atomic synchronous entities – Global asynchrony – Break synchrony, no compositional problem – Allow efficient mapping to heterogeneous architectures
{"Source-Url": "https://ptolemy.berkeley.edu/projects/chess/design/2010/lectures/mocFSM-CFSM.pdf", "len_cl100k_base": 6277, "olmocr-version": "0.1.53", "pdf-total-pages": 66, "total-fallback-pages": 0, "total-input-tokens": 97032, "total-output-tokens": 8646, "length": "2e12", "weborganizer": {"__label__adult": 0.0003888607025146485, "__label__art_design": 0.0005884170532226562, "__label__crime_law": 0.0004448890686035156, "__label__education_jobs": 0.000949382781982422, "__label__entertainment": 8.147954940795898e-05, "__label__fashion_beauty": 0.00018405914306640625, "__label__finance_business": 0.0003314018249511719, "__label__food_dining": 0.0004177093505859375, "__label__games": 0.0007901191711425781, "__label__hardware": 0.003997802734375, "__label__health": 0.0005807876586914062, "__label__history": 0.0003638267517089844, "__label__home_hobbies": 0.00017249584197998047, "__label__industrial": 0.0011835098266601562, "__label__literature": 0.0003142356872558594, "__label__politics": 0.0003862380981445313, "__label__religion": 0.0007290840148925781, "__label__science_tech": 0.155517578125, "__label__social_life": 0.00010216236114501952, "__label__software": 0.00917816162109375, "__label__software_dev": 0.8212890625, "__label__sports_fitness": 0.0003650188446044922, "__label__transportation": 0.0011730194091796875, "__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, 22525, 0.00773]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 22525, 0.57449]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 22525, 0.81172]], "google_gemma-3-12b-it_contains_pii": [[0, 276, false], [276, 605, null], [605, 881, null], [881, 964, null], [964, 1343, null], [1343, 1793, null], [1793, 2175, null], [2175, 2491, null], [2491, 2649, null], [2649, 2840, null], [2840, 3207, null], [3207, 3391, null], [3391, 3680, null], [3680, 4111, null], [4111, 4420, null], [4420, 5034, null], [5034, 5432, null], [5432, 6066, null], [6066, 6493, null], [6493, 6814, null], [6814, 7090, null], [7090, 7606, null], [7606, 7813, null], [7813, 7889, null], [7889, 8471, null], [8471, 9182, null], [9182, 9678, null], [9678, 9922, null], [9922, 10049, null], [10049, 10169, null], [10169, 10277, null], [10277, 10678, null], [10678, 11110, null], [11110, 11179, null], [11179, 11239, null], [11239, 11816, null], [11816, 12344, null], [12344, 12845, null], [12845, 13253, null], [13253, 13497, null], [13497, 13912, null], [13912, 14244, null], [14244, 14646, null], [14646, 15614, null], [15614, 15765, null], [15765, 16382, null], [16382, 16734, null], [16734, 16885, null], [16885, 17142, null], [17142, 17462, null], [17462, 17740, null], [17740, 18157, null], [18157, 18579, null], [18579, 18928, null], [18928, 19292, null], [19292, 19578, null], [19578, 19868, null], [19868, 20194, null], [20194, 20513, null], [20513, 20770, null], [20770, 21134, null], [21134, 21227, null], [21227, 21582, null], [21582, 21895, null], [21895, 22236, null], [22236, 22525, null]], "google_gemma-3-12b-it_is_public_document": [[0, 276, true], [276, 605, null], [605, 881, null], [881, 964, null], [964, 1343, null], [1343, 1793, null], [1793, 2175, null], [2175, 2491, null], [2491, 2649, null], [2649, 2840, null], [2840, 3207, null], [3207, 3391, null], [3391, 3680, null], [3680, 4111, null], [4111, 4420, null], [4420, 5034, null], [5034, 5432, null], [5432, 6066, null], [6066, 6493, null], [6493, 6814, null], [6814, 7090, null], [7090, 7606, null], [7606, 7813, null], [7813, 7889, null], [7889, 8471, null], [8471, 9182, null], [9182, 9678, null], [9678, 9922, null], [9922, 10049, null], [10049, 10169, null], [10169, 10277, null], [10277, 10678, null], [10678, 11110, null], [11110, 11179, null], [11179, 11239, null], [11239, 11816, null], [11816, 12344, null], [12344, 12845, null], [12845, 13253, null], [13253, 13497, null], [13497, 13912, null], [13912, 14244, null], [14244, 14646, null], [14646, 15614, null], [15614, 15765, null], [15765, 16382, null], [16382, 16734, null], [16734, 16885, null], [16885, 17142, null], [17142, 17462, null], [17462, 17740, null], [17740, 18157, null], [18157, 18579, null], [18579, 18928, null], [18928, 19292, null], [19292, 19578, null], [19578, 19868, null], [19868, 20194, null], [20194, 20513, null], [20513, 20770, null], [20770, 21134, null], [21134, 21227, null], [21227, 21582, null], [21582, 21895, null], [21895, 22236, null], [22236, 22525, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 22525, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 22525, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 22525, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 22525, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 22525, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 22525, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 22525, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 22525, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 22525, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 22525, null]], "pdf_page_numbers": [[0, 276, 1], [276, 605, 2], [605, 881, 3], [881, 964, 4], [964, 1343, 5], [1343, 1793, 6], [1793, 2175, 7], [2175, 2491, 8], [2491, 2649, 9], [2649, 2840, 10], [2840, 3207, 11], [3207, 3391, 12], [3391, 3680, 13], [3680, 4111, 14], [4111, 4420, 15], [4420, 5034, 16], [5034, 5432, 17], [5432, 6066, 18], [6066, 6493, 19], [6493, 6814, 20], [6814, 7090, 21], [7090, 7606, 22], [7606, 7813, 23], [7813, 7889, 24], [7889, 8471, 25], [8471, 9182, 26], [9182, 9678, 27], [9678, 9922, 28], [9922, 10049, 29], [10049, 10169, 30], [10169, 10277, 31], [10277, 10678, 32], [10678, 11110, 33], [11110, 11179, 34], [11179, 11239, 35], [11239, 11816, 36], [11816, 12344, 37], [12344, 12845, 38], [12845, 13253, 39], [13253, 13497, 40], [13497, 13912, 41], [13912, 14244, 42], [14244, 14646, 43], [14646, 15614, 44], [15614, 15765, 45], [15765, 16382, 46], [16382, 16734, 47], [16734, 16885, 48], [16885, 17142, 49], [17142, 17462, 50], [17462, 17740, 51], [17740, 18157, 52], [18157, 18579, 53], [18579, 18928, 54], [18928, 19292, 55], [19292, 19578, 56], [19578, 19868, 57], [19868, 20194, 58], [20194, 20513, 59], [20513, 20770, 60], [20770, 21134, 61], [21134, 21227, 62], [21227, 21582, 63], [21582, 21895, 64], [21895, 22236, 65], [22236, 22525, 66]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 22525, 0.01449]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
61bfe09c8c75c7f4820613a3de96a0eabbce3053
1 Motivation Fibonacci Heaps [Fredman and Tarjan, 1987] can be viewed as an extension of Binomial Heaps. In particular, they support the decrease-key operation in $O(1)$ amortized time, while preserving the complexity of all other operations. Table 1 provides a comparative summary of the complexity of each operation supported by Binomial and Fibonacci Heaps. <table> <thead> <tr> <th></th> <th>Binomial Heaps (lazy)</th> <th>Fibonacci Heaps</th> </tr> </thead> <tbody> <tr> <td>MAKE-HEAP</td> <td>$O(1)$</td> <td>$O(1)$</td> </tr> <tr> <td>FIND-MIN</td> <td>$O(1)$</td> <td>$O(1)$</td> </tr> <tr> <td>INSERT</td> <td>$O(1)$</td> <td>$O(1)$</td> </tr> <tr> <td>DELETE-MIN</td> <td>$O(\log n)$</td> <td>$O(\log n)$</td> </tr> <tr> <td>MELD</td> <td>$O(1)$</td> <td>$O(1)$</td> </tr> <tr> <td>DELETE</td> <td>$O(\log n)$</td> <td>$O(\log n)$</td> </tr> <tr> <td>DECREASE-KEY</td> <td>$O(\log n)$</td> <td>$O(1)$</td> </tr> </tbody> </table> Table 1: Amortized complexity of operations in Binomial and Fibonacci Heaps. As seen in the previous lecture, the logarithmic cost of decrease-key in Binomial Heaps is related to the fact that decreasing the key of a node may lead to a violation of the min-heap ordering (unless performed on a root), which is fixed by “bubbling up” the modified node in the heap, until the min-heap ordering is satisfied again. Since the trees have at most logarithmic height, in the worst-case (i.e., when it is necessary to bubble up a leaf up to the root), this operation takes $O(\log n)$ time. Fibonacci Heaps completely avoid this inconvenience, by allowing links to be cut in a controlled way. By supporting the decrease-key operation in $O(1)$ time, Fibonacci Heaps become clearly attractive for all those applications making extensive use of this operation. In particular, historically they allowed an improvement in the runtime of the Dijkstra’s single-source shortest path algorithm, bringing its time complexity down to $O(m + n \log n)$. 2 Overview Fibonacci Heaps are an extension of Binomial Heaps, and share many common points with Binomial Heaps. To start, a Fibonacci Heap is also represented as a linked-list of heap-ordered trees (also known as a forest). Furthermore, like in Binomial Heaps, each node \( v \) in a Fibonacci Heap has associated a value \( \text{RANK}(v) \), representing the number of children of \( v \); the rank of a tree \( T \), \( \text{RANK}(T) \), is equal to the rank of the root of \( T \), and again we only link trees with equal rank. Each node has a pointer to its parent (or nil if the node is a root), and a list of pointers to its children. Finally, a global pointer (the \text{MIN-PTR}) at each instant points to one of trees in the forest containing the minimum element of the collection (such value must be stored at the root, since the trees are all heap-ordered). What sets Fibonacci Heaps apart is the fact that nodes can be unlinked (or cut) away from their parents in amortized constant time. While the operation of cutting trees is not hard to implement \textit{per se}, it is important to consider that it poses a threat to the efficiency of the other operations, especially delete-min. Indeed, after a number of cuts, the forest risks to be composed of scraggly trees with high rank, making the implementation of \text{DELETE-MIN} we saw in the last lecture inefficient. In order to guarantee that the trees in the forest are “bushy”, the cuts need to be done in a controlled way. 3 Cuts As aforementioned, Fibonacci Heaps introduce a new function, called \text{cut}. When \text{cut} is called on the non-root vertex \( v \), the link from \( v \) to its parent gets deleted, splitting the tree. As we will show in a moment, it is possible to implement \text{cut} in constant time. However, let’s first stop to appreciate how a constant-time implementation of \text{cut} allows us to implement \text{DECREASE-KEY}(v, \delta) in constant time. As we recalled earlier, the problem with \text{DECREASE-KEY}(v, \delta) is that when \( v \) is not the root of the tree, a decrement in its value might break the heap order. However, by first running \text{cut}(v), we are guaranteed that \( v \) is the root of a tree in the heap, and changing the value of \( v \) surely does not break the heap order. In order to avoid the potential problem of having extremely sparse trees of high rank, we limit the number of cuts among the children of any vertex to two. The rational behind this choice is that by doing this, we can guarantee that each tree of rank \( k \) has at least \( c^k \) nodes, for a suitable value of \( c \) (reasonably, \( c < 2 \), i.e. we get a slightly worse base for the exponent than vanilla Binomial Heaps). We defer this analysis to Section 4.2. In order to keep track of the number of cut children of a node, we instrument every node \( v \) with a boolean flag \text{MARKED}(v). When \text{MARKED}(v) is \text{FALSE}, no child of \( v \) has been cut; when it is \text{TRUE}, exactly one child has been cut. In order to maintain our invariant, whenever \text{MARKED}(v) is \text{TRUE} and the second child of \( v \) gets cut, \( v \) gets recursively cut as well, and its \text{MARKED} attribute reset. Figure 1 shows a sample forest with only one tree; the numbers inside the nodes represent the values stored in the heap, while gray nodes with bold text represent nodes for which \text{MARKED} is \text{TRUE}. Figure 1: Sample forest with only one tree. The numbers inside the nodes represent the values stored in the heap, while gray nodes with bold text represent nodes for which MARKED is TRUE. Algorithm 1 shows the pseudocode for the algorithm described above, while Figure 2 presents a step-by-step simulation of the effect of cut(19) on the tree of Figure 1. Algorithm 1 Pseudocode for the cut operation. 1: procedure CUT(v) 2: if PARENT(v) \neq \text{NIL} then ▷ v is not the root of the tree 3: \( p \leftarrow \text{PARENT}(v) \) 4: Remove the link from \( p \) to \( v \); add the new tree rooted in \( v \) to the list of trees 5: \text{MARKED}(v) \leftarrow \text{FALSE} 6: \text{RANK}(p) \leftarrow \text{RANK}(p) - 1 7: if \text{MARKED}(p) then ▷ \( p \) had already lost one child 8: \text{CUT}(p) 9: else 10: \text{MARKED}(p) \leftarrow \text{TRUE} 11: end if 12: end if 13: end procedure 3.1 Interplay with the other operations Apart from cut, all the other operations are agnostic to the presence of marks. This implies that they can be mostly borrowed from Binomial Heaps without changes. The only exceptions are: - \text{INSERT}(v), which also needs to initialize \text{MARKED}(v) to \text{FALSE}; - \text{DECREASE-KEY}(v, \delta), which is now re-implemented to execute \text{CUT}(v) before changing the value of the (now) root \( v \). 4 Analysis Most of the (amortized) analysis done for Binomial Heap transfers unchanged to Fibonacci Heaps. In particular, this is true for \text{MAKE-HEAP}, \text{LINK}, \text{CONSOLIDATE}, \text{FIND-MIN}, \text{MELD} and \text{INSERT}. On the The link connecting node 19 to its parent 7 is deleted. Node 7 was marked, so we recursively cut 7 as well. The link connecting node 7 to its parent 5 is deleted. Node 7 is unmarked. Node 5 was marked, so we recursively cut 5 as well. The link connecting node 5 to its parent 4 is deleted. Node 5 is unmarked. Node 4 was not marked, so we mark it and return. The call to \textsc{cut}(19) returns. The heap now contains 4 trees, among which 4 nodes are marked. Figure 2: Step by step simulation of the effect of \textsc{cut}(19) on the tree of Figure 1. contrary, extra care has to be put into the analysis of DELETE-MIN (which heavily depends on having a logarithmic bound on the maximum rank of any tree), DECREASE-KEY (whose implementation differs from Binomial Heaps), and of course the new operation, CUT. 4.1 Analysis of CUT and DECREASE-KEY As discussed previously, the ability of performing CUT operations in (amortized) constant time is what sets Fibonacci Heaps apart, allowing for an efficient implementation of the DECREASE-KEY operation. Here, we prove this amortized bound, using the potential method. Each call to CUT performs a constant amount of work, and potentially cascades, recursively calling CUT on the parent of the node. Let $c$ be the number of calls to CUT (including the first one) needed before stopping. For instance, in the example of Figure 2, $c = 3$ as CUT(19) results in a call to CUT(7) and CUT(5) as well. Consider now the potential function $$\Phi(H) = T(H) + 2M(H), \quad (1)$$ where $T(H)$ and $M(H)$ are respectively the number of trees and of marked nodes in the heap $H$. As an example, the potential function of the heap in the End stage of Figure 2 is given by $\Phi(H) = 4 + 2 \times 4 = 12$. Each cut creates a new tree, provoking a change in potential of $\Delta_n \text{trees} = +c$. Furthermore, each cut, except maybe the first one, clears a marked node, provoking a successive change in potential $\Delta_\text{cleared marks} \leq -2(c - 1)$. Finally, a node might\(^1\) be marked when the recursion stops, provoking a change in potential $\Delta_\text{new mark} \leq +2$. Therefore, the overall change in potential after a call to CUT makes $c - 1$ additional recursive calls is at most $$\Delta \Phi(H) = \Delta_n \text{trees} + \Delta_\text{cleared marks} + \Delta_\text{new mark} \leq c - 2(c - 1) + 2 = -c + 4.$$ The amortized cost per CUT is then $c + 4 - c = O(1)$. Conveniently, this also proves that DECREASE-KEY$(v)$ runs in amortized constant time, as it just consists of a call to CUT$(v)$ and an access to memory to decrease the value of the (now) root $v$. 4.2 Analysis of DELETE-MIN The logarithmic performance of DELETE-MIN (and therefore also DELETE) in Binomial Heaps is directly related to the fact that the maximum rank of any tree in a heap of size $n$ is at most logarithmic in $n$ (equivalently, the number of nodes in a tree is at least exponential in the rank of that tree). Theorem 4.2, the central result for this section, proves that the same property holds for Fibonacci heaps. We begin with a lemma. **Lemma 4.1.** Let $x$ be any vertex, and let $y_1, \ldots, y_m$ be the children of $x$, arranged in the order in which they were linked into $x$. Then $\text{RANK}(y_i) \geq i - 2$. **Proof.** This is a direct consequence of our policy of only linking trees having equal rank. When $y_i$ was linked into $x$, $x$ had already $i - 1$ children. Hence, at that time, $\text{RANK}(y_i) = i - 1$. Since then, $y_i$ might have lost one child, but not two, or otherwise $y_i$ itself would have been cut from the tree. Hence, $\text{RANK}(y_i) \geq i - 2$. \qed \(^1\)It depends on whether the recursion stops before reaching the root or not. Theorem 4.2. Let $T$ be a tree in a Fibonacci Heap. The size of $T$ is exponential in $\text{rank}(T)$. Proof. The conclusion follows easily from Lemma 4.1. Let $S_r$ be a lower bound on the size of any tree having rank $r$. Clearly, $S_0 = 1$, so that we can focus on the case $r \geq 1$. By definition of rank, the root of such a tree $T$ has $r$ children $y_1, \ldots, y_r$. Using Lemma 4.1 on the $y_i$'s, we know that the subtree rooted in $y_i$ has size at least $S_i - 2$ (when $i = 1$, this means that the subtree rooted in $y_1$ has size at least $S_0 = 1$ — i.e. node $y_1$ itself). Therefore, the size $s$ of the tree $T$ is bounded by \[ s \geq 1 + S_0 + \sum_{i=2}^{r} S_{i-2} = 2 + \sum_{i=2}^{r} S_{i-2} = 2 + \sum_{i=0}^{r-2} S_i, \] and hence we can let \[ S_r = 2 + \sum_{i=0}^{r-2} S_i. \tag{2} \] Equation 2 defines a recurrence relation, whose first terms are \[ \begin{align*} S_0 &= 1, \\ S_1 &= 2, \\ S_2 &= 2 + 1 = 3, \\ S_3 &= 2 + 1 + 2 = 5, \\ S_4 &= 2 + 1 + 2 + 3 = 8, \\ & \quad \vdots \end{align*} \] This sequence of integers is known as the “Fibonacci sequence” (hence the name of the data structure). It is immediate to show that Equation 2 can also be rewritten as \[ S_n = S_{n-1} + S_{n-2} \quad \forall n \geq 2, \quad S_0 = 1, S_1 = 2. \] In order to conclude the proof, we show that $S_r = \Omega(c^r)$ for some $c > 1$. For the time being, we prove that by induction, by explicitly providing, “out of the blue”, the constant $c$; see Section 5 for a more insightful proof. Let $\phi$ be the only positive root of the quadratic equation $x^2 = x + 1$; notice that such root is smaller than 2. We prove by induction that $S_r \geq \phi^r$ for all $r$. The base cases are readily checked, as $S_0 = 1 \geq 1$ and $S_1 = 2 \geq \phi$. Now, suppose the claim holds for $r = 1, \ldots, \bar{r} - 1$; we prove that it holds for $\bar{r}$ as well. Indeed, \[ \begin{align*} S_{\bar{r}} &= S_{\bar{r}-1} + S_{\bar{r}-2} \\ &\geq \phi^{\bar{r}-1} + \phi^{\bar{r}-2} \\ &= \phi^{\bar{r}-2}(\phi + 1) = \phi^{\bar{r}}, \end{align*} \] where we used the fact that $\phi + 1 = \phi^2$ by construction. This concludes the proof. Theorem 4.2 immediately implies that in a heap containing $n$ values, the rank of any tree in the forest is $O(\log_\phi n) = O(\log n)$. Therefore, the amortized cost of DELETE-MIN (and hence, also of DELETE) is $O(\log n)$, as claimed. References 5 Appendix: Fibonacci numbers We give an alternative proof of the asymptotics of Fibonacci numbers, whose definition is reported in Equation 3: \[ S_0 = 1, S_1 = 2, \quad S_n = S_{n-1} + S_{n-2} \quad \forall \ n \geq 2. \] \tag{3} Equation 3 can be regarded as a discrete version of a linear ordinary differential equation (ODE) of the second order. Like with higher-order linear ODEs, we can always reduce Equation 3 to first order by increasing the dimension of the space: \[ F_0 = \begin{pmatrix} 2 \\ 1 \end{pmatrix}, \quad F_n = MF_{n-1}, \text{ where } M = \begin{pmatrix} 1 & 1 \\ 1 & 0 \end{pmatrix}, \quad \forall n \geq 1. \] \tag{4} Notice that for all \( n \), \( F_n = (S_{n+1}, S_n)^\top \). We now show how to analytically compute a closed formula for \( F_n \). Notice that we have \[ F_n = M^n F_0. \] Since \( M \) is a symmetric matrix, the spectral theorem guarantees that it is (orthogonally) diagonalizable. In this case we have \[ M = P \Lambda P^{-1} = P \Lambda P^\top, \] where \( P = \frac{1}{\sqrt{\phi^2 + 1}} \begin{pmatrix} \phi & -1 \\ 1 & \phi \end{pmatrix}, \quad \Lambda = \begin{pmatrix} \phi & 0 \\ 0 & -\phi^{-1} \end{pmatrix}, \] and \( \phi \approx 1.618 \) is the only positive eigenvalue of \( M \), i.e. the only positive root of the quadratic equation \( x^2 = x + 1 \). This representation is particularly useful, because it allows us to write \[ M^n = \left( \underbrace{P \Lambda P^\top} \right) \left( \underbrace{P \Lambda P^\top} \right) \cdots \left( \underbrace{P \Lambda P^\top} \right) = P \Lambda^n P^{-1} = P \Lambda^n P^\top. \] However, \( \Lambda \) is a diagonal matrix, and therefore \[ \Lambda^n = \begin{pmatrix} \phi^n & 0 \\ 0 & (-\phi^{-1})^n \end{pmatrix}. \] Wrapping up, we find that \[ F_n = M^n F_0 = P \begin{pmatrix} \phi^n & 0 \\ 0 & (-\phi^{-1})^n \end{pmatrix} P^\top F_0. \] This immediately proves that the terms in \( F_n \) (i.e. the Fibonacci numbers) grow as \( \Theta(\phi^n) \). Besides, it also gives us a closed formula for computing the \( n \)-th Fibonacci number: by expanding the matrix products, we find \[ S_n = \frac{1 + \phi}{\sqrt{5}} \cdot \phi^n - \frac{2 - \phi}{\sqrt{5}} \cdot (-\phi^{-1})^n \approx 1.17 \cdot \phi^n - 0.17 \cdot (-\phi^{-1})^n. \] Notice that, as unlikely as it might look, the expression above evaluates to an integer for all \( n \in \mathbb{N} \).
{"Source-Url": "http://www.cs.cmu.edu/afs/cs/academic/class/15750-s17/ScribeNotes/lecture3.pdf", "len_cl100k_base": 4730, "olmocr-version": "0.1.53", "pdf-total-pages": 7, "total-fallback-pages": 0, "total-input-tokens": 23783, "total-output-tokens": 5147, "length": "2e12", "weborganizer": {"__label__adult": 0.0004906654357910156, "__label__art_design": 0.00038504600524902344, "__label__crime_law": 0.0006284713745117188, "__label__education_jobs": 0.0008392333984375, "__label__entertainment": 0.0001852512359619141, "__label__fashion_beauty": 0.0002570152282714844, "__label__finance_business": 0.0005178451538085938, "__label__food_dining": 0.0007753372192382812, "__label__games": 0.001129150390625, "__label__hardware": 0.0022449493408203125, "__label__health": 0.0020046234130859375, "__label__history": 0.000591278076171875, "__label__home_hobbies": 0.00025725364685058594, "__label__industrial": 0.0010662078857421875, "__label__literature": 0.0005941390991210938, "__label__politics": 0.0004711151123046875, "__label__religion": 0.0009469985961914062, "__label__science_tech": 0.43701171875, "__label__social_life": 0.0001468658447265625, "__label__software": 0.007511138916015625, "__label__software_dev": 0.53955078125, "__label__sports_fitness": 0.0007028579711914062, "__label__transportation": 0.001399993896484375, "__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, 15836, 0.0372]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 15836, 0.63375]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 15836, 0.89069]], "google_gemma-3-12b-it_contains_pii": [[0, 2018, false], [2018, 5472, null], [5472, 7110, null], [7110, 7667, null], [7667, 10847, null], [10847, 13444, null], [13444, 15836, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2018, true], [2018, 5472, null], [5472, 7110, null], [7110, 7667, null], [7667, 10847, null], [10847, 13444, null], [13444, 15836, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 15836, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 15836, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 15836, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 15836, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 15836, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 15836, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 15836, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 15836, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 15836, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 15836, null]], "pdf_page_numbers": [[0, 2018, 1], [2018, 5472, 2], [5472, 7110, 3], [7110, 7667, 4], [7667, 10847, 5], [10847, 13444, 6], [13444, 15836, 7]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 15836, 0.07826]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
4c0d32908ce1873e0a52a149593ac7857f7604ad
Announcements: • HW4 due Saturday • Dataset survey (mandatory) • June 4 – Extra Project Office Hours (optional) Mining Data Streams (Part 1) New Topic: Infinite Data High dim. data - Locality sensitive hashing - Clustering - Dimensionality reduction Graph data - PageRank, SimRank - Community Detection - Spam Detection Infinite data - Sampling data streams - Filtering data streams - Queries on streams Machine learning - Decision Trees - SVM - Parallel SGD Apps - Recommender systems - Association Rules - Duplicate document detection Data Streams - In many data mining situations, we do not know the entire data set in advance. - **Stream Management** is important when the input rate is controlled externally: - Google queries - Twitter or Facebook status updates - We can think of the data as **infinite** and **non-stationary** (the distribution changes over time). - This is the fun part and why interesting algorithms are needed. The Stream Model - **Input elements** enter at a rapid rate, at one or more input ports (i.e., **streams**) - **We call elements of the stream tuples** - The system cannot store the entire stream accessibly - **Q: How do you make critical calculations about the stream using a limited amount of (secondary) memory?** Side note: SGD is a Streaming Alg. - **Stochastic Gradient Descent (SGD) is an example of a stream algorithm** - In Machine Learning we call this: **Online Learning** - Allows for modeling problems where we have a continuous stream of data - We want an algorithm to learn from it and slowly adapt to the changes in data - **Idea: Do small updates to the model** - **SGD** (SVM, Perceptron) makes small updates - **So:** First train the classifier on training data - **Then:** For every example from the stream, we slightly update the model (using small learning rate) Streams Entering. Each stream is composed of elements/tuples. ... 1, 5, 2, 7, 0, 9, 3 ... a, r, v, t, y, h, b ... 0, 0, 1, 0, 1, 1, 0 time General Stream Processing Model Limited Working Storage Ad-Hoc Queries Archival Storage Output Processor Standing Queries Types of queries one wants on answer on a data stream: (we’ll do these today) - Sampling data from a stream - Construct a random sample - Queries over sliding windows - Number of items of type $x$ in the last $k$ elements of the stream Problems on Data Streams - **Types of queries one wants on answer on a data stream:** (we’ll do these on Thu) - Filtering a data stream - Select elements with property $x$ from the stream - Counting distinct elements - Number of distinct elements in the last $k$ elements of the stream - Estimating moments - Estimate avg./std. dev. of elements in stream - Finding frequent elements Applications (1) - **Mining query streams** - Google wants to know what queries are more frequent today than yesterday - **Mining click streams** - Wikipedia wants to know which of its pages are getting an unusual number of hits in the past hour - **Mining social network news feeds** - Look for trending topics on Twitter, Facebook Applications (2) - **Sensor Networks** - Many sensors feeding into a central controller - **Telephone call records** - Data feeds into customer bills as well as settlements between telephone companies - **IP packets monitored at a switch** - Gather information for optimal routing - Detect denial-of-service attacks - **Large-scale machine learning models** - Get summary statistics of data for candidate splits in decision tree model (e.g. Xgboost) Sampling from a Data Stream: Sampling a fixed proportion As the stream grows the sample also gets bigger Sampling from a Data Stream - Since **we can not store the entire stream**, one obvious approach is to store a **sample** - **Two different problems:** - (1) Sample a **fixed proportion** of elements in the stream (say 1 in 10) - (2) Maintain a **random sample of fixed size** over a potentially infinite stream - At any “time” \( k \) we would like a random sample of \( s \) elements - **What is the property of the sample we want to maintain?** For all time steps \( k \), each of \( k \) elements seen so far has equal prob. of being sampled Problem 1: Sampling fixed proportion Scenario: Search engine query stream - Stream of tuples: (user, query, time) - Answer questions such as: How often did a user run the same query in a single day - Have space to store $1/10^{th}$ of query stream Naïve solution: - Generate a random integer in $[0...9]$ for each query - Store the query if the integer is 0, otherwise discard Problem with Naïve Approach - **Simple question:** What fraction of unique queries by an average search engine user are duplicates? - Suppose each user issues \( x \) queries once and \( d \) queries twice (total of \( x + 2d \) query instances) - Correct answer: \( \frac{d}{x+d} \) - Proposed solution: We keep 10% of the queries - Sample will contain \( \frac{x}{10} \) of the singleton queries and \( \frac{2d}{10} \) of the duplicate queries at least once - But only \( \frac{d}{100} \) pairs of duplicates - \( \frac{d}{100} = \frac{1}{10} \cdot \frac{1}{10} \cdot d \) - Of \( d \) “duplicates” \( \frac{18d}{100} \) appear exactly once - \( \frac{18d}{100} = (\frac{1}{10} \cdot \frac{9}{10} + \frac{9}{10} \cdot \frac{1}{10}) \cdot d \) - So the sample-based answer is \( \frac{\frac{d}{100}}{x + \frac{d}{100} + \frac{18d}{100}} = \frac{d}{10x + 19d} \) Solution: Sample Users Solution: - Pick $\frac{1}{10}$th of users and take all their searches in the sample - Use a hash function that hashes the user name or user id uniformly into 10 buckets Generalized Solution - **Stream of tuples with keys:** - Key is some subset of each tuple’s components - e.g., tuple is (user, search, time); key is **user** - Choice of key depends on application - **To get a sample of $a/b$ fraction of the stream:** - Hash each tuple’s key uniformly into $b$ buckets - Pick the tuple if its hash value is at most $a$ Hash table with $b$ buckets, pick the tuple if its hash value is at most $a$. **How to generate a 30% sample?** Hash into $b=10$ buckets, take the tuple if it hashes to one of the first 3 buckets. Sampling from a Data Stream: Sampling a fixed-size sample As the stream grows, the sample is of fixed size Maintaining a fixed-size sample - Problem 2: Fixed-size sample - Suppose we need to maintain a random sample $S$ of size exactly $s$ tuples - E.g., main memory size constraint - **Why?** Don’t know length of stream in advance - Suppose by time $n$ we have seen $n$ items - Each item is in the sample $S$ with equal prob. $s/n$ How to think about the problem: say $s = 2$ Stream: $\{a, x, c, y, z, k, c, d, e, g, \ldots\}$ At $n=5$, each of the first 5 tuples is included in the sample $S$ with equal prob. At $n=7$, each of the first 7 tuples is included in the sample $S$ with equal prob. **Impractical solution would be to store all the $n$ tuples seen so far and out of them pick $s$ at random** Solution: Fixed Size Sample - **Algorithm (a.k.a. Reservoir Sampling)** - Store all the first $s$ elements of the stream to $S$ - Suppose we have seen $n-1$ elements, and now the $n^{th}$ element arrives ($n > s$) - With probability $s/n$, keep the $n^{th}$ element, else discard it - If we picked the $n^{th}$ element, then it replaces one of the $s$ elements in the sample $S$, picked uniformly at random - **Claim:** This algorithm maintains a sample $S$ with the desired property: - After $n$ elements, the sample contains each element seen so far with probability $s/n$ Proof: By Induction - **We prove this by induction:** - Assume that after $n$ elements, the sample contains each element seen so far with probability $s/n$ - We need to show that after seeing element $n+1$ the sample maintains the property - Sample contains each element seen so far with probability $s/(n+1)$ - **Base case:** - After we see $n=s$ elements the sample $S$ has the desired property - Each out of $n=s$ elements is in the sample with probability $s/s = 1$ Proof: By Induction - **Inductive hypothesis:** After \( n \) elements, the sample \( S \) contains each element seen so far with prob. \( s/n \) - **Now element \( n+1 \) arrives** - **Inductive step:** For elements already in \( S \), probability that the algorithm keeps it in \( S \) is: \[ \left( 1 - \frac{s}{n+1} \right) + \left( \frac{s}{n+1} \right) \left( \frac{s-1}{s} \right) = \frac{n}{n+1} \] - Element \( n+1 \) discarded - Element \( n+1 \) not discarded - Element in the sample not picked - So, at time \( n \), tuples in \( S \) were there with prob. \( s/n \) - Time \( n \to n+1 \), tuple stayed in \( S \) with prob. \( n/(n+1) \) - So prob. tuple is in \( S \) at time \( n+1 \) = \( \frac{s}{n} \cdot \frac{n}{n+1} = \frac{s}{n+1} \) Queries over a (long) Sliding Window Sliding Windows - A useful model of stream processing is that queries are about a window of length $N$ – the $N$ most recent elements received - **Interesting case:** $N$ is so large that the data cannot be stored in memory, or even on disk - Or, there are so many streams that windows for all cannot be stored - **Amazon example:** - For every product $X$ we keep 0/1 stream of whether that product was sold in the $n$-th transaction - We want answer queries, how many times have we sold $X$ in the last $k$ sales Sliding Window: 1 Stream - Sliding window on a single stream: \( N = 6 \) \[ \text{Past} \quad \text{Future} \] \[ \text{q w e r t y u i o p a s d f g h j k l z x c v b n m} \] \[ \text{q w e r t y u i o p a s d f g h j k l z x c v b n m} \] \[ \text{q w e r t y u i o p a s d f g h j k l z x c v b n m} \] \[ \text{q w e r t y u i o p a s d f g h j k l z x c v b n m} \] Counting Bits (1) - **Problem:** - Given a stream of 0s and 1s - Be prepared to answer queries of the form **How many 1s are in the last \( k \) bits?** For any \( k \leq N \) - **Obvious solution:** - Store the most recent \( N \) bits - When new bit comes in, discard the \( N+1^{st} \) bit Suppose \( N=6 \): \[ 0 1 0 0 1 1 0 1 1 0 1 0 1 0 1 1 0 \] \( 1 1 0 1 1 0 \) Past Future Counting Bits (2) - You can not get an exact answer without storing the entire window - **Real Problem:** What if we cannot afford to store \( N \) bits? - We’re processing many such streams and for each \( N=1\text{B} \) - But we are happy with an approximate answer An attempt: Simple solution - **Q:** How many 1s are in the last \( N \) bits? - A simple solution that does not really solve our problem: **Uniformity assumption** - **Maintain 2 counters:** - \( S \): number of 1s from the beginning of the stream - \( Z \): number of 0s from the beginning of the stream - **How many 1s are in the last \( N \) bits?** \( N \cdot \frac{S}{S+Z} \) - **But, what if stream is non-uniform?** - What if distribution changes over time? DGIM Method - DGIM solution that does **not** assume uniformity - We store $O(\log^2 N)$ bits per stream - Solution gives approximate answer, never off by more than 50% - Error factor can be reduced to any fraction $> 0$, with more complicated algorithm and proportionally more stored bits - Error: If we have 10 1s then 50% error means 10 +/- 5 Idea: Exponential Windows - Solution that doesn’t (quite) work: - Summarize **exponentially increasing** regions of the stream, looking backward - Drop small regions if they begin at the same point as a larger region We can reconstruct the count of the last $N$ bits, except we are not sure how many of the last 6 1s are included in the $N$ Stores only $O(\log^2 N)$ bits - $O(\log N)$ counts of $\log_2 N$ bits each Easy update as more bits enter Error in count no greater than the number of 1s in the “unknown” area What’s Not So Good? - As long as the 1s are fairly evenly distributed, the error due to the unknown region is small – no more than 50% - But it could be that all the 1s are in the unknown area at the end - In that case, the error is unbounded! Fixup: DGIM method - **Idea:** Instead of summarizing fixed-length blocks, summarize blocks with specific number of 1s: - Let the block *sizes* (number of 1s) increase exponentially - When there are few 1s in the window, block sizes stay small, so errors are small DGIM: Timestamps - Each bit in the stream has a timestamp, starting 1, 2, ... - Record timestamps modulo $N$ (the window size), so we can represent any relevant timestamp in $O(\log_2 N)$ bits DGIM: Buckets - A **bucket** in the DGIM method is a record consisting of: - (A) The timestamp of its end [\(O(\log N)\) bits] - (B) The number of 1s between its beginning and end [\(O(\log \log N)\) bits] - **Constraint on buckets:** Number of 1s must be a power of 2 - That explains the \(O(\log \log N)\) in (B) above Either one or two buckets with the same power-of-2 number of 1s Buckets do not overlap in timestamps Buckets are sorted by size - Earlier buckets are not smaller than later buckets Buckets disappear when their end-time is $> N$ time units in the past Example: Bucketized Stream Three properties of buckets that are maintained: - Either **one** or **two** buckets with the same **power-of-2** number of **1s** - Buckets do not overlap in timestamps - Buckets are sorted by size Updating Buckets (1) - When a new bit comes in, drop the last (oldest) bucket if its end-time is prior to $N$ time units before the current time. - **2 cases:** Current bit is 0 or 1 - **If the current bit is 0:** no other changes are needed Updating Buckets (2) - If the current bit is 1: - (1) Create a new bucket of size 1, for just this bit - End timestamp = current time - (2) If there are now three buckets of size 1, combine the oldest two into a bucket of size 2 - (3) If there are now three buckets of size 2, combine the oldest two into a bucket of size 4 - (4) And so on ... Example: Updating Buckets Current state of the stream: ``` 1001010110001011 0101010101010111 0101010110101000 10110010 ``` Bit of value 1 arrives ``` 0010101100010111 0101010101010111 0101010110101000 10110010 ``` Two orange buckets get merged into a yellow bucket ``` 0010101100010111 0101010101010111 0101010110101000 10110010 ``` Next bit 1 arrives, new orange bucket is created, then 0 comes, then 1: ``` 010110001011 0101010101010111 0101010110101000 10110010 1101 ``` Buckets get merged... ``` 010110001011 0101010101010111 0101010110101000 10110010 1101 ``` State of the buckets after merging ``` 010110001011 01010101010101101001 010101110101001101 ``` How to Query? - To estimate the number of 1s in the most recent $N$ bits: 1. Sum the sizes of all buckets but the last (note “size” means the number of 1s in the bucket) 2. Add half the size of the last bucket - Remember: We do not know how many 1s of the last bucket are still within the wanted window Example: Bucketized Stream At least 1 of size 16. Partially beyond window. Estimate for the number of ones in window of size N is: \[ 1 + 1 + 2 + 4 + 4 + 8 + 8 + 16/2 \] Error Bound: Proof Sketch - Why is error at most 50%? Let’s prove it! - Suppose the last bucket has size $2^r$ - Worst case overestimate: All the 1s in the bucket are outside of window (except rightmost) - we make an error of at most $2^{r-1}$ - Since there is at least one bucket of each of the sizes less than $2^r$, the true sum is at least $1 + 2 + 4 + \ldots + 2^{r-1} = 2^r - 1$ - Thus, error at most 50% At least 16 1s Further Reducing the Error - Instead of maintaining 1 or 2 of each size bucket, we allow either \( r-1 \) or \( r \) buckets (\( r > 2 \)) - Except for the largest size buckets; we can have any number between 1 and \( r \) of those - Error is at most \( O(1/r) \) - By picking \( r \) appropriately, we can tradeoff between number of bits we store and the error Extensions - Can we use the same trick to answer queries **How many 1’s in the last \( k \)?** where \( k < N \)? **A:** Find earliest bucket \( B \) that at overlaps with \( k \). Number of 1s is the sum of sizes of more recent buckets + ½ size of \( B \) - Can we handle the case where the stream is not bits, but integers, and we want the sum of the last \( k \) elements? Extensions - **Stream of positive integers** - **We want the sum of the last** \(k\) **elements** - **Amazon:** Avg. price of last \(k\) sales - **Solution:** - **(1) If you know all have at most** \(m\) **bits** - Treat \(m\) bits of each integer as a separate stream - Use DGIM to count 1s in each integer/stream - The sum is \(\sum_{i=0}^{m-1} c_i 2^i\) - **(2) Use buckets to keep partial sums** - Sum of elements in size \(b\) bucket is at most \(2^b\) \[ \begin{array}{cccccccccccccccc} 2 & 5 & 7 & 1 & 3 & 8 & 4 & 6 & 7 & 9 & 1 & 3 & 7 \\ 2 & 5 & 7 & 1 & 3 & 8 & 4 & 6 & 7 & 9 & 1 & 3 & 7 & 6 & 5 \\ 2 & 5 & 7 & 1 & 3 & 8 & 4 & 6 & 7 & 9 & 1 & 3 & 7 & 6 & 5 \\ 2 & 5 & 7 & 1 & 3 & 8 & 4 & 6 & 7 & 9 & 1 & 3 & 7 & 6 & 5 \\ \end{array} \] \[ \begin{array}{cccccccccccccccc} 6 & 5 & 3 & 5 & 7 & 1 & 3 & 3 & 1 & 2 & 2 & 3 \\ 3 & 5 & 7 & 1 & 3 & 3 & 1 & 2 & 2 & 3 & 3 & 3 \\ 3 & 5 & 7 & 1 & 3 & 3 & 1 & 2 & 2 & 3 & 3 & 3 & 2 & 5 \\ 1 & 6 & 8 & 4 & 2 & 1 \\ \end{array} \] \(c_i\) … estimated count for \(i\)-th bit *Max bucket sum:* 25 *Idea:* Sum in each bucket is at most \(2^b\) (unless bucket has only 1 integer) Summary - Sampling a fixed proportion of a stream - Sample size grows as the stream grows - Sampling a fixed-size sample - Reservoir sampling - Counting the number of 1s in the last N elements - Exponentially increasing windows - Extensions: - Number of 1s in any last k (k < N) elements - Sums of integers in the last N elements Counting Itemsets New Problem: Given a stream, which items appear more than \( s \) times in the window? Possible solution: Think of the stream of baskets as one binary stream per item - 1 = item present; 0 = not present - Use **DGIM** to estimate counts of 1s for all items At least 1 of size 16. Partially beyond window. Extension to Itemsets - In principle, you could count frequent pairs or even larger sets the same way - **One stream per itemset** - **Drawbacks:** - Only approximate - **Number of itemsets is way too big** Exponentially Decaying Windows - Exponentially decaying windows: A heuristic for selecting likely frequent item(s)ets - What are “currently” most popular movies? - Instead of computing the raw count in last $N$ elements - Compute a smooth aggregation over the whole stream - If stream is $a_1, a_2, \ldots$ and we are taking the sum of the stream, take the answer at time $t$ to be: $$ \sum_{i=1}^{t} a_i (1 - c)^{t-i} $$ - $c$ is a constant, presumably tiny, like $10^{-6}$ or $10^{-9}$ - When new $a_{t+1}$ arrives: Multiply current sum by $(1-c)$ and add $a_{t+1}$ Example: Counting Items - If each $a_i$ is an “item” we can compute the characteristic function of each possible item $x$ as an Exponentially Decaying Window - That is: $\sum_{i=1}^{t} \delta_i \cdot (1 - c)^{t-i}$ - where $\delta_i = 1$ if $a_i = x$, and 0 otherwise - Imagine that for each item $x$ we have a binary stream (1 if $x$ appears, 0 if $x$ does not appear) - New item $x$ arrives: - Multiply all counts by $(1-c)$ - Add +1 to count for element $x$ - Call this sum the “weight” of item $x$ Important property: Sum over all weights \( \sum_t (1 - c)^t \) is \( 1/[1 - (1 - c)] = 1/c \) Example: Counting Items - What are “currently” most popular movies? - Suppose we want to find movies of weight > \( \frac{1}{2} \) - Important property: Sum over all weights \( \sum_t (1 - c)^t \) is \( \frac{1}{1 - (1 - c)} = \frac{1}{c} \) - Thus: - There cannot be more than \( \frac{2}{c} \) movies with weight of \( \frac{1}{2} \) or more - So, \( \frac{2}{c} \) is a limit on the number of movies being counted at any time Extension to Itemsets - **Count (some) itemsets in an E.D.W.** - What are currently “hot” itemsets? - **Problem:** Too many itemsets to keep counts of all of them in memory - **When a basket B comes in:** - Multiply all counts by \((1-c)\) - For uncounted items in B, create new count - Add 1 to count of any item in B and to any itemset contained in B that is already being counted - **Drop counts < \(1/2\)** - Initiate new counts (next slide) Initiation of New Counts - Start a count for an itemset $S \subseteq B$ if every proper subset of $S$ had a count prior to arrival of basket $B$ - **Intuitively:** If all subsets of $S$ are being counted this means they are “frequent/hot” and thus $S$ has a potential to be “hot” - **Example:** - Start counting $S=\{i, j\}$ iff both $i$ and $j$ were counted prior to seeing $B$ - Start counting $S=\{i, j, k\}$ iff $\{i, j\}$, $\{i, k\}$, and $\{j, k\}$ were all counted prior to seeing $B$ Counts for single items < \((2/c) \cdot (\text{avg. number of items in a basket})\) Number of larger itemsets is very large But we are conservative about starting counts of large sets - If we counted every set we saw, one basket of 20 items would initiate 1M counts \((2^{20})\)
{"Source-Url": "https://courses.cs.washington.edu/courses/cse547/19sp/slides/15-streams1.pdf", "len_cl100k_base": 6442, "olmocr-version": "0.1.50", "pdf-total-pages": 57, "total-fallback-pages": 0, "total-input-tokens": 88154, "total-output-tokens": 9039, "length": "2e12", "weborganizer": {"__label__adult": 0.0003228187561035156, "__label__art_design": 0.0003969669342041016, "__label__crime_law": 0.0006151199340820312, "__label__education_jobs": 0.0029392242431640625, "__label__entertainment": 0.00010406970977783204, "__label__fashion_beauty": 0.00016939640045166016, "__label__finance_business": 0.0003819465637207031, "__label__food_dining": 0.0004203319549560547, "__label__games": 0.0007948875427246094, "__label__hardware": 0.0018215179443359375, "__label__health": 0.0006365776062011719, "__label__history": 0.0003521442413330078, "__label__home_hobbies": 0.0002417564392089844, "__label__industrial": 0.0007557868957519531, "__label__literature": 0.00039315223693847656, "__label__politics": 0.0003364086151123047, "__label__religion": 0.0005431175231933594, "__label__science_tech": 0.174072265625, "__label__social_life": 0.0001914501190185547, "__label__software": 0.0214080810546875, "__label__software_dev": 0.79248046875, "__label__sports_fitness": 0.0003001689910888672, "__label__transportation": 0.00040221214294433594, "__label__travel": 0.00018477439880371096}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 21439, 0.03303]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 21439, 0.08931]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 21439, 0.84073]], "google_gemma-3-12b-it_contains_pii": [[0, 142, false], [142, 543, null], [543, 951, null], [951, 1273, null], [1273, 1852, null], [1852, 2122, null], [2122, 2363, null], [2363, 2767, null], [2767, 3109, null], [3109, 3573, null], [3573, 3679, null], [3679, 4249, null], [4249, 4630, null], [4630, 5533, null], [5533, 5729, null], [5729, 6295, null], [6295, 6403, null], [6403, 7120, null], [7120, 7711, null], [7711, 8197, null], [8197, 8970, null], [8970, 9007, null], [9007, 9531, null], [9531, 9910, null], [9910, 10311, null], [10311, 10586, null], [10586, 11064, null], [11064, 11419, null], [11419, 11766, null], [11766, 11946, null], [11946, 12191, null], [12191, 12460, null], [12460, 12655, null], [12655, 12986, null], [12986, 13242, null], [13242, 13469, null], [13469, 13714, null], [13714, 14071, null], [14071, 14843, null], [14843, 15157, null], [15157, 15330, null], [15330, 15758, null], [15758, 16122, null], [16122, 16515, null], [16515, 17662, null], [17662, 18009, null], [18009, 18009, null], [18009, 18027, null], [18027, 18335, null], [18335, 18550, null], [18550, 19145, null], [19145, 19666, null], [19666, 19761, null], [19761, 20195, null], [20195, 20658, null], [20658, 21158, null], [21158, 21439, null]], "google_gemma-3-12b-it_is_public_document": [[0, 142, true], [142, 543, null], [543, 951, null], [951, 1273, null], [1273, 1852, null], [1852, 2122, null], [2122, 2363, null], [2363, 2767, null], [2767, 3109, null], [3109, 3573, null], [3573, 3679, null], [3679, 4249, null], [4249, 4630, null], [4630, 5533, null], [5533, 5729, null], [5729, 6295, null], [6295, 6403, null], [6403, 7120, null], [7120, 7711, null], [7711, 8197, null], [8197, 8970, null], [8970, 9007, null], [9007, 9531, null], [9531, 9910, null], [9910, 10311, null], [10311, 10586, null], [10586, 11064, null], [11064, 11419, null], [11419, 11766, null], [11766, 11946, null], [11946, 12191, null], [12191, 12460, null], [12460, 12655, null], [12655, 12986, null], [12986, 13242, null], [13242, 13469, null], [13469, 13714, null], [13714, 14071, null], [14071, 14843, null], [14843, 15157, null], [15157, 15330, null], [15330, 15758, null], [15758, 16122, null], [16122, 16515, null], [16515, 17662, null], [17662, 18009, null], [18009, 18009, null], [18009, 18027, null], [18027, 18335, null], [18335, 18550, null], [18550, 19145, null], [19145, 19666, null], [19666, 19761, null], [19761, 20195, null], [20195, 20658, null], [20658, 21158, null], [21158, 21439, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 21439, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 21439, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 21439, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 21439, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 21439, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 21439, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 21439, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 21439, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 21439, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 21439, null]], "pdf_page_numbers": [[0, 142, 1], [142, 543, 2], [543, 951, 3], [951, 1273, 4], [1273, 1852, 5], [1852, 2122, 6], [2122, 2363, 7], [2363, 2767, 8], [2767, 3109, 9], [3109, 3573, 10], [3573, 3679, 11], [3679, 4249, 12], [4249, 4630, 13], [4630, 5533, 14], [5533, 5729, 15], [5729, 6295, 16], [6295, 6403, 17], [6403, 7120, 18], [7120, 7711, 19], [7711, 8197, 20], [8197, 8970, 21], [8970, 9007, 22], [9007, 9531, 23], [9531, 9910, 24], [9910, 10311, 25], [10311, 10586, 26], [10586, 11064, 27], [11064, 11419, 28], [11419, 11766, 29], [11766, 11946, 30], [11946, 12191, 31], [12191, 12460, 32], [12460, 12655, 33], [12655, 12986, 34], [12986, 13242, 35], [13242, 13469, 36], [13469, 13714, 37], [13714, 14071, 38], [14071, 14843, 39], [14843, 15157, 40], [15157, 15330, 41], [15330, 15758, 42], [15758, 16122, 43], [16122, 16515, 44], [16515, 17662, 45], [17662, 18009, 46], [18009, 18009, 47], [18009, 18027, 48], [18027, 18335, 49], [18335, 18550, 50], [18550, 19145, 51], [19145, 19666, 52], [19666, 19761, 53], [19761, 20195, 54], [20195, 20658, 55], [20658, 21158, 56], [21158, 21439, 57]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 21439, 0.0]]}
olmocr_science_pdfs
2024-12-02
2024-12-02
e797d4c122ca289ee434069058ae6fc53a4cb44b
Department of Operations Research Stanford University Stanford, CA 94305 SOFTWARE FOR OPTIMIZATION, by L. Nazareth TECHNICAL REPORT, SOL 78-32 December 1978 Research and reproduction of this report were partially supported by the Office of Naval Research Contract N00014-75-C-0267; the National Science Foundation Grants MCS76-20019 A01 and ENG77-05/61 A01; and the Department of Energy Contract EY-76-S-03-0326 PA #18. Reproduction in whole or in part is permitted for any purposes of the United States Government. This document has been approved for public release and sale; its distribution is unlimited. Abstract Our aim in this paper is to provide the reader with: - some feel for what quality software entails, - an overview of various aspects of optimization software, - information on solution techniques and available software in the form of a decision tree. - An extensive bibliography so that the reader can further pursue specific topics of interest. We concentrate upon linear programming, non-linear unconstrained optimization and related areas, and non-linear programming. This paper is intended to supplement an earlier oral presentation at the Texas Conference on Mathematical Software entitled "State of Software for Optimization". Acknowledgment My grateful appreciation to Professor G.B. Dantzig and the many others who helped make my visit to the Systems Optimization Laboratory an interesting and valuable learning experience. My thanks also to the Applied Mathematics Division, Argonne National Laboratory, who jointly with the Systems Optimization Laboratory supported my appointment at Stanford. SOFTWARE FOR OPTIMIZATION by L. Nazareth 1. Introduction This paper is intended to supplement an earlier oral presentation on developments in optimization software.* Since very many mathematical problems can be posed in terms of function optimization, and since software for each optimization area ranges from small scale pilot programs to the large scale systems of which commercial LP systems are the most familiar example, we are of necessity selective in our choice of subject matter. We concentrate upon the areas of linear programming, non-linear unconstrained optimization (and the related areas of non-linear least squares and systems of non-linear equations), and non-linear programming. In particular, the very important areas of discrete variable programming and dynamic programming are not covered here. Our aim in this paper is to provide the interested reader with: a) Some feel for what quality software entails. b) An overview of various aspects of optimization software. c) Information on solution techniques and available software for the above areas in the form of a decision tree. d) An extensive bibliography, so that the reader can further pursue specific topics of interest. The paper is organized as follows: Section 2 provides some historical background to the optimization areas covered. Section 3 gives an overview of the software development process, and discusses attributes of 'quality' mathematical software, illustrating these with specific examples. Section 4 deals with software primarily intended to aid algorithm and code development, and discuss the idea of a language for mathematical programming. Section 5 deals with available optimization software for the areas covered here. A detailed decision tree is given. Section 6 discusses the testing of software and the bibliography is given in the final section. We make no claims to being complete, but the author would welcome feedback on important omissions and inaccuracies, particularly with regard to material in Section 5. 2. Background Table 1 is designed to give the reader a time frame for developments in optimization. Some of the important theoretical and algorithmic references are listed along with a few parallel developments in software and computers, and the reader can superimpose his own set of favorite topics. Table 2, adapted from Wolfe [1975b], shows how our ability to solve problems has increased substantially. The vertical axis represents complexity of the problem and the horizontal axes lists different areas of optimization. For further historical details see the survey articles of Dantzig [1977], Orchard-Hays [1977] and Wolfe [1975b]. <table> <thead> <tr> <th>Dates</th> <th>Algorithms &amp; Theory</th> <th>Software</th> <th>Computers</th> </tr> </thead> <tbody> <tr> <td>1935</td> <td>Newton (1727); Fourier (1823); Babbage (1840)</td> <td>EDSAC Library</td> <td>First Generation ENIAC, UNIVAC, EDVAC, ACE, EDSAC</td> </tr> <tr> <td>1940</td> <td>Motzkin (1936)-Inequality Theory; Kantorovitch (1939)-L.P.</td> <td>LP 10 rows (1952)</td> <td>SEAC at N.B.S.</td> </tr> <tr> <td>1945</td> <td>VonNeumann (1944)-Game Theory</td> <td>LP 100 rows (1954)</td> <td>IBM 701</td> </tr> <tr> <td>1950</td> <td>Dantzig (1947)-L.P., Simplex Method</td> <td>LP 256 rows (1956)</td> <td>IBM 704</td> </tr> <tr> <td>1960</td> <td>Gomory (1958)-Integer Programming; Wolfe (1959)-Q.P.</td> <td>LP 90/94-1000 rows</td> <td>Third Generation IBM 360, CDC 6400</td> </tr> <tr> <td>1965</td> <td>Davidson (1959)-Variable Metric</td> <td></td> <td>Parallel Computers</td> </tr> <tr> <td>1975</td> <td>Fiacco &amp; McCormick (1964/6)-Penalty</td> <td>SUMT</td> <td></td> </tr> <tr> <td>1975</td> <td>Han (1975), Powell (1977)-Variable Metric for Constrained Optimization</td> <td>NAG Project, IMSL</td> <td></td> </tr> <tr> <td></td> <td></td> <td>MPSX/370</td> <td></td> </tr> <tr> <td></td> <td></td> <td>NPL Optimization Library</td> <td></td> </tr> <tr> <td></td> <td></td> <td>MINPACK (Argonne)</td> <td></td> </tr> <tr> <td></td> <td></td> <td>MINOS CODE (Murtagh &amp; Saunders (1977))</td> <td></td> </tr> <tr> <td></td> <td></td> <td>NL2SOL (Dennis et al. (1977))</td> <td></td> </tr> </tbody> </table> Table 2 <table> <thead> <tr> <th>Complexity</th> <th>1978</th> <th>1955</th> </tr> </thead> <tbody> <tr> <td>DECOMPOSABLE</td> <td>LP</td> <td>LP</td> </tr> </tbody> </table> U.M. — Unconstrained minimization, QP—Quadratic Programming LC/NLO — Linear constraints, non-linear objective, NLC/NLO—non linear constraints and objectives Complexity — (number of rows + number of variables) ‡ — indicates the figure given is only a rough approximation between the bounds indicated 3. Quality Software 3.1. Overview of Software Development The design of an item of mathematical software depends very much upon the intended use of the software. We wish to stress the distinction between implementations of an algorithm designed primarily for studying the behavior of an algorithm, and implementations designed primarily for solving problems. The former are called algorithm/code oriented versions and the latter user/problem oriented versions. The distinction is, of course, not clear cut, since algorithm/code oriented versions can and should be used to solve practical problems, and user/problem oriented versions can and should be used to study the encoded algorithm. However an implementation will usually place emphasis on one of these two goals; and often an algorithm/code oriented version will be developed as a prelude to a user/problem oriented version. An algorithm/code oriented version should not be construed to mean a hastily thrown together version. Rather it indicates a version in which emphasis is placed upon the goals of flexibility, generality and modifiability, even if this results in a sacrifice of efficiency. In a user/problem oriented version, increasing emphasis is placed upon efficiently solving a wide class of problems and providing a wide range of options. This may call for substantial reformulation and reorganization of the calculations to reduce overhead and circumvent numerical difficulties. We feel that insufficient attention has been paid to developing tools to aid the implementation of algorithm/code oriented versions and this has contributed to the proliferation of untested algorithms which abound in the literature. This will be discussed further in Section 4. In contrast, a number of software aids have been developed to aid the process of tailoring a code to a particular compiler/machine configuration, i.e., to develop portable versions. For further details see Boyle [1976]. Since such aids can be applied to most items of mathematical software and are not specialized to optimization, we shall not discuss them further here. For a more detailed discussion of the process of mathematical software development see Nazareth [1978a]. 3.2. Attributes of Quality Software Both algorithm/code oriented and user/problem oriented software should meet certain standards. What is it that characterizes 'quality' software? Recent efforts to develop good mathematical software, Rice [1971], Smith et al. [1974], Ford and Hague [1974], identify several attributes. We quote these and illustrate them with specific examples. (a) Robustness refers to the ability of a computer program to detect and gracefully recover from abnormal situations without unnecessary interruption of the computer run. In situations when a calculation does fail, the code should fail gracefully. Robustness involves, for example, the filtering out of improper arguments, the avoidance of destructive overflows, and the reorganization of a calculation to minimize the effect of rounding error. Example 2: Cody [1976], Avoiding both destructive overflows and non-destructive underflows in the computation of \( \|x\| = \left( \sum_{i=1}^{n} x_i^2 \right)^{1/2} \). The usual FORTRAN calculation proceeds as follows: ``` SUM = 0.0 DO DO 10 I = 1, N SUM = SUM + X(I)**2 10 CONTINUE XNORM = DSQRT(SUM) ``` SUM can overflow even though XNORM may be a machine representable member. In order to avoid this, the calculation can be done as follows, where we assume for convenience, that the largest element, in absolute value, is \( x(1) \). ``` SUM = 1.0 DO DO 10 I = 2, N A = X(I)/X(1) SUM = SUM + A*A 10 CONTINUE XNORM = DABS(X(I))*DSQRT(SUM) ``` Now $x(I)/x(I)$ can underflow (non-destructively) leading to troublesome interrupt messages. To avoid this the computation can be further reorganized as follows: ``` SUM = 1.0 DO B = DABS(X(I)) DO 10 I = 2, N A = 0.0 DO IF (B + DABS(X(I)) .NE. B) A = X(I)/X(I) SUM = SUM + A*A 10 CONTINUE XNORM = DABS(X(I))*DSQRT(SUM). ``` Example 2: Reorganizing calculation to minimize effect of rounding error. When variable metric methods were first suggested for solving the problem \( \min_{x \in \mathbb{R}^n} f(x) \), the calculation was stated in terms of updating an approximation to the inverse Hessian \( H \) of \( f(x) \). Given a step \( \Delta x \hat{=} x^* - x \) and the associated change of gradient of \( f(x) \), \( \Delta g \hat{=} \Delta f(x^*) - \Delta f(x) \hat{=} g^* - g \), a new approximation \( H^* \) is developed, for example, by the BFGS (see Broyden [1970]) update \[ H^* = H + \frac{1}{\Delta x \Delta g} \left[ \rho \Delta x \Delta x^T - \Delta x \Delta g^T H - H \Delta g \Delta x^T \right] \] (3.1) where \[ \rho \hat{=} 1 + \frac{\Delta g^T H \Delta g}{\Delta x^T \Delta g} \] (3.2) In theory \( H > 0 \) (i.e., positive definite) \( \Rightarrow H^* > 0 \) whenever \( \Delta g^T \Delta x > 0 \). However rounding error in the computation of \( H^* \) can destroy this property. Another difficulty is that even when \( H^* > 0 \) but ill-conditioned, rounding error in computing the next direction of search \( d^* \triangleq -H^* g^* \) can result in \( d^*_c g^*_c > 0 \), where \( d^*_c = -f_l(H^*g^*) \) is the computed search direction. See Gill, Murray and Pitfield [1972]. The above difficulties can be circumvented by reorganizing the calculation following the suggestions of Gill and Murray [1972]. They suggest working with an approximation to the Hessian \( B \) which is maintained in the factored form \( B = LDL^T \), where \( L \) is lower triangu- lar and \( D \) diagonal. In this case we can ensure positive definite- ness by keeping \( D > 0 \). In addition a bound on the condition number of \( B \) can be improved by modifying \( D \). See also the Example 2 under Reliability. (b) **Reliability** refers to the ability of an item of software to perform a calculation both efficiently and accurately and to reflect the basic characteristics of the algorithm e.g., its scale invariances. **Example 1:** Estimating gradients of \( f(x) \) by finite differences. In theory each component \( g_j \) can be estimated by first order finite differences \[ g_j = \frac{[f(x + h e_j) - f(x)]}{h} \tag{3.3} \] where \( h \) is an infinitesimal step. In finite precision arithmetic however this is a difficult computation. A good routine must be designed with considerable care and we state some of the issues which arise in designing such a routine. -- Choice of step length, h. - Should h vary with each component? - Should h be chosen to balance rounding and truncation? In this latter case estimates of second derivatives are needed to estimate truncation error. How are these obtained? Should h be estimated at every iteration or should it be only periodically recomputed in a separate subroutine and held fixed in between calls to this subroutine. -- Should a switch to central differences be made when forward differences are insufficiently accurate? -- Should the increment h be relative to $|x_j|$ or should it be absolute? In the former case $g_j$ is invariant under a simple scaling of variables $x_j + \alpha x_j$, whilst in the latter case $g_j$ is invariant under a translation of variables $x + x + c$. -- Should gradients be estimated in a transformed space of variables? i.e., consider the function $$f(z) = f(x) + g^T(z - x) + \frac{1}{2}(z - x)^T B(z - x)$$ where $B = (JJ^T)^{-1}$ and non-singular. Contours of $f(z)$ are illustrated in Figure 3. If we make the transformation $z = x + Jy$, then $f(z)$ transforms to $\tilde{f}(y)$ $$\tilde{f}(y) = f(x) + k^T y + \frac{1}{2} y^T y$$ where $k = J^T g$. The contours of $\tilde{f}(y)$ are illustrated in Figure 4. $k_i$ are estimated by $$k_i = \frac{f(x + J_i h) - f(x)}{h} - \frac{h}{2}$$ and $g$ is then given by $g = (J^T)^{-1} k$. Figure 3 Figure 4 Example 2: Invariance w.r.t. transformations of variables. It is well known that apart from the initial choice of the approximation, the variable metric algorithm is invariant w.r.t. transformation of the variables. However, if the algorithm is modified to ensure that the search direction \( d_k = -H_k g_k \) satisfies \[ |d_k^T g_k| \geq \varepsilon \|g_k\| \|d_k\|, \] for \( \varepsilon \) a small constant, (3.4) (for example by modifying \( H_k \) suitably), then this destroys scale invariance, since (3.4) is not invariant. For a fuller discussion, see Powell [1976b]. (c) **Structured** refers to whether the program is designed along the principles of good programming, i.e., whether it has a top to bottom flow of control, is formatted to display its structure and so on. See Dahl et al. [1972] and Kerninger and Plauger [1974]. (d) **Usability** refers to the ease with which a user can choose a program and apply it to his problem. For example, how well designed are the calling sequences and documentation. See Gill et al. [1977]. (e) **Validity** refers to the existence of evidence that the software has performed well in a particular computer environment, and to the existence of testing aids which demonstrate that the present installation of software is performing as expected. We discuss testing further in Section 6. (f) **Transportability** refers to whether an item of software can be moved from one computer installation to another without degradation of performance and with minimal change. **Example:** Features of COMMON statement in FORTRAN which can hinder transportability. A very complete discussion of difficulties which arise in transporting FORTRAN programs is given in Smith [1976]. When using the COMMON statement some of the difficulties which arise are: --- -- The order of variables affects portability, e.g., some IBM machines require that variables in a COMMON statement which use two storage units, begin on an even word boundary, else alignment errors or a degradation in efficiency can result. -- Variables in labelled COMMON may become undefined upon execution of a RETURN (or END) statement, unless there is a COMMON statement for that block, in at least one of the higher level program units in the chain of active programs. -- Other inconveniences associated with COMMON are that variable dimensioned entities cannot be used in COMMON, and that the size of a labelled COMMON block may be required to be the same in each program unit in which the COMMON block occurs. 4. Software Designed to aid Algorithm/Code Development Implementing an optimization algorithm is a difficult and a time consuming task. For this reason it is essential that the algorithm or software developer be provided with suitable tools which facilitate his task. We can distinguish three approaches: Approach 1. Develop a high level language, for example along the lines of the Mathematical Programming Language (MPL) of Dantzig et al. [1970]. The aim is to design a language in which highly readable programs can be written and which parallels the venacular of applied mathematics. This would make it possible to write programs quickly and easily and would serve as a means of communicating ideas precisely. In the early creative stages of algorithm development such a language is an invaluable aid since one's intuition can now be supplemented by hard computational results. This can then in turn lead to new ideas. Such a language is also a valuable educational aid. However, once the main features of an algorithm have been laid out, a fundamental difficulty remains, namely that numerically sound procedures are difficult to write in any language, no matter how convenient. What is then needed is a good library of procedures, tailored to optimization, from which an optimization algorithm can be built. This is particularly useful when one wants to test out a new algorithm on real life problems. Building optimization algorithms from a library of procedures also makes for a more uniform comparison of algorithms since their implementations can be made to differ only in the essentials and test results are thus less subject to variations in programming style. It is difficult for a new language to gain wide acceptance and for compilers to be made available on a wide range of machines. Often therefore, we have to fall back upon FORTRAN, although other high level languages, e.g., PL-1 and ALGOL-68 are making some headway. **Approach 2.** Use individual components of a user/problem oriented implementation (or optimization system) which has a modular design. Examples in the area of Linear Programming are discussed in Nazareth [1978]. For examples of such systems in the area of non-linear programming see Muralidharan and Jain [1975], Hillstrom [1976]. The main difficulty with this approach is that one has usually very limited flexibility. Each component in a user/problem oriented system is usually designed within the context of the overall system and often utilizes a common data structure. Using a component on a stand alone basis usually requires that it be substantially modified. **Approach 3.** The idea behind the third approach has already been mentioned. Here one seeks to develop a carefully specified set of modules which can be viewed as being the 'primitives' or 'basic operators' of a language for building optimization algorithms. Two efforts along these lines are discussed in Nazareth [1977] and [1978]. The former describes a pilot system based upon a set of algorithms developed by the author in the area of non-linear unconstrained optimization. Building upon this experience, a software organization and development effort was undertaken in the area of Linear Programming, as described in Nazareth [1978]. It is important to emphasize that the development of a code requires careful craftsmanship and should not be viewed as the mere stringing together of modules. However if such modules are carefully designed and correctly implemented, they can greatly ease the task of implementing an algorithm and perhaps they should be viewed as a way of developing an "artists sketch" of a code, which can then be further refined. They also serve as a valuable means of cooperation and communication between different researchers. Finally they are a useful educational aid. 5. Optimization Software In this section we give a detailed decision tree of the major categories of optimization methods together with references to some recent implementations and/or algorithms in each category. References are given to journal articles or technical reports and implementations are identified by a symbol indicating their source. Available software varies widely in quality and we do not set out here to make any value judgements. Clearly such a compact presentation is also far from complete. Our more modest aim is to provide the reader with some selected information on individual items of software. Other surveys e.g., Dennis [1976], Dixon [1973], Fletcher [1976], Wolfe [1975a], Wright [1978] should also be consulted. 5.1. Some Major Sources of Optimization Software (Alphabetical) [a] Argonne National Laboratory, Applied Mathematics Division([hp]- Hillstrom's Package [1976] and [m]-MINPACK-1). [b] Bell Telephone Laboratory, Murray Hill, New Jersey, (PORT Library). Science and Systems Division, Harwell, England. [ibm] IBM Mathematical Subroutine Library (SL-MATH). [ims] International Mathematical and Statistical Libraries, Inc. [w] Computer Center, University of Wisconsin, Madison. [nber] National Bureau of Economic Research, Cambridge, Massachusetts (now part of M.I.T.). [noc] Numerical Optimization Center, Hatfield College of Technology, Hatfield, Herts., England. [npl] National Physical Laboratory, Division of Numerical Analysis and Computing, Teddington, England. (The NPL Optimization Library is the most comprehensive collection of optimization software currently available.) [s] Computer Science Department, Stanford University. [sol] Systems Optimization Laboratory, Department of Operations Research, Stanford University. The symbol associated with each establishment in the above list is used to identify the establishment in the Decision Tree. Note that software referred to in this manner is not necessarily available for general distribution. Conversely when an algorithm in the Decision Tree does not have a symbol associated with it or when the symbol [au] is used, an implementation may be available from the author(s) of the cited reference. Decision Tree UNCONSTRAINED OPTIMIZATION \[ \min f(x) \quad (1) \] \[ x \in \mathbb{R}^n \] SMALL/MEDIUM \[ f(2) \] DIRECT SEARCH (CONJUGACY BASED (GILL & MURRAY [1972a][np1], DAVIDON & NAZARETH [1977a,b][au]) (VARIABLE METRIC (GILL, MURRAY & PICKEN [1972])(np1), FLETCHER & FREEMAN [1975], MORE & SORENSEN [1977]) (LARGE (MODIFIED NEWTON (GILL & MURRAY [1972a][np1], DAVIDON & NAZARETH [1977a,b][au]) (NON-DIFFERENTIABLE (WOLFE [1974]) (CONJUGATE GRADIENT³ (Powell [1975][h], SHANNO [1977]) (NON-DIFFERENTIABLE (WOLFE [1974]) (Powell [1975][h], Shanno [1977]) (Powell & Toint [1978]) NON-LINEAR LEAST SQUARES \[ \min \sum_{i=1}^{m} [f_i(x)]^2 \] \[ x \in \mathbb{R}^n \] DIRECT SEARCH (SPENDLEY [1969]) (QUASI-NEWTON UPDATES TO JACOBIAN (Powell [1971a][h][hp]) (SMALL RESIDUAL -- GAUSS-NEWTON VARIANTS (Levenberg-Marquardt [1963][m]) (LARGE RESIDUAL (DENNIS ET AL. [1977][nber], GILL & MURRAY [1976b][np1], NAZARETH [1975]) (SEPARABLE (Golub & Porenyra [1973][s]) 20 ## Quadratic Programming \[ \begin{align*} \text{min } & \mathbf{x}^T \mathbf{C} \mathbf{x} + \mathbf{b}^T \mathbf{x} \\ \text{such that } & \mathbf{A} \mathbf{x} = \mathbf{b} \\ & \mathbf{x} \geq 0 \end{align*} \] **Small**: Active Set Strategies **Convex/Indefinite**: Based upon Simplex Method **Large**: Primarily Convex **Based upon Complementarity** *(Fletcher [1970][h], Gill & Murray [1977a][np1]) *(see e.g., Cottle [1977]) *(Tomlin [1976][sol]) ## Linearly Constrained Optimization \[ \begin{align*} \text{min } & f(x) \\ \text{subject to } & \mathbf{A} \mathbf{x} \leq \mathbf{b} \end{align*} \] **Projected/Reduced Gradient/VARIABLE METRIC** **MODIFIED NEWTON** *(Buckley [1975][h], Rosen & Wagner [1975], Gill & Murray [1976a][np1]) *(Gill & Murray [1976a][np1]) *(Murtagh & Saunders [1977][sol]) ## Nonlinear Programming \[ \begin{align*} \text{min } & f(x) \\ \text{subject to } & c(x) \leq 0 \end{align*} \] **Penalty/Barrier** **AUGMENTED LAGRANGIAN** **PROJECTED LAGRANGIAN** **PROJECTED LAGRANGIAN** **PROJECTED LAGRANGIAN** **SMALL/MEDIUM REDUCED GRADIENT** **LARGE REDUCED GRADIENT** *(Fiacco & McCormick [1964], Mylander et al. [1971][au], Lootsma [1970], Rosen & Kreuser [1971][w]) *(Fletcher [1975][h], Gill & Murray [1977b][np1]) *(Rosen [1977][au]) *(Wilson [1963], Murray [1969], Biggs [1972][noc], Han [1975], Powell [1977][au], Murray & Wright [1978]) *(Abadie & Guigou [1969][1971][au], Lasdon et al. [1976][au]) *(Jain, Lasdon & Saunders, see Jain [1976]) Footnotes to Decision Tree 1 A particular case of this problem is that of 1-D optimization, both stand alone and for use within n-dimensional optimization routines. See e.g., Brent [1973a], Gill and Murray [1974]. 2 The symbols f, g, B and J are used to indicate the type of information about the function that is usually required when \[ f \] stands for function value \[ g \] stands for gradient \[ B \] stands for Hessian \[ J \] stands for Jacobian. Thus e.g., \( f/(f,g) \) means function value or (function value and gradient). 3 Currently a very active research area. For an overview see Nazareth and Nocedal [1978]. 4 The distinction between small, medium and large scale is as follows. In small scale L.P. no account is taken of the sparsity of the L.P. matrix, i.e., it is assumed that the matrix is dense and is usually stored as a 2-D array. In medium scale L.P. it is assumed that the L.P. matrix will fit in core provided only non-zeros are stored in packed form, e.g., as a column list/row index data structure. Finally, large scale systems e.g., MPSX/370 make extensive use of secondary storage. 5 For a good overview see Dantzig [1968], Geoffrion [1970]. 6 Terminology of Murray and Wright [1978]. 6. **Testing** Evaluating optimization routines is a difficult task, and one which requires both qualitative and quantitative measures of performance. A fundamental requirement is that the testing environment simulate an actual environment of use since, if it did not, the evaluation would be valid but in all likelihood, irrelevant. Furthermore, the overall quality of a code can only be gauged after investigating a broad range of issues, for example, efficiency, robustness, usability, usefulness of documentation, ability of fail gracefully in the presence of user abuse, rounding error difficulties or violation of underlying assumptions. A testing method usually concentrates on efficiency and robustness, evaluating these by exercising the code on a set of well chosen and hopefully realistic problems. To date the most common method of evaluating optimization routines has become known as 'battery' or 'simulation' testing. Comprehensive studies along these lines are described in Colville [1968], Hillstrom [1977], Himmelblau [1972]. Battery testing has two basic components, namely a set of test problems and a set of measures of performance. The approach is subject to limitations which sometimes make a clear ranking of methods difficult to discern. For example, it is difficult to know how much confidence should be attached to a particular measure of performance when slight variation of starting point or geometry of test problem leads to a substantial variation in the measure of performance. For a discussion of these difficulties see Nazareth and Schlick [1976]. This has motivated the approach which employs "problem families" or "parametrically defined test problems" introduced originally into the evaluation of routines for numerical quadrature by Lyness and Kaganove [1976]. See also Dembo and Mulvey [1976]. A careful a priori experimental design and the use of statistical sampling theory and analysis are implicit in this approach, which is sometimes referred to as 'performance profile' testing to differentiate it from 'battery' testing. A second distinction which it is worth emphasizing is the distinction between algorithm and software evaluation. In particular testing an algorithm usually places most emphasis on efficiency whilst software evaluation attaches a great deal of importance to reliability and robustness. Finally it is worthwhile making a distinction between decentralized and centralized testing of routines. The former is illustrated by the original study of Colville [1968], and the latter is illustrated by the study of Hillstrom [1977]. In decentralized testing a set of software tools are usually made available to developers of routines who then use them to develop information about how well their routines perform. For an example in the area of non-linear programming see Nazareth [1977 where the testing tools comprise: (i) Subroutines which return function and/or gradient information for a set of different test functions. (ii) Subroutines which return starting point and expected solution (if known), for each function. (iii) Report writer whose features include: — Flexible and convenient way of specifying which functions to test. — Replaceable section of code for routine being tested. — Interface subroutines between user form of function call and subroutines in (i) above. — Output summaries and graphical display. Systems Optimization Laboratories (see Dantzig et al. [1973]) are a natural environment for centralized testing, i.e., gathering and testing a number of routines at one particular site. This usually requires a substantial commitment of resources, but it makes for a much more uniform comparison and permits the use of much more stringent test problems, in particular problems arising from real life applications (see Dantzig and Parikh [1977]). Until fairly recently, the development of a testing methodology for optimization routines has been sorely neglected. However, the crucial importance of the subject is now being recognized. For a description of some recent work see Bus [1977], Crowder, Dembo and Mulvey [1977], Nash [1975], More et al. [1978], and consult the minutes of meetings of the Committee on Algorithms of the Mathematical Programming Society. Bibliography 27 Nash, J. (1975), Bibliography of Non-linear Least Squares (microfiche). Powell, M.J.D. (1971a), A.E.R.E., Harwell Library Subroutine, VAO5A. Staha, R.L. and Himmelblau, D.M. (1976), "Evaluation of Constrained Non-linear Programming Techniques," (manuscript), Department of Chemical Engineering, University of Texas, Austin. **SOFTWARE FOR OPTIMIZATION** **AUTHOR(s)** L. Nazareth **PERFORMING ORGANIZATION NAME AND ADDRESS** Department of Operations Research — SOL Stanford University Stanford, CA 94305 **CONTROLLING OFFICE NAME AND ADDRESS** Operations Research Program — ONR Department of the Navy 800 N. Quincy Street, Arlington, VA 22217 **PROJECT OFFICE NAME AND ADDRESS** **REPORT DATE** December 1978 **NUMBER OF PAGES** 36 **DISTRIBUTION STATEMENT (of this Report)** This document has been approved for public release and sale; its distribution is unlimited. **DISTRIBUTION STATEMENT (of the abstract entered in Block 20, if different from Report)** **SUPPLEMENTARY NOTES** **KEYWORDS** Mathematical Software Software Bibliography Unconstrained Optimization **ABSTRACT** See Attached **DECLASSIFICATION/DEGRADING SCHEDULE** Unclassified **AFFECTED SECURITY CLASSIFICATION OF THIS PAGE (When Data Entered)** Unclassified SOL 78-32 SOFTWARE FOR OPTIMIZATION L. Nazareth Our aim in this paper is to provide the reader with: a) Some feel for what quality software entails. b) An overview of various aspects of optimization software. c) Information on solution techniques and available software in the form of a decision tree. d) An extensive bibliography so that the reader can further pursue specific topics of interest. We concentrate upon linear programming, non-linear unconstrained optimization and related areas, and non-linear programming. This paper is intended to supplement an earlier oral presentation at the Texas Conference on Mathematical Software entitled "State of Software for Optimization".
{"Source-Url": "https://apps.dtic.mil/dtic/tr/fulltext/u2/a066343.pdf", "len_cl100k_base": 7982, "olmocr-version": "0.1.50", "pdf-total-pages": 43, "total-fallback-pages": 0, "total-input-tokens": 97437, "total-output-tokens": 16426, "length": "2e12", "weborganizer": {"__label__adult": 0.00036025047302246094, "__label__art_design": 0.0005655288696289062, "__label__crime_law": 0.0004732608795166016, "__label__education_jobs": 0.003889083862304687, "__label__entertainment": 0.00013518333435058594, "__label__fashion_beauty": 0.00023949146270751953, "__label__finance_business": 0.0006394386291503906, "__label__food_dining": 0.0005273818969726562, "__label__games": 0.000965118408203125, "__label__hardware": 0.0010099411010742188, "__label__health": 0.0011348724365234375, "__label__history": 0.0005135536193847656, "__label__home_hobbies": 0.00021266937255859375, "__label__industrial": 0.0008363723754882812, "__label__literature": 0.000453948974609375, "__label__politics": 0.0003802776336669922, "__label__religion": 0.0006265640258789062, "__label__science_tech": 0.293701171875, "__label__social_life": 0.0001951456069946289, "__label__software": 0.0194854736328125, "__label__software_dev": 0.671875, "__label__sports_fitness": 0.0005917549133300781, "__label__transportation": 0.0008273124694824219, "__label__travel": 0.00024068355560302737}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 53220, 0.05124]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 53220, 0.48468]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 53220, 0.85656]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 73, false], [73, 611, null], [611, 1257, null], [1257, 1630, null], [1630, 2745, null], [2745, 3775, null], [3775, 4416, null], [4416, 6221, null], [6221, 6644, null], [6644, 8096, null], [8096, 9439, null], [9439, 10341, null], [10341, 11458, null], [11458, 12943, null], [12943, 14118, null], [14118, 14531, null], [14531, 15876, null], [15876, 17058, null], [17058, 18640, null], [18640, 20209, null], [20209, 20870, null], [20870, 22154, null], [22154, 23190, null], [23190, 24191, null], [24191, 24191, null], [24191, 25708, null], [25708, 26931, null], [26931, 28534, null], [28534, 30017, null], [30017, 31194, null], [31194, 33131, null], [33131, 35249, null], [35249, 37375, null], [37375, 39388, null], [39388, 41273, null], [41273, 43383, null], [43383, 45463, null], [45463, 47401, null], [47401, 49536, null], [49536, 51614, null], [51614, 52532, null], [52532, 53220, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 73, true], [73, 611, null], [611, 1257, null], [1257, 1630, null], [1630, 2745, null], [2745, 3775, null], [3775, 4416, null], [4416, 6221, null], [6221, 6644, null], [6644, 8096, null], [8096, 9439, null], [9439, 10341, null], [10341, 11458, null], [11458, 12943, null], [12943, 14118, null], [14118, 14531, null], [14531, 15876, null], [15876, 17058, null], [17058, 18640, null], [18640, 20209, null], [20209, 20870, null], [20870, 22154, null], [22154, 23190, null], [23190, 24191, null], [24191, 24191, null], [24191, 25708, null], [25708, 26931, null], [26931, 28534, null], [28534, 30017, null], [30017, 31194, null], [31194, 33131, null], [33131, 35249, null], [35249, 37375, null], [37375, 39388, null], [39388, 41273, null], [41273, 43383, null], [43383, 45463, null], [45463, 47401, null], [47401, 49536, null], [49536, 51614, null], [51614, 52532, null], [52532, 53220, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 53220, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 53220, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 53220, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 53220, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 53220, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 53220, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 53220, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 53220, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 53220, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 53220, null]], "pdf_page_numbers": [[0, 0, 1], [0, 73, 2], [73, 611, 3], [611, 1257, 4], [1257, 1630, 5], [1630, 2745, 6], [2745, 3775, 7], [3775, 4416, 8], [4416, 6221, 9], [6221, 6644, 10], [6644, 8096, 11], [8096, 9439, 12], [9439, 10341, 13], [10341, 11458, 14], [11458, 12943, 15], [12943, 14118, 16], [14118, 14531, 17], [14531, 15876, 18], [15876, 17058, 19], [17058, 18640, 20], [18640, 20209, 21], [20209, 20870, 22], [20870, 22154, 23], [22154, 23190, 24], [23190, 24191, 25], [24191, 24191, 26], [24191, 25708, 27], [25708, 26931, 28], [26931, 28534, 29], [28534, 30017, 30], [30017, 31194, 31], [31194, 33131, 32], [33131, 35249, 33], [35249, 37375, 34], [37375, 39388, 35], [39388, 41273, 36], [41273, 43383, 37], [43383, 45463, 38], [45463, 47401, 39], [47401, 49536, 40], [49536, 51614, 41], [51614, 52532, 42], [52532, 53220, 43]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 53220, 0.044]]}
olmocr_science_pdfs
2024-12-02
2024-12-02
1d03885fbfcbb0df59f1d9b4b4cef87132dc6add
Please read through the entire examination first! We designed this exam so that it can be completed in 100 minutes and, hopefully, this estimate will prove to be reasonable. There are 7 problems worth a total of 100 points. The point value of each problem is indicated in the table below. Write your answer neatly in the spaces provided. If you need more space (you shouldn't), you can write on the back of the sheet where the question is posed, but please make sure that you indicate clearly the problem to which the comments apply. Do NOT use any other paper to hand in your answers. If you have difficulty with part of a problem, move on to the next one. They are mostly independent of each other. The exam is CLOSED book and CLOSED notes. Please do not ask or provide anything to anyone else in the class during the exam. Make sure to ask clarification questions early so that both you and the others may benefit as much as possible from the answers. <table> <thead> <tr> <th>Problem</th> <th>Max Score</th> <th>Score</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>12</td> <td></td> </tr> <tr> <td>2</td> <td>10</td> <td></td> </tr> <tr> <td>3</td> <td>10</td> <td></td> </tr> <tr> <td>4</td> <td>12</td> <td></td> </tr> <tr> <td>5</td> <td>24</td> <td></td> </tr> <tr> <td>6</td> <td>20</td> <td></td> </tr> <tr> <td>7</td> <td>12</td> <td></td> </tr> <tr> <td>TOTAL</td> <td>100</td> <td></td> </tr> </tbody> </table> 1. Caches (12 points) When images are printed on paper four different inks are used to generate colors: cyan, magenta, yellow, and black (CMYK). Software that deals with color printing needs to be able to represent images as arrays of these colors. For this problem we would like to determine the efficiency of the following code on a machine with a 2048-byte direct-mapped data cache with 32-byte blocks. We are given the following data definitions: ```c struct point_color { int c; int m; int y; int k; }; struct point_color grid[16][16]; int i, j; ``` Assume the following: - `sizeof(int) == 4` - `grid` begins at memory address 0 - The cache is initially empty - The only memory accesses are to the entries of array `grid`. Variables `i` and `j` are stored in registers What is the cache hit ratio when the following code is executed? ```c for (i = 0; i < 16; i++) { for (j = 0; j < 16; j++) { grid[i][j].c = 0; grid[i][j].m = 0; grid[i][j].y = 0; grid[i][j].k = 0; } } ``` Include enough details so we can follow your calculations. Please try to simplify your answers, but it’s ok if you need to save time by leaving some of them as fractions. Write Your Answer On the Next Page… 1. Caches (cont.) Write your answer here. (This is problem 6.39 from the textbook) Each cache block holds 2 16-byte point_color structs The array is $16 \times 16 \times 16 = 4096$ bytes. The cache holds half of that. Since we are scanning in row-major order, each miss (for a grid[i][j].c int value) is followed by 7 hits (the rest of that struct and the entire following one). The hit ratio, then, is $7/8 = 87.5\%$. 2. Caches and Programming (10 points) Three programmers are debating how best to write the code to transpose a matrix in a C software package that will run on a variety of different machines. The exact details of the different computers aren’t known. What is known is that all of them have caches and virtual memory. The matrix is much too large to fit entirely in the caches, but it is small enough to fit in main memory, so virtual memory paging is not an issue. The array is a normal C array of doubles stored in row-major order. Alice says that this code will do the best overall job: ``` for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { temp = A[i][j]; A[i][j] = A[j][i]; A[j][i] = temp; } } ``` Bob says that this is all wrong and that the performance will be much better if it’s written this way: ``` for (j = 0; j < N; j++) { for (i = 0; i < N; i++) { temp = A[i][j]; A[i][j] = A[j][i]; A[j][i] = temp; } } ``` Chris says it doesn’t matter. The code will perform about the same either way. Who’s right and why? Give a brief technical justification for your answer. Chris is right – the order doesn’t matter. Each iteration of either inner loop references both A[i][j] and A[j][i], so there is one group of references going through the array sequentially and another that is jumping by a complete row at a time. Both sets of nested loops will have essentially the same reference pattern and cache behavior. 3. Disk Performance (10 points) The Round Number Disk Manufacturing Company specializes in manufacturing disks designed to produce simple calculations on CSE exams. Their CSE351 Special has the following performance characteristics: - Rotational speed: 6000 rpm (100 revolutions per second) - Average seek time: 5 ms. - Number of sectors (data blocks) per track: 1000 - Sector size: 500 bytes The disk has only two surfaces on a single platter. Tracks on both surfaces can be accessed without moving the head once it is in position after a seek. Recall that the time needed to read data from a disk is the time needed to position the head over the first block (average rotational latency and seek time) plus the time for the data to move under the head once it is positioned. a) What is the best expected time in milliseconds (ms) needed to read 1,000,000 bytes from the disk, assuming that the data is organized sequentially on the disk with the best possible mapping of logical blocks to disk sectors. If the blocks are ordered sequentially, it takes 1 seek and 1 rotational latency to access the first block, followed by two complete rotations of the disk to transfer all the data. Total time is \[ 5 \text{ ms seek } + 5 \text{ ms latency } + 2 \times 10 \text{ ms/rotation} = 30 \text{ ms}. \] b) What is the expected time in milliseconds (ms) needed to read the same 1,000,000 bytes from the disk if the data blocks are scattered randomly on the disk? We still need 20 ms. to transfer all the data, even though the data is scattered over the disk. The difference this time is that we potentially have a seek + latency delay to access each individual block. We need to read 2,000 blocks. The total time is: \[ 2000 \times (5 \text{ ms seek } + 5 \text{ ms latency}) + 20 \text{ ms transfer} \] \[ = 2000 \times 10 \text{ ms} + 20 \text{ ms} \] \[ = 20.02 \text{ sec.} \] (Quite a bit worse than sequential transfer.) 4. Linking and Relocation (12 points) Here is the code and relocation information for a small function named f. Lines have been numbered for reference below: 1) 00000000 <f>: 2) 0: 55 push %ebp 3) 1: 89 e5 mov %esp,%ebp 4) 3: 83 ec 10 sub $0x10,%esp 5) 6: a1 0c 00 00 00 mov 0xc,%eax 6) 7: R_386_32 stuff 7) b: a3 00 00 00 00 mov %eax,0x0 8) c: R_386_32 data 9) 10: c7 45 f8 fc ff ff ff movl $0xfffffffc, -0x8(%ebp) 10) 13: R_386_32 stuff 11) 17: b8 11 00 00 00 mov $0x11,%eax 12) 1c: c9 leave 13) 1d: c3 ret When this code is loaded, the linker assigned the following absolute addresses for the external symbols in the .code and .data sections of the program, and loads the bytes of function f starting at the address given here (0x08048394): f 0x08048394 stuff 0x08049634 data 0x08049648 The above code contains three relocated references. For each relocated reference, give the line number in the above code of the instruction that is being relocated, the runtime memory address of the relocated data, and the relocated value stored at that address. <table> <thead> <tr> <th>Line #</th> <th>Relocated Data Address</th> <th>Relocated Data Value</th> </tr> </thead> <tbody> <tr> <td>5</td> <td>0x0804839b</td> <td>0x08049640</td> </tr> <tr> <td>7</td> <td>0x080483a0</td> <td>0x08049648</td> </tr> <tr> <td>9</td> <td>0x080483a7</td> <td>0x08049630</td> </tr> </tbody> </table> 5. Virtual Memory (24 points) Our system implements virtual memory with a translation look-aside buffer (TLB – 16 entries, 4-way set associative), page table (PT – 1024 page entries, only the first 16 shown below), and memory cache (16 entries, 4-byte lines, direct-mapped). The initial contents are shown in the tables below. The virtual address is 16 bits (4 hex digits) while the physical address is 12 bits (3 hex digits); the page size is 64 bytes. (You can remove this page for reference while answering the rest of this question.) a) (2 points) Outline the bits corresponding to each of the components of the virtual address, namely, the virtual page number (VPN), the virtual page offset (VPO), the TLB set index (TLBI), and the TLB tag value (TLBT). \[ \begin{array}{cccccccccc} \text{VPN} & \text{VPO} & \text{TLB Tag} & \text{TLBI} \\ \hline 15 & 14 & 13 & 12 & 11 & 10 & 9 & 8 & 7 & 6 & 5 & 4 & 3 & 2 & 1 & 0 \end{array} \] b) (2 points) Outline the bits corresponding to each of the components of the physical address, namely, the physical page number (PPN), the physical page offset (PPO), the cache set index (CI), the cache tag value (CT), and the cache byte offset (CO). \[ \begin{array}{cccccccccc} \text{CT} & \text{CI} & \text{CO} & \text{PPN} & \text{PPO} \\ \hline 11 & 10 & 9 & 8 & 7 & 6 & 5 & 4 & 3 & 2 & 1 & 0 \end{array} \] c) (12 points) Determine the returned values for the following sequence of accesses and specify whether a TLB miss, page fault, and/or cache miss occurred. In some cases, it may not be possible to determine what value is accessed or whether there is a cache miss or not. For these cases, simply write ND (for Not Determinable). If it matters, assume the accesses occur in this sequence and each access updates the tables as needed. <table> <thead> <tr> <th>Virtual Address</th> <th>Physical Address</th> <th>Value</th> <th>TLB Miss?</th> <th>Page Fault?</th> <th>Cache Miss?</th> </tr> </thead> <tbody> <tr> <td>0x01B9</td> <td>ND</td> <td>ND</td> <td>Y</td> <td>Y</td> <td>ND</td> </tr> <tr> <td>0x0363</td> <td>0xb63</td> <td>ND</td> <td>N</td> <td>N</td> <td>Y</td> </tr> <tr> <td>0x0353</td> <td>0xb53</td> <td>ND</td> <td>N</td> <td>N</td> <td>Y</td> </tr> <tr> <td>0x072B</td> <td>0x0AB</td> <td>ND</td> <td>N</td> <td>N</td> <td>Y</td> </tr> </tbody> </table> 8 of 13 d) (5 points) One of our customers is running the following code snippet to initialize every entry in a byte array to 0x00: ```c char array[32][32]; for (int i = 0; i < 32; i++){ for (int j = 0; j < 32; j++){ array[j][i] = 0; } } ``` How many TLB misses occur when this code runs on our system? (You should assume this code is executed on a cold system with an initially empty cache and empty TLB.) 16 initial misses. After that, all pages in the active set are in the cache. e) (3 points) Bernie Bitkiller, the summer intern, suggested that it would be better if we used the virtual address bits differently to access the TLB. His idea is that the TLBI (TLB Index) bits should be the high-order bits of the virtual address starting at bit 15, then the TLBT (TLB Tag) bits next, and the VPO (virtual page offset) bits in the lower-order part of the address ending with bit 0. Basically he wants to interchange the positions of the TLBI and TLBT bits. Suppose we execute code that has many sequential reads from memory. How will this design perform for those programs? What will the TLB hit/miss ratios be like and why? There is an initial cold miss, then every subsequent read in the block is a hit – only the offset bits will be changing. The TLB hit ratio will be close to 1. (Note: this is actually a little unexpected, since using the high-order bits for the index often leads to bad behaviors in caches. In this particular case it turns out not to be a problem.) 6. Memory Management (20 points) One of our customers has an unusual request for an addition to our memory manager code. They would like to have the following function added: ```c void * max_alloc(size_t * size_found) ``` - max_alloc() locates the largest single block on the free list and allocates it to the caller. It is similar to malloc, except that the caller does not specify the size requested; instead the largest available free block is allocated. - If the free list is empty when max_alloc() is called, it returns null as the function result and does not use the pointer parameter size_found. - Otherwise, if there is at least one block on the free list, max_alloc finds the largest such block, removes it from the free list, and returns a pointer to the payload part of the block as the function result. It also stores the payload size in bytes in the variable referenced by the pointer size_found. (i.e., this function has two outputs – a pointer to the allocated block and the size of the block. The pointer is the value returned by the function; the size is stored in the memory location referenced by the parameter.) - If two or more blocks on the free list have the maximum size, the function removes only one of them from the free list and allocates it. (i.e., you may break ties any way you wish) Write C-like pseudo-code for this function, using the explicit free list from lab 7. Be sure to adhere to the specification above. Your pseudo-code should be close to C (with comments as needed), but don’t worry about syntax details if you don’t remember them exactly. Here is the relevant code from our explicit free list implementation for reference. You may call any of the functions below. You may also remove this page and the next one from the exam if you wish. Write your answer on the page after that. ```c /* Alignment of blocks returned by mm_malloc. */ #define ALIGNMENT 8 /* Size of a word on this architecture. */ #define WORD_SIZE sizeof(void*) /* Pointer to the first BlockInfo in the free list, the list's head. You can treat this as a BlockInfo*. */ #define FREE_LIST_HEAD *((BlockInfo **)mem_heap_lo()) /* Minimum implementation-internal block size (to account for size header, next ptr, prev ptr, and boundary tag). This is NOT the minimum size of an object that may be returned to the caller of mm_malloc. */ #define MIN_BLOCK_SIZE 4*WORD_SIZE ``` /* Macros for pointer arithmetic to keep other code cleaner. Casting to a char* has the effect that pointer arithmetic happens at the byte granularity (i.e. POINTER_ADD(0x1, 1) would be 0x2). (By default, incrementing a pointer in C has the effect of incrementing it by the size of the type to which it points (e.g. BlockInfo).) */ #define POINTER_ADD(p,x) ((char*)(p) + (x)) #define POINTER_SUB(p,x) ((char*)(p) - (x)) /* A BlockInfo contains information about a block, including the size and usage tags, as well as pointers to the next and previous blocks in the free list. Note that the next and prev pointers are only needed when the block is free. To achieve better utilization, mm_malloc would use the space for next and prev as part of the space it returns. */ +-------------+-----------------------------+ | sizeAndTags | <- BlockInfo pointers in free list point here +-------------+-----------------------------+ | next | <- Pointers returned by mm_malloc point here +-------------+-----------------------------+ | prev | +-------------+ | space | | ... | */ struct BlockInfo { /* Size of the block (log(ALIGNMENT) high bits) and tags for whether the block and its predecessor in memory are in use. */ int sizeAndTags; // Pointer to the next block in the free list. struct BlockInfo* next; // Pointer to the previous block in the free list. struct BlockInfo* prev; }; typedef struct BlockInfo BlockInfo; /* SIZE(x) selects just the higher bits of x to ensure that it is properly aligned. Additionally, the low bits of the sizeAndTags member are used to tag a block as free/used, etc. */ #define SIZE(x) ((x) & ~(ALIGNMENT - 1)) /* TAG_USED bit mask used in sizeAndTags to mark a block as used. */ #define TAG_USED 1 /* TAG_PRECEDING_USED is the bit mask used in sizeAndTags to indicate that the block preceding it in memory is used. (used in turn for coalescing) */ #define TAG_PRECEDING_USED 2 void insertFreeBlock(BlockInfo* freeBlock); void removeFreeBlock(BlockInfo* freeBlock); void coalesceFreeBlock(BlockInfo* oldBlock); void * mm_malloc (size_t size); void mm_free (void *ptr); 6. Memory Management (cont) Implement max_alloc below ```c void * max_alloc(size_t * size_found) { // PLACE YOUR CODE HERE BlockInfo * current = FREE_LIST_HEAD; if (current == NULL) return NULL; BlockInfo * maxBlock; // locn. and size of largest block int max = 0; while (current != NULL) { int size = SIZE(current->sizeAndTags); if (size > max) { max = size; maxBlock = block; } } removeFreeBlock(maxBlock); *size_found = max - WORD_SIZE; return (void *)POINTER_ADD(maxBlock, WORD_SIZE); } ``` Notes: Many solutions called mm_alloc with the max size after searching the free list. That “works” so we didn’t deduct points for it, but it is not a good solution since it searches the free list a second time. We didn’t worry about 8-byte alignment in the solutions as long as they correctly managed the difference between pointers and sizes of blocks vs. pointers and sizes of the payload area. 7. Processes and Concurrency (12 points) Suppose we have the following program: ```c int main() { printf(“0”); if (fork() != 0) { printf(“1”); fork(); printf(“2”); } else { printf(“3”); } exit(0); } ``` List all of the possible outputs that can occur when this program is run. If it helps, feel free to draw a graph showing the various processes that are created. The original process prints 0 – 1 – 2 and the second child process prints 2 either before or after the original process prints 2. So those two processes always produce the output sequence 0 – 1 – 2 – 2. The first child process prints 3. That can happen any time after the first process prints 0. So the possible output sequences are ``` 0 3 1 2 2 0 1 3 2 2 0 1 2 3 2 0 1 2 2 3 ```
{"Source-Url": "http://courses.cs.washington.edu/courses/cse351/11au/past-exams/cse351-10au-final-solution.pdf", "len_cl100k_base": 4964, "olmocr-version": "0.1.50", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 27586, "total-output-tokens": 5584, "length": "2e12", "weborganizer": {"__label__adult": 0.0005207061767578125, "__label__art_design": 0.00034689903259277344, "__label__crime_law": 0.0004100799560546875, "__label__education_jobs": 0.005767822265625, "__label__entertainment": 9.5367431640625e-05, "__label__fashion_beauty": 0.0002218484878540039, "__label__finance_business": 0.0002236366271972656, "__label__food_dining": 0.0007219314575195312, "__label__games": 0.0012187957763671875, "__label__hardware": 0.002529144287109375, "__label__health": 0.0005421638488769531, "__label__history": 0.0003528594970703125, "__label__home_hobbies": 0.00021529197692871096, "__label__industrial": 0.0007920265197753906, "__label__literature": 0.00033354759216308594, "__label__politics": 0.00029587745666503906, "__label__religion": 0.0006589889526367188, "__label__science_tech": 0.0157470703125, "__label__social_life": 0.00018203258514404297, "__label__software": 0.00371551513671875, "__label__software_dev": 0.96337890625, "__label__sports_fitness": 0.0004792213439941406, "__label__transportation": 0.001018524169921875, "__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, 17914, 0.05706]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 17914, 0.31312]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 17914, 0.86168]], "google_gemma-3-12b-it_contains_pii": [[0, 1278, false], [1278, 2530, null], [2530, 2956, null], [2956, 4445, null], [4445, 6380, null], [6380, 7775, null], [7775, 8315, null], [8315, 10090, null], [10090, 11581, null], [11581, 13974, null], [13974, 16113, null], [16113, 17112, null], [17112, 17914, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1278, true], [1278, 2530, null], [2530, 2956, null], [2956, 4445, null], [4445, 6380, null], [6380, 7775, null], [7775, 8315, null], [8315, 10090, null], [10090, 11581, null], [11581, 13974, null], [13974, 16113, null], [16113, 17112, null], [17112, 17914, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 17914, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 17914, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 17914, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 17914, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 17914, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 17914, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 17914, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 17914, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, true], [5000, 17914, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 17914, null]], "pdf_page_numbers": [[0, 1278, 1], [1278, 2530, 2], [2530, 2956, 3], [2956, 4445, 4], [4445, 6380, 5], [6380, 7775, 6], [7775, 8315, 7], [8315, 10090, 8], [10090, 11581, 9], [11581, 13974, 10], [13974, 16113, 11], [16113, 17112, 12], [17112, 17914, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 17914, 0.09023]]}
olmocr_science_pdfs
2024-11-30
2024-11-30
df6f4405aec683a339f15343fec1dbb084bde11d
Lecture #14 Query Planning & Optimization **ADMINISTRIVIA** **Mid-Term Exam** - Grades have been posted to S3 - See the Profs. during OH for exam viewing - Next week, you can post a regrade request on Gradescope **Project #2** - Due: **Oct 29th @ 11:59pm** - Special OH: **Oct 28th from 3-5pm in GHC 4303** **Project #3** - Due: **Nov 12th @ 11:59pm** SELECT distinct ename FROM Emp E, Dept D WHERE E.did = D.did AND D.dname = 'Toy' **Catalog** <table> <thead> <tr> <th>EMP (ssn, ename, addr, sal, did)</th> <th>clustered nonclustered nonclustered</th> </tr> </thead> <tbody> <tr> <td>10,000 records</td> <td>1,000 pages</td> </tr> </tbody> </table> <table> <thead> <tr> <th>DEPT (did, dname, floor, mgr)</th> <th>clustered nonclustered</th> </tr> </thead> <tbody> <tr> <td>500 records</td> <td>50 pages</td> </tr> </tbody> </table> **Total: 2M I/Os** - 4 reads, 1 write - 2,000 + 4 writes - (10K/500 = 20 emps per dept) - 1,000,000 + 2,000 writes - (FK join, 10K tuples in temp T2) - 50 + 50,000 + 1,000,000 writes - (write to temp file T1) - 5 tuples per page in T1 **Query** \[ \pi_{ename} \left( \sigma_{dname = 'Toy'} \left( \sigma_{EMP.did = DEPT.did} (\pi_{ename} (SELECT * FROM Emp E) \times \sigma_{dname = 'Toy'} (SELECT * FROM Dept D)) \right) \right) \] SELECT distinct ename FROM Emp E, Dept D WHERE E.did = D.did AND D.dname = 'Toy' Query Total: 54K I/Os Read temp T2 4 reads + 1 writes Read temp T1 2,000 reads + 4 writes Page NL, write to temp T1 50 + 50,000 + 2000 writes Catalog <table> <thead> <tr> <th>EMP (ssn, ename, addr, sal, did)</th> </tr> </thead> <tbody> <tr> <td>clustered</td> </tr> <tr> <td>▲</td> </tr> <tr> <td>10,000 records</td> </tr> </tbody> </table> <table> <thead> <tr> <th>DEPT (did, dname, floor, mgr)</th> </tr> </thead> <tbody> <tr> <td>clustered</td> </tr> <tr> <td>▲</td> </tr> <tr> <td>500 records</td> </tr> </tbody> </table> \( \pi_{\text{ename}} \) \( \sigma_{\text{dname} = 'Toy'} \) \( \bowtie \) \( \text{EMP}.\text{did} = \text{DEPT}.\text{did} \) SELECT distinct ename FROM Emp E, Dept D WHERE E.did = D.did AND D.dname = 'Toy' Catalog <table> <thead> <tr> <th></th> <th>clustered</th> <th>nonclustered</th> <th>nonclustered</th> </tr> </thead> <tbody> <tr> <td>EMP</td> <td>▲</td> <td>▲</td> <td>▲</td> </tr> <tr> <td>DEPT</td> <td>▲</td> <td>▲</td> <td></td> </tr> </tbody> </table> EMP (ssn, ename, addr, sal, did) 10,000 records 1,000 pages DEPT (did, dname, floor, mgr) 500 records 50 pages Query w/ Materialization Total: 7,159 I/Os w/ Pipelining Total: 3,151 I/Os Read temp T2 4 reads + 1 writes Read temp T1 2,000 reads + 4 writes Sort-merge join (50 buffers) 3*(|Emp|+|Dept|) = 3150 + 2000 writes \[ \begin{align*} \pi_{ename} \\ \sigma_{dname = 'Toy'} \\ \bowtie_{EMP.did = DEPT.did} \\ \end{align*} \] EMP DEPT SELECT distinct ename FROM Emp E, Dept D WHERE E.did = D.did AND D.dname = ‘Toy’ Catalog <table> <thead> <tr> <th>EMP (ssn, ename, addr, sal, did)</th> <th>clustered</th> <th>nonclustered</th> <th>nonclustered</th> </tr> </thead> <tbody> <tr> <td>10,000 records</td> <td>1,000 pages</td> <td></td> <td></td> </tr> </tbody> </table> <table> <thead> <tr> <th>DEPT (did, dname, floor, mgr)</th> <th>clustered</th> <th>nonclustered</th> <th>nonclustered</th> </tr> </thead> <tbody> <tr> <td>500 records</td> <td>50 pages</td> <td></td> <td></td> </tr> </tbody> </table> Total: 37 I/Os Access: Index (name) Read temp T1, NL-IDX Join 1 + 3 (idx) + 20 (ptr chase) + 4 writes Read temp T2 4 reads + 1 writes Πename σdname = ‘Toy’ Annotated RA Tree a.k.a. The Physical Plan Simple projection Estimates: output cardinality = 20, ... \[ \pi_{ename} \] Pipeline EMP did = DEPT did NL-IDX using unclustered index on EMP.id Estimates: output cardinality = 20, ... Access Path: Un-clustered B-tree Estimates: output cardinality = 1, ... \[ \sigma_{dname = 'Toy'} \] DEPT Access Path: File Scan Estimates: output cardinality = 10K To the scheduler to run the query Query Optimization (QO) 1. Identify candidate equivalent trees (logical). It is an NP-hard problem, so the space is large. 2. For each candidate, find the execution plan tree (physical). We need to estimate the cost of each plan. 3. Choose the best overall (physical) plan. Practically: Choose from a subset of all possible plans. LOGICAL VS. PHYSICAL PLANS The optimizer generates a mapping of a **logical** algebra expression to the optimal equivalent physical algebra expression. **Physical** operators define a specific execution strategy using an access path. → They can depend on the physical format of the data that they process (i.e., sorting, compression). → Not always a 1:1 mapping from logical to physical. QUERY OPTIMIZATION Heuristics / Rules → Rewrite the query to remove (guessed) inefficiencies; e.g., always do selections first, or push down projections as early as possible. → These techniques may need to examine catalog, but they do not need to examine data. Cost-based Search → Use a model to estimate the cost of executing a plan. → Enumerate multiple equivalent plans for a query and pick the one with the lowest cost. Predicate Pushdown \[ \pi_{\text{ename}} \] \[ \sigma_{\text{dname} = 'Toy'} \] \[ \pi_{\text{ename}} \left( \sigma_{\text{dname} = 'Toy'} \left( \text{DEPT} \bowtie \text{EMP} \right) \right) \] \[ \pi_{\text{ename}} \left( \text{EMP} \bowtie \sigma_{\text{dname} = 'Toy'} \left( \text{DEPT} \right) \right) \] Replace Cartesian Product \[ \sigma_{\text{EMP}.\text{did} = \text{DEPT}.\text{did}} \] \[ \text{EMP} \times \text{DEPT} \] \[ \sigma_{\text{DEPT}.\text{did} = \text{EMP}.\text{did}} \left( \text{DEPT} \times \text{EMP} \right) \] \[ \text{EMP} \bowtie \text{DEPT} \] \[ \text{EMP} \times \text{DEPT} \] \[ \sigma_{\text{EMP}.\text{did} = \text{DEPT}.\text{did}} \] \[ \text{EMP} \bowtie \text{DEPT} \] Projection Pushdown \[ \pi_{\text{ename}}(\ldots \bowtie \text{did} \ EMP) \] \[ \pi_{\text{ename}} \] \[ \pi_{\text{ename, did}} \] \[ \pi_{\text{EMP, did}}(\pi_{\text{ename, did}} \ EMP) \] Equivalence \[ \sigma_{P_1} (\sigma_{P_2}(R)) \equiv \sigma_{P_2} (\sigma_{P_1}(R)) \] (\(\sigma\) commutativity) \[ \sigma_{P_1 \land P_2 \ldots \land P_n}(R) \equiv \sigma_{P_1}(\sigma_{P_2}(\ldots \sigma_{P_n}(R))) \] (cascading \(\sigma\)) \[ \Pi_{a_1}(R) \equiv \Pi_{a_1}(\Pi_{a_2}(\ldots \Pi_{a_k}(R)\ldots)), \ a_i \subseteq a_{i+1} \] (cascading \(\Pi\)) \[ R \bowtie S \equiv S \bowtie R \] (join commutativity) \[ R \bowtie (S \bowtie T) \equiv (R \bowtie S) \bowtie T \] (join associativity) \[ \sigma_P(R \times S) \equiv (R \bowtie_P S), \text{ if } P \text{ is a join predicate} \] \[ \sigma_P(R \times S) \equiv \sigma_{P_1}(\sigma_{P_2}(R) \bowtie_{P_4} \sigma_{P_3}(S)), \text{ where } P = p_1 \land p_2 \land p_3 \land p_4 \] \[ \Pi_{A_1,A_2,\ldots A_n}(\sigma_P(R)) \equiv \Pi_{A_1,A_2,\ldots A_n}(\sigma_P(\Pi_{A_1,\ldots A_n,B_1,\ldots B_M}R)), \text{ where } B_1 \ldots B_M \text{ are columns in } P \] ... ARCHITECTURE OVERVIEW 1. SQL Query 2. Abstract Syntax Tree 3. Logical Plan 4. Physical Plan Parser → Binder → Optimizer Application → Schema Info → Cost Model Estimates System Catalog Name→Internal ID QUERY OPTIMIZATION Heuristics / Rules → Rewrite the query to remove inefficient patterns. → These techniques may need to examine catalog, but they do not need to examine data. Cost-based Search → Use a model to estimate the cost of executing a plan. → Enumerate multiple equivalent plans for a query and pick the one with the lowest cost. Examples: predicate pushdown, replace cartesian product, projection pushdown … COST-BASED QUERY OPTIMIZATION Let’s start with a certain style of QO: cost-based, bottom-up QO (the classic System-R optimizer approach) Approach: Enumerate different plans for the query and estimate their costs. → Single relation. → Multiple relations. → Nested sub-queries. It chooses the best plan it has seen for the query after exhausting all plans or some timeout. SINGLE-RELATION QUERY PLANNING Pick the best access method. → Sequential Scan → Binary Search (clustered indexes) → Index Scan Predicate evaluation ordering. Simple heuristics are often good enough for this. SYSTEM R OPTIMIZER Break the query into blocks and generate the logical operators for each block. For each logical operator, generate a set of physical operators that implement it. → All combinations of join algorithms and access paths Then, iteratively construct a “left-deep” join tree that minimizes the estimated amount of work to execute the plan. **SYSTEM R OPTIMIZER** --- **SELECT** ARTIST.NAME **FROM** ARTIST, APPEARS, ALBUM **WHERE** ARTIST.ID=APPEARS.ARTIST_ID AND APPEARS.ALBUM_ID=ALBUM.ID AND ALBUM.NAME="Andy's OG Remix" **ORDER BY** ARTIST.ID **ARTIST**: Sequential Scan **APPEARS**: Sequential Scan **ALBUM**: Index Look-up on NAME --- **Step #1**: Choose the best access paths to each table **Step #2**: Enumerate all possible join orderings for tables **Step #3**: Determine the join ordering with the lowest cost The query has `ORDER BY` on `ARTIST.ID` but the plans do not carry an explicit notion of the sorting properties. MULTI-RELATION QUERY PLANNING We just saw an example of this, the System R approach Choice #1: Bottom-up Optimization → Start with nothing and then build up the plan to get to the outcome that you want. Choice #2: Top-down Optimization → Start with the outcome that you want, and then work down the tree to find the optimal plan that gets you to that goal. BOTTOM-UP OPTIMIZATION Use static rules to perform initial optimization. Then use dynamic programming to determine the best join order for tables using a divide-and-conquer search method. Examples: IBM System R, DB2, MySQL, Postgres, most open-source DBMSs. TOP-DOWN OPTIMIZATION Start with a logical plan of what we want the query to be. Perform a branch-and-bound search to traverse the plan tree by converting logical operators into physical operators. → Keep track of global best plan during search. → Treat physical properties of data as first-class entities during planning. Example: MSSQL, Greenplum, CockroachDB Invoke rules to create new nodes and traverse the tree. → *Logical*→*Logical*: JOIN(A,B) to JOIN(B,A) → *Logical*→*Physical*: JOIN(A,B) to HASH_JOIN(A,B) Can create “enforcer” rules that require input to have certain properties. Life so far ... single block QO Often, we get nested queries. → We could optimize each block using the methods we have discussed. → However, this may be inefficient since we optimize each block separately without a global approach. What if we could flatten a nested query into a single block and optimize it? → Then, apply single-block query optimization methods. → Even if one can’t flatten to a single block, flattening to fewer blocks is still beneficial. NESTED SUB-QUERIES The DBMS treats nested sub-queries in the where clause as functions that take parameters and return a single value or set of values. Two Approaches: → Rewrite to de-correlate and/or flatten them. → Decompose nested query and store results in a temporary table. NESTED SUB-QUERIES: REWRITE ```sql SELECT name FROM sailors AS S WHERE EXISTS ( SELECT * FROM reserves AS R WHERE S.sid = R.sid AND R.day = '2022-10-25' ) | SELECT name FROM sailors AS S, reserves AS R WHERE S.sid = R.sid AND R.day = '2022-10-25' ``` DECOMPOSING QUERIES For harder queries, the optimizer breaks up queries into blocks and then concentrates on one block at a time. Sub-queries are written to temporary tables that are discarded after the query finishes. DECOMPOSING QUERIES SELECT MAX(rating) FROM sailors SELECT S.sid, MIN(R.day) FROM sailors S, reserves R, boats B WHERE S.sid = R.sid AND R.bid = B.bid AND B.color = 'red' AND S.rating = *** GROUP BY S.sid HAVING COUNT(*) > 1 Outer Block Nested Block **EXPRESSION REWRITING** An optimizer transforms a query’s expressions (e.g., *WHERE/ON* clause predicates) into the minimal set of expressions. Implemented using if/then/else clauses or a pattern-matching rule engine. → Search for expressions that match a pattern. → When a match is found, rewrite the expression. → Halt if there are no more rules that match. EXPRESSION REWRITING Impossible / Unnecessary Predicates ``` SELECT * FROM A WHERE false; SELECT * FROM A WHERE false; SELECT * FROM A WHERE RANDOM() IS NULL; ``` Merging Predicates ``` SELECT * FROM A WHERE val BETWEEN 1 AND 150; OR val BETWEEN 50 AND 150; ``` How do we calculate the cost of the plans? We have formulas for the operator algorithms (e.g. the cost formulae for hash join, sort merge join, ...), but we also need to estimate the size of the output that an operator produces. COST ESTIMATION The DBMS uses a cost model to predict the behavior of a query plan given a database state. → This is an internal cost that allows the DBMS to compare one plan with another. It is too expensive to run every possible plan to determine this information, so the DBMS need a way to derive this information. COST MODEL COMPONENTS Choice #1: Physical Costs → Predict CPU cycles, I/O, cache misses, RAM consumption, network messages… → Depends heavily on hardware. Choice #2: Logical Costs → Estimate output size per operator. → Independent of the operator algorithm. → Need estimations for operator result sizes. POSTGRES COST MODEL Uses a combination of CPU and I/O costs that are weighted by “magic” constant factors. Default settings are obviously for a disk-resident database without a lot of memory: → Processing a tuple in memory is $400\times$ faster than reading a tuple from disk. → Sequential I/O is $4\times$ faster than random I/O. 19.7.2. Planner Cost Constants The cost variables described in this section are measured on an arbitrary scale. Only their relative values matter, hence scaling them all up or down by the same factor will result in no change in the planner's choices. By default, these cost variables are based on the cost of sequential page fetches; that is, seq_page_cost is conventionally set to 1.0 and the other cost variables are set with reference to that. But you can use a different scale if you prefer, such as actual execution times in milliseconds on a particular machine. Note: Unfortunately, there is no well-defined method for determining ideal values for the cost variables. They are best treated as averages over the entire mix of queries that a particular installation will receive. This means that changing them on the basis of just a few experiments is very risky. seq_page_cost (floating point) Sets the planner's estimate of the cost of a disk page fetch that is part of a series of sequential fetches. The default is 1.0. This value can be overridden for tables and indexes in a particular tablespace by setting the tablespace parameter of the same name (see ALTER TABLESPACE). random_page_cost (floating point) The DBMS stores internal statistics about tables, attributes, and indexes in its internal catalog. Different systems update them at different times. Manual invocations: → Postgres/SQLite: **ANALYZE** → Oracle/MySQL: **ANALYZE TABLE** → SQL Server: **UPDATE STATISTICS** → DB2: **RUNSTATS** The selectivity \( \text{sel} \) of a predicate \( P \) is the fraction of tuples that qualify. **Equality Predicate: \( A=\text{constant} \)** \[ \rightarrow \text{sel}(A=\text{constant}) = \frac{\#\text{occurences}}{|R|} \] \[ \rightarrow \text{Example: sel(age=9)} = \frac{4}{45} \] SELECTION CARDINALITY Assumption #1: Uniform Data → The distribution of values (except for the heavy hitters) is the same. Assumption #2: Independent Predicates → The predicates on attributes are independent Assumption #3: Inclusion Principle → The domain of join keys overlap such that each key in the inner relation will also exist in the outer table. CORRELATED ATTRIBUTES Consider a database of automobiles: → # of Makes = 10, # of Models = 100 And the following query: → (make="Honda" AND model="Accord") With the independence and uniformity assumptions, the selectivity is: → \( \frac{1}{10}\times \frac{1}{100} = 0.001 \) But since only Honda makes Accords the real selectivity is \( \frac{1}{100} = 0.01 \) Source: Guy Lohman STATISTICS Choice #1: Histograms → Maintain an occurrence count per value (or range of values) in a column. Choice #2: Sketches → Probabilistic data structure that gives an approximate count for a given value. Choice #3: Sampling → DBMS maintains a small subset of each table that it then uses to evaluate expressions to compute selectivity. Our formulas are nice, but we assume that data values are uniformly distributed. **Histogram** 15 Keys $\times$ 32-bits = 60 bytes Distinct values of attribute EQUI-WIDTH HISTOGRAM Maintain counts for a group of values instead of each unique key. All buckets have the same width (i.e., same # of value). Bucket Ranges Bucket #1 Count=8 Bucket #2 Count=4 Bucket #3 Count=15 Bucket #4 Count=3 Bucket #5 Count=14 EQUI-DEPTH HISTOGRAMS Vary the width of buckets so that the total number of occurrences for each bucket is roughly the same. *Histogram (Quantiles)* 1. **Bucket #1** - Count=12 2. **Bucket #2** - Count=12 3. **Bucket #3** - Count=9 4. **Bucket #4** - Count=12 SKETCHES Probabilistic data structures that generate approximate statistics about a data set. Cost-model can replace histograms with sketches to improve its selectivity estimate accuracy. Most common examples: → **HyperLogLog** (2007): Approximate the number of distinct elements in a set. Modern DBMSs also collect samples from tables to estimate selectivities. Update samples when the underlying tables changes significantly. ``` SELECT AVG(age) FROM people WHERE age > 50 ``` <table> <thead> <tr> <th>id</th> <th>name</th> <th>age</th> <th>status</th> </tr> </thead> <tbody> <tr> <td>1001</td> <td>Obama</td> <td>61</td> <td>Rested</td> </tr> <tr> <td>1002</td> <td>Kanye</td> <td>45</td> <td>Weird</td> </tr> <tr> <td>1003</td> <td>Tupac</td> <td>25</td> <td>Dead</td> </tr> <tr> <td>1004</td> <td>Bieber</td> <td>28</td> <td>Crunk</td> </tr> <tr> <td>1005</td> <td>Andy</td> <td>41</td> <td>Illin</td> </tr> <tr> <td>1006</td> <td>TigerKing</td> <td>59</td> <td>Jailed</td> </tr> </tbody> </table> sel(age>50) = 1/3 Table Sample <table> <thead> <tr> <th>id</th> <th>name</th> <th>age</th> <th>status</th> </tr> </thead> <tbody> <tr> <td>1001</td> <td>Obama</td> <td>61</td> <td>Rested</td> </tr> <tr> <td>1003</td> <td>Tupac</td> <td>25</td> <td>Dead</td> </tr> <tr> <td>1005</td> <td>Andy</td> <td>41</td> <td>Illin</td> </tr> </tbody> </table> 1 billion tuples CONCLUSION - Query optimization is critical for a database system. - SQL -> logical plan -> physical plan. - Flatten queries before going to the optimization part. Expression handling is also important. - QO enumeration can be bottom-up or top-down. - Need to cost each plan, so need cost-estimation methods. Essential Query Optimization papers 1. **An Overview of Query Optimization in Relational Systems** 2. **The Volcano Optimizer Generator: Extensibility and Efficient Search** - **Goetz Graefe, William J. McKenna**: The Volcano Optimizer Generator: Extensibility and Efficient Search. ICDE 1993: 209-218 3. **Access Path Selection in a Relational Database Management System** - **Patricia G. Selinger, Morton M. Astrahan, Donald D. Chamberlin, Raymond A. Lorie, Thomas G. Price**: Access Path Selection in a Relational Database Management System. SIGMOD Conference 1979: 23-34 4. **Of Nests and Trees: A Unified Approach to Processing Queries That Contain Nested Subqueries, Aggregates, and Quantifiers** - **Umeshwar Dayal**: Of Nests and Trees: A Unified Approach to Processing Queries That Contain Nested Subqueries, Aggregates, and Quantifiers. VLDB 1987: 197-208 Suggestions if you are going to build a QO Rule 1: Read lots of papers, especially from the 80s & 90s. → Expect new combinations, only partially new core inventions. Rule 2: Early on, test various workloads on the QO. → QOs harden over time as they “see” new workloads. Let them see more ASAP. Rule 3: Throw away the initial one (or two) and start anew. → The hard part is going to be nitty-gritty details like data structures and pointers to shared objects; e.g., the list of predicates and the query graph structure, … You will NOT get this right in the first pass. Don’t try to patch; be prepared to rewrite. NEXT CLASS Transactions! → aka the second hardest part about database systems
{"Source-Url": "https://15445.courses.cs.cmu.edu/fall2023/slides/14-optimization.pdf", "len_cl100k_base": 6050, "olmocr-version": "0.1.50", "pdf-total-pages": 51, "total-fallback-pages": 0, "total-input-tokens": 67731, "total-output-tokens": 7951, "length": "2e12", "weborganizer": {"__label__adult": 0.0004591941833496094, "__label__art_design": 0.0004832744598388672, "__label__crime_law": 0.0005097389221191406, "__label__education_jobs": 0.02349853515625, "__label__entertainment": 0.00013709068298339844, "__label__fashion_beauty": 0.00023794174194335935, "__label__finance_business": 0.0005888938903808594, "__label__food_dining": 0.0005970001220703125, "__label__games": 0.0007109642028808594, "__label__hardware": 0.0010347366333007812, "__label__health": 0.0008292198181152344, "__label__history": 0.0006232261657714844, "__label__home_hobbies": 0.0002386569976806641, "__label__industrial": 0.0009150505065917968, "__label__literature": 0.0005164146423339844, "__label__politics": 0.0003285408020019531, "__label__religion": 0.0006761550903320312, "__label__science_tech": 0.07171630859375, "__label__social_life": 0.0003170967102050781, "__label__software": 0.027587890625, "__label__software_dev": 0.86669921875, "__label__sports_fitness": 0.0003502368927001953, "__label__transportation": 0.0006432533264160156, "__label__travel": 0.0003514289855957031}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 20264, 0.03548]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 20264, 0.48293]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 20264, 0.78311]], "google_gemma-3-12b-it_contains_pii": [[0, 43, false], [43, 356, null], [356, 1346, null], [1346, 2067, null], [2067, 2821, null], [2821, 3490, null], [3490, 3927, null], [3927, 4260, null], [4260, 4651, null], [4651, 5077, null], [5077, 5393, null], [5393, 5803, null], [5803, 5999, null], [5999, 6937, null], [6937, 7144, null], [7144, 7567, null], [7567, 7941, null], [7941, 8152, null], [8152, 8508, null], [8508, 9017, null], [9017, 9130, null], [9130, 9492, null], [9492, 9752, null], [9752, 10117, null], [10117, 10350, null], [10350, 10811, null], [10811, 11093, null], [11093, 11358, null], [11358, 11579, null], [11579, 11853, null], [11853, 12217, null], [12217, 12483, null], [12483, 12713, null], [12713, 13033, null], [13033, 13339, null], [13339, 13673, null], [13673, 14896, null], [14896, 15187, null], [15187, 15476, null], [15476, 15833, null], [15833, 16218, null], [16218, 16563, null], [16563, 16726, null], [16726, 16979, null], [16979, 17257, null], [17257, 17631, null], [17631, 18280, null], [18280, 18590, null], [18590, 19571, null], [19571, 20186, null], [20186, 20264, null]], "google_gemma-3-12b-it_is_public_document": [[0, 43, true], [43, 356, null], [356, 1346, null], [1346, 2067, null], [2067, 2821, null], [2821, 3490, null], [3490, 3927, null], [3927, 4260, null], [4260, 4651, null], [4651, 5077, null], [5077, 5393, null], [5393, 5803, null], [5803, 5999, null], [5999, 6937, null], [6937, 7144, null], [7144, 7567, null], [7567, 7941, null], [7941, 8152, null], [8152, 8508, null], [8508, 9017, null], [9017, 9130, null], [9130, 9492, null], [9492, 9752, null], [9752, 10117, null], [10117, 10350, null], [10350, 10811, null], [10811, 11093, null], [11093, 11358, null], [11358, 11579, null], [11579, 11853, null], [11853, 12217, null], [12217, 12483, null], [12483, 12713, null], [12713, 13033, null], [13033, 13339, null], [13339, 13673, null], [13673, 14896, null], [14896, 15187, null], [15187, 15476, null], [15476, 15833, null], [15833, 16218, null], [16218, 16563, null], [16563, 16726, null], [16726, 16979, null], [16979, 17257, null], [17257, 17631, null], [17631, 18280, null], [18280, 18590, null], [18590, 19571, null], [19571, 20186, null], [20186, 20264, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 20264, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 20264, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 20264, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 20264, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 20264, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 20264, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 20264, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 20264, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 20264, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 20264, null]], "pdf_page_numbers": [[0, 43, 1], [43, 356, 2], [356, 1346, 3], [1346, 2067, 4], [2067, 2821, 5], [2821, 3490, 6], [3490, 3927, 7], [3927, 4260, 8], [4260, 4651, 9], [4651, 5077, 10], [5077, 5393, 11], [5393, 5803, 12], [5803, 5999, 13], [5999, 6937, 14], [6937, 7144, 15], [7144, 7567, 16], [7567, 7941, 17], [7941, 8152, 18], [8152, 8508, 19], [8508, 9017, 20], [9017, 9130, 21], [9130, 9492, 22], [9492, 9752, 23], [9752, 10117, 24], [10117, 10350, 25], [10350, 10811, 26], [10811, 11093, 27], [11093, 11358, 28], [11358, 11579, 29], [11579, 11853, 30], [11853, 12217, 31], [12217, 12483, 32], [12483, 12713, 33], [12713, 13033, 34], [13033, 13339, 35], [13339, 13673, 36], [13673, 14896, 37], [14896, 15187, 38], [15187, 15476, 39], [15476, 15833, 40], [15833, 16218, 41], [16218, 16563, 42], [16563, 16726, 43], [16726, 16979, 44], [16979, 17257, 45], [17257, 17631, 46], [17631, 18280, 47], [18280, 18590, 48], [18590, 19571, 49], [19571, 20186, 50], [20186, 20264, 51]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 20264, 0.08804]]}
olmocr_science_pdfs
2024-11-28
2024-11-28
b9d13a002d821bc12720218890b6d741c0ce1dec
WEB-SUPPORTED PRODUCT CONCEPT DEVELOPMENT Lars Holmdahl, Evastina Björk, Stig Ottosson, Sándor Vajna Abstract Web-based activities are becoming more and more common. Telephoning free of charge over the Internet (IP – Internet Protocol) has become much used within a short period of time. In a similar way videoconferences can be held in an inexpensive way over the Internet. Equally, radio and TV broadcasting over Internet will become more and more common. It should be possible to use inexpensive web-based support both during the creation of a new product concept and during the following product development. However, two types of dilemma exist: the mental problem and technological problems. In tests in late 2004 and early 2005 we have found that mentally related problems seem to be the most difficult ones to overcome as most people found it of outmost importance to meet in person to be creative. We have also experienced that the technology still is not good enough for combined IP-based meetings. However, the latter is a technology problem that seems easier to be solved. We have experienced that using web-based support can be beneficial in many ways. We believe that in the future the web will be used even in the creative process to bring forward product concepts. As it offers global cooperation without expensive and time consuming travelling, it is of great interest to innovative enterprises. Keywords: CPD, concept development, Internet, IP technology, product development 1. Background The term "Collaborative Product Development" (CPD) emerged during the 1990s (e.g. [1]) to describe a concept of "work around the clock", virtually speaking following the sun around the globe. Thus, when a development team had finished its work for the day, it sent its work further to a second team being 8 hours behind the first team. When that team had finished its work after 8 hours, it sent in turn its work further to a third team being 8 hours behind the second team. When that team had finished its work for the day, it should send the work further to the first team. Running a product development project in this way was thought of to be very time-efficient – theoretically. However, limited tests (e.g. [2]) showed great problems getting acceptable results out of CPD, even for simple development projects. Despite the disappointing results, globally acting enterprises are determined to find (even unusual) ways to overcome these problems. General Motors e.g. has formed a global network of universities in what is called the PACE project (www.pacepartners.org) of which one important aim is to encourage CPD projects. An obvious benefit from distributing workgroups around the world is the increased sharing possibility of software licenses. Thus, when Ford acquired Volvo Car, the total number of software licenses didn't increase since the USA, Europe and Japan are suitably separated in time [3]. Within standard CPD descriptions, product development is done in a sequential way with information attached to each package of work (mostly CAD files). The next team can use this information as input and can continue the work. CPD is also regarded as a possibility to shorten the Engineering design process. As Engineering design is partly artistic and heuristic, it is, however, difficult to transfer the so-far-existing or still vague ideas in a written and consistent form so that the next team can continue the work without ambiguity. One approach to overcome these difficulties and to improve the outcome of CPD is to use IP communication by phone and video, at least for a certain period of time, where both teams have to overlap. At the 5th workshop on Integrated Product Development (IPD) held in Magdeburg in September 2004, it was decided to investigate whether IPD students from different universities in Europe could create product concepts by purely using the Internet (no personal meetings) under the leadership of a project leader, who was supposed to participate from still another place in Europe. Initially it was decided that Halmstad University in Sweden and Magdeburg University in Germany should take part in the project after which other universities should join when experiences had been gained. Halmstad University was to give the problem to solve. This paper tells about our findings of this investigation so far. Communication over the Internet is a much-researched subject. There is e.g. the problem of designing the software for voice and video transfer [4], [5], and to interface with the system [6]. Experimenters have tried different arrangement of components of wearable computers in order to create so-called tele-presence [7]. Tele learning is an important subject as there is a need for distributed educational opportunities [8]. There is videoconferencing [9] and a wish for mobility [10], which puts out demand for positioning [11], and to create ad hoc networks [12]. There is also a wish for immersion and enrichment of experience with multimedia [13], [14]. It seems that so-called e-meetings and videoconferences so far only have used video to create a sense of presence. For good communication these systems have to rely on high quality audio channels [5], [15]. Design activities, however, are different in nature from learning or sharing information. Because being of highly interactive nature, they are also more demanding activities than e.g. tele-participation in sports events or immersing oneself in multimedia presentations. 2. Purpose Our focus of interest has been to investigate to what extent low cost web collaboration and low cost video, voice and file transfer solutions using the Internet could efficiently enable creative collaborative product development when team members are geographically dispersed. 3. Approach and methods This paper describes a CPD project where the researchers have an insider as well as an outsider perspective on the project [15]. The idea was to set up a concept development team of three students from Halmstad University and three students from Magdeburg University, under the leadership of a project leader, who was a PhD student in Magdeburg. The teams should develop a product concept on a problem that had been solved earlier by student groups in a regular product development course at Halmstad University. No personal meetings should take place, as all communication should happen over the Internet. The teams should have three weeks from project start to the presentation of their results. The process was to be observed by the authors. The problem to be solved was that packages of wash powder are difficult to handle for people with reduced body functions due to impairment like e.g. a stroke or rheumatoid arthritis. A new solution was needed that should 1. be easy to open with only one hand and 2. not break or open by itself if it falls from a table on a hard floor. This problem has already been investigated at the University of Halmstad using traditional methods. In a similar way, the student teams in the pilot test should develop a product concept together, "meeting" each other only over the web. For the project work, a web portal should be used, which in turn could also be entered over a home page set up for the test project to offer to other participating universities participating at the IPD workshop to follow the project. 3.1. Mental problems Having set up the home page and connected the web portal to it, the next step was the setting up of the two student teams in Germany and Sweden. A preparation meeting was held in January 2005 in Magdeburg. In the discussions, the PhD student, who was expected to be the project leader, showed to be very sceptical about the whole idea as he was convinced that it is not possible to develop new concepts if the team members do not meet in person "to sit together". Additionally, because of the actual winter semester in Germany, the possible student members were tied up in lectures and other work. The same situation happened when Delft Technical University in the Netherlands was asked to recruit the students. Therefore, the project could not be conducted in the planned way. Instead, one of the authors, Lars Holmdahl, was asked to be project leader. Having installed the project leader and in order to minimise technical problems occurring with the new IP technology, the authors agreed that the first tests should be conducted in Sweden after which it should be easier to conduct the additional tests that would include students from Sweden and other countries. 3.2. Technology issues By the end of 2004, the number of worldwide broadband subscribers exceeded 150 millions, with a 50% annual increase. There are 14 – 25 broadband lines per 100 inhabitants in the top ten countries (www.point-topic.com). Therefore IP (Internet Protocol) rapidly offers an increasing possibility to communicate, for example by video, voice and file transfer, and to broadcast over the Internet. This is a cost-effective way to communicate, which in turn means that small companies, clusters of small enterprises, and virtual companies can afford to use distance communication en masse. As an example, IP telephone market leader Skype (www.skype.com) has got more than 29 millions of registered users since its start in 2003 (actually, the number of users increases by 0.15 million per day). At any single time there are more than 2 million users on-line. This can, in effect, lead to the creation of the first true worldwide telephone book. 1 His standpoint was "taking a beer and being together is important for the creative process". 2 The different teaching times throughout Europe have caused quite a lot of problems when establishing international IPD student project teams. There are three main types of solutions available: **Web collaboration** - The simultaneous viewing and modification of a shared document or computer application. **Videoconferencing** - The use of digital video transmission systems to communicate between sites using video and voice. Digital video transmission systems typically consist of camera, codec\(^3\), network access equipment, video and audio system. **Webconferencing** - A term that describes the industry forming around the creation of virtual events. This industry is a convergence of technology developed to provide cost-effective interactive communication channels for individuals and businesses. By searching the Internet we found 152 vendors providing web collaboration (40), videoconferencing (54) and webconferencing solutions (104). To test IP-based cost effective videoconferences, webcams were bought in January 2005. One *iVisit Plus* and two free *iVisit Lite* licenses were acquired from iVisit (www.ivisit.com). The annual cost for the *iVisit Plus* license is $40, that is about 1% of the cost for a high-end solution. For each license there is one channel each for video, voice, and file transfer. Mid January 2005 the authors Ottosson and Holmdahl and a third person started a conference. Holmdahl was sitting in his home in Göteborg while the two other test persons were sitting in an office in central Göteborg about 4 meters from each other not in a Face-to-Face (F2F) position. Video, chat, and file transfer were working well, but we experienced problems with the voice channel (apparently the software did not allocate enough bandwidth for this channel). By switching to Skype for voice communication, we also had flawless voice transfer (20–20,000 Hz as compared to 300-3,000 Hz for normal telephone communication) and could start testing how to use cameras and software for dialogues and brainstorming. **3.3. Functional set up** Often when a group comes together for discussions or creative work (talking, making quick sketches and quick calculations), members sit close to each other around a table face to face, where items to be discussed can be viewed. Almost always a whiteboard hangs on the wall at the short end of the table and often there are provisions for hanging drawings, pictures, and diagrams on the walls. In a video conference/web collaboration setting we wanted to recreate – as far as possible – this familiar way of working. This was realised by a set-up, as shown in figure 1, in which an (although weak) illusion is created that the two groups are sitting at each end of a table. The projected picture on the wall in figure 1 can be the other group, for instance for introductory presentations, or a special object to be viewed by the groups. It can also be a digital whiteboard where all participants can draw and write on the same surface using the mouse or special pen and digitiser tablet. The difference compared to “classical” videoconferencing is the multitude of communication channels and the available collaborative software. Only the number of computers and broadband connections limits the number of channels for video, voice, and file transfer. The operator of the computer connected to the video projector controls the content of the projection. It is fully possible for each participant to have his own computer, webcam, etc. --- \(^3\) Codec is the short form for compressor/decompressor, i.e. any technology for compressing and decompressing data. Codcs can be implemented in software, in hardware, or in a combination of both. Some popular codecs for computer video include MPEG, Indeo, and Cinepak. and freely to choose what windows to be open, what channels to monitor, with whom to chat, to talk to, etc. ![Diagram of collaboration setup](image) Figure 1: Even though the two groups are sitting thousands of kilometres apart (symbolised by the wall in the middle of the table) the web cameras and the projected pictures, by the imaginary window between the groups, create a feeling of collaboration. The principle set-up of the solution that we found to be useful for dialogues and brainstorming is shown in figure 2. Depending on the set-up of the router/firewall, several licences can be operated on the same IP number. This means that additional cameras can be added as is shown for project group 2 in figure 2. ![Diagram of network setup](image) Figure 2: A functional set up when two groups of three people are sitting together and the project leader is sitting at a third place. In this example project group 2 has an additional web camera attached to a second computer as shown in figure 3. ![Diagram of setup for two separate groups](image) Figure 3: A functional set up when two groups of three people are sitting together and the project leader is sitting at a third place. In this example project group 2 has an additional web camera attached to a second computer as shown in figure 3. It is possible to use only one web camera and move the camera, showing a person or the whole group and a piece of paper on which a sketch is made. However, it is more convenient to have additional web cameras, each dedicated for a certain purpose. We quickly found that it is most convenient to have web cameras positioned so as to capture paper and pencil sketches. as they are made, exactly as when sitting together in a real life situation. This retains the important coupling between brain, hand, and visual impression during creative concept development [16]. For this purpose there are many simple ways to arrange an additional web camera, see figure 3. Figure 3: Simple ways for arranging a web camera, so as to capture paper and pencil sketches In product development there are many instances when visual information is important. There are, to name a few, the check of first shot specimens, reverse engineering of designs of a competitor, and the inspection of tested parts. In all these cases a high quality video image is very important if we intend to substitute regular meetings with videoconferences. Figure 4 shows an example of the screen set-up used during an actual videoconference session. In this example we see two of the participants, some video conference “house holding” windows and the share window put on top of a Microsoft Paint window containing a drawing of a belt tensioner which is commented upon. Thereby the drawing was made visible to the other party. Figure 4: An example of a computer screen used during the test videoconference session The total investment for the arrangement for the set-up shown in figure 1 (except for computers, video projectors and Internet connection) was less than 500 Euros. 4. Results The whole test session showed that it is possible to be creative, even under the given circumstances. Not surprisingly the quality of the video image is important as concept development in new product development relies heavily on making sketches and jotting down ideas using symbols [17]. There is also a need for sharing images of prototypes and models. In the later case a high video frame rate is important for the correct representation of movements. In the dialogues we found solutions of how to arrange cameras etc. to make dialogues and brainstorming on distance using IP technology. The planning and conducting of the test have clearly shown that IP technology can be used for dialogues and brainstorming sessions when people are sitting distributed. The purpose to find cheap ways for small companies using the web was also satisfied in the test. 5. Discussion Many researchers have experienced as a difficult task the implementation of new tools and methods on how to perform product development and its management. The explanations of why enterprises take a distant position towards new research findings have been discussed among researchers as well as among practitioners [18] and the arguments have varied with research approach, size of company, organisation etc. A well-known argument heard from companies is that the outside research perspective provides the researchers with “outside information” meaning information known and obvious to anyone. In order to get hold of the “unspoken and silent” knowledge often needed to be able to understand a task/problem in a proper way, and to create useful and valuable solutions to the practitioner, a totally different research approach is needed [19]. Product development projects, especially new product development projects (often with tight time schedules due to short life cycles and financial reasons) demand effective global communication and rather fast decision making. Therefore it should be of industrial interest, especially for international companies with many subsidiaries and partners abroad as well as for virtual companies, to introduce new tools and methods based on Information and Communication Technology (ICT) for supporting the creative part of the development process. As many employees today have access to own and other personal computers and laptops connected to web servers (see figure 5) and as web cameras are inexpensive, there are possibilities to have short daily videoconferences, virtually at no cost and regardless of where one happens to be [5]. So far, the research has provided us with another picture [1] based on a situation when the new web based possibilities did not exist. Young people at European universities are familiar with computers, the use of web-based services, and communication tools. However, due to various difficulties, it was only possible to set up a student group in Sweden, but not in Germany. For instance, the attitude of the potential German project leader towards conducting an innovative product concept development without personal meetings was negative. This “mental dilemma” was an example of how unfamiliar ways of handling things make people feel insecure and doubtful. In the limited test we found that it was possible to make brainstorming. Solving the technical problems we got in a way quite similar to what our experiences are when people are actually together. Our test did not grasp cultural and language problems that theoretically can be an additional problem to handle working “around the clock”. Thus we think that the traditional rules of thumb on what is needed for a group to be creative (geographical collocation, sitting in an office, etc) must be re-judged. The fast development of the web technology has opened new possibilities, even when it comes to innovative product concept development and the work to finish the development of a new product. The way of working that we have tested should offer new opportunities to make CPD more functional even though it means that people on different continents have to attend meetings over the web at off-time hours. It also offers possibilities to involve experts without time-consuming travel to bring them together. As often is the case when new ways of working are tested, few people initially want to take part if the learned behaviour is threatened. Only when an outer pressure is put on change, resistant people accept changes. With the globalisation that takes part in a rapid speed, methods as the tested will be needed in a near future. Hence, a new thrilling field for research therefore surely has opened not the least to bring in small companies on the scene. References Ass. Prof. Dr.-Ing. Evastina Björk, School of Business and Engineering Halmstad University P.O. Box 803, SE-301 18 Halmstad Sweden evastina.bjork@set.hh.se Lic. Lars Holmdahl, Prof. Dr. Stig Ottosson, Prof Dr.-Ing. Sándor Vajna Information Technologies in Mechanical Engineering Otto-von-Guericke-University Magdeburg Universitätsplatz 2, D – 39106 Magdeburg Germany lars.holmdahl@bostream.nu stig.ottosson@mb.uni-magdeburg.de vajna@mb.uni-magdeburg.de
{"Source-Url": "https://www.designsociety.org/download-publication/23166/web-supported_product_concept_development", "len_cl100k_base": 4369, "olmocr-version": "0.1.49", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 19167, "total-output-tokens": 6004, "length": "2e12", "weborganizer": {"__label__adult": 0.00040030479431152344, "__label__art_design": 0.00446319580078125, "__label__crime_law": 0.000659942626953125, "__label__education_jobs": 0.048980712890625, "__label__entertainment": 0.0002887248992919922, "__label__fashion_beauty": 0.0003323554992675781, "__label__finance_business": 0.00720977783203125, "__label__food_dining": 0.0005207061767578125, "__label__games": 0.000720977783203125, "__label__hardware": 0.0036678314208984375, "__label__health": 0.0009937286376953125, "__label__history": 0.0007262229919433594, "__label__home_hobbies": 0.0004982948303222656, "__label__industrial": 0.00231170654296875, "__label__literature": 0.0007719993591308594, "__label__politics": 0.0003771781921386719, "__label__religion": 0.0004820823669433594, "__label__science_tech": 0.37548828125, "__label__social_life": 0.0004916191101074219, "__label__software": 0.0970458984375, "__label__software_dev": 0.451171875, "__label__sports_fitness": 0.0003445148468017578, "__label__transportation": 0.0016088485717773438, "__label__travel": 0.00035691261291503906}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 25438, 0.02763]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 25438, 0.53623]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 25438, 0.94281]], "google_gemma-3-12b-it_contains_pii": [[0, 2929, false], [2929, 6399, null], [6399, 9776, null], [9776, 13419, null], [13419, 15094, null], [15094, 16304, null], [16304, 19166, null], [19166, 21440, null], [21440, 25438, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2929, true], [2929, 6399, null], [6399, 9776, null], [9776, 13419, null], [13419, 15094, null], [15094, 16304, null], [16304, 19166, null], [19166, 21440, null], [21440, 25438, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 25438, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 25438, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 25438, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 25438, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 25438, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 25438, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 25438, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 25438, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 25438, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 25438, null]], "pdf_page_numbers": [[0, 2929, 1], [2929, 6399, 2], [6399, 9776, 3], [9776, 13419, 4], [13419, 15094, 5], [15094, 16304, 6], [16304, 19166, 7], [19166, 21440, 8], [21440, 25438, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 25438, 0.0]]}
olmocr_science_pdfs
2024-11-27
2024-11-27
3e632478e55f5f979ebe9b511a7d0997ea841099
A Compositional Analysis Framework for Hierarchical and Partitioned Real-Time Systems Insup Lee PRECISE Center Department of Computer and Information Science University of Pennsylvania June 2, 2009 AFOSR FA9550-07-1-0216 (PM: Dr. David Luginbuhl) Motivation and Goal • Embedded systems are becoming complex, networked, and large-scale. • Embedded systems have many para-functional aspects: – physically coupled, real-time, location-aware, resource-constrained, heterogeneous, and etc. – real-time: required to react to events or complete tasks in specific time – resource-constrained: subject to operating with scarce resources, such as processor power, memory, power, bandwidth • Component-based approach for the design of large complex systems – Interoperability, predictability, scalability,… • Goal: resource-sensitive component framework – Hierarchical, compositional, incremental Component technologies - Enable component-based development - abstract components through interfaces - Interfaces preserve intellectual property - compose components preserving compositionality - facilitate modularity, portability, and reusability - Traditional focus: functional, behavioral aspects - need: non-functional aspects, such as timeliness, reliability, safety, and resource use ARINC 653: Schedulability Abstraction and Composition • Abstraction Problem: abstract the real-time application as a component with an interface • Compute the minimum real-time requirements necessary for guaranteeing the schedulability of a component Abstraction and Composition • Composition Problem: compose component-level properties into system-level (or next-level component) properties Compositionality • Compositionality: – system-level properties can be established by composing independently analyzed component-level properties • Compositional reasoning based on assume/guarantee paradigm – components are combined to form a system such that properties established at the component-level still hold at the system level. • Compositional schedulability analysis using the demand/supply bounds – Establish the system-level timing properties by combining component-level timing properties through interfaces Resource Satisfiability Analysis • Given a task set and a resource model, resource satisfiability analysis is to determine if, for every time, \[\text{resource demand, which a task set needs under a scheduling algorithm} \leq \text{(minimum possible) resource supply}\] Hierarchical Scheduling Framework - Resource allocation from parent to child - Notations - Leaf → C₁, C₂, C₃ - Non-leaf → C₄, C₅ - Root → C₅ ARINC 653 → Two-level hierarchical framework OS Scheduler’s Viewpoint - Digital Controller - \( T_1(25,5) \) - Multimedia - \( T_2(33,10) \) - Java Virtual Machine - Real-Time Task - Real-Time Demand - OS Scheduler - CPU Resource Demand Models Real-time demand composition • Combine real-time requirements of multiple tasks into real-time requirement of a single task Real-Time Constraint || Real-Time Constraint = Real-Time Constraint Periodic Task || Periodic Task = Periodic Task EDF / RM Non-composable periodic models? - What are right abstraction levels for real-time components? *(period, execution time)* - \(P_1 = (p_1, e_1); \) e.g., \((3,1)\) - \(P_2 = (p_2, e_2); \) e.g., \((7,1)\) - What is \(P_1 \parallel P_2?\) - \((\text{LCM}(p_1, p_2), e_1 \cdot n_1 + e_2 \cdot n_2); \) e.g., \((21, 10)\) - where \(n_1 \cdot p_1 = n_2 \cdot p_2 = \text{LCM}(p_1, p_2)\) - What is the problem? - \(\text{beh}(P_1) \parallel \text{beh}(P_2) = \text{beh}(P_1 \parallel P_2)?\) - Compositionality - \((P_1 \parallel P_2) \parallel P_3 = P \parallel P_3, \) where \(P = P_1 \parallel P_2\) Resource Demand Bound - Resource demand bound during an interval of length $t$ - $dbf(W,A,t)$ computes the maximum possible resource demand that $W$ requires under algorithm $A$ during a time interval of length $t$ - Periodic task model $T(p,e)$ [Liu & Layland, ’73] - characterizes the periodic behavior of resource demand with period $p$ and execution time $e$ - Ex: $T(3,2)$ ![Diagram of resource demand over time] Demand Bound - EDF - For a periodic workload set $W = \{T_i(p_i,e_i)\}$, - $dbf(W,A,t)$ for EDF algorithm [Baruah et al., '90] $$dbf(W,EDF,t) = \sum_{T_i \in W} \left\lfloor \frac{t}{p_i} \right\rfloor \cdot e_i$$ Demand-based Schedulability Analysis • A periodic task set is schedulable under EDF over the periodic resource model \( \Gamma(P,Q) \) if and only if \( \forall t > 0 \ dbf(t) \leq t \leq \ lsbf(t) \) [Shin and Lee, 2003] Demand bound revisited - More than one resource model may be used - Consider only LSBF that intersect DBF - An “optimal” choice from the component perspective may be globally unsuitable Task (resource demand) representations Resource Supply Models Resource Modeling • Dedicated resource: always available at full capacity • Shared resource: not a dedicated resource – Time-sharing: available at some times – Non-time-sharing: available at fractional capacity Resource Modeling • Time-sharing resources – Bounded-delay resource model [Mok et al., ’01] characterizes a time-sharing resource w.r.t. a non-time-sharing resource – Periodic resource model \( \Gamma(\Pi, \Theta) \) [Shin & Lee, RTSS ’03] characterizes periodic resource allocations - EDP model [Easwaran et al., RTSS 07] Resource Supply Bound • Resource supply during an interval of length t – \( \text{sbf}_R(t) \): the minimum possible resource supply by resource R over all intervals of length t • For a single periodic resource model, i.e., \( \Gamma(3,2) \) – we can identify the worst-case resource allocation Resource Supply Bound • Resource supply during an interval of length t – $\text{sbf}_\Gamma(t)$: the minimum possible resource supply by resource R over all intervals of length t • For a single periodic resource model $\Gamma(\Pi, \Theta)$ $$\text{sbf}_R(t) = \begin{cases} t - (k + 1)(\Pi - \Theta) & \text{if } t \in [(k + 1)\Pi - 2\Theta, (k + 1)\Pi - \Theta] \\ (k - 1)\Theta & \text{otherwise} \end{cases}$$ Resource Schedulability Analysis - **Schedulability analysis** determines whether resource demand, which a workload set requires under a scheduling algorithm \[ \leq \] resource supply, which available resources provide Schedulability conditions - $\text{sbf}_{\Gamma}(t)$: Supply bound function: Minimum resource supply of model $\Gamma$ in any time interval of length $t$ - $\text{lsbf}_{\Gamma}(t)$: Linear lower bound of $\text{sbf}_{\Gamma}(t)$ \[ \text{lsbf}_{\Gamma}(t) = \Theta \frac{t - 2(\Pi - \Theta)}{\Pi} \] Schedulability conditions Starvation length \[2 (\Pi - \Theta)\] Bandwidth \(\Theta/\Pi\) (slope of line) sbf\(_\Gamma\) lsbf\(_\Gamma\) The EDP Resource Model • Explicit Deadline Periodic resource • Model: $\Omega = (\Pi, \Theta, \Delta)$ – Explicit deadline $\Delta$ – $\Theta$ resource units in $\Delta$ time units – Repeat supply every $\Pi$ time units • Properties – Periodic resource model is a EDP model with $\Delta = \Pi$ – Maximum slack of EDP model depends on $\Theta$ and $\Delta$ for a fixed $\Pi$ – Slack can be controlled using $\Delta$ without changing bandwidth of model (within limits) – Smaller bandwidth required to schedule the same component, when compared to periodic resource models – improves precision of resource allocation Supply bound function \( (sbf_{\Omega}) \) - \( \Gamma(5,3) \) - Starvation length = 4 - \( \Omega(5,3,4) \) - Starvation length = 3 Bandwidth optimal interface • Given component $C$ and period $\Pi$ – Compute $\Theta$ and $\Delta$ • We use bandwidth optimality – Minimizes resource bandwidth $\Theta/\Pi$ – Occurs when $\Delta=\Theta$ (*Theorem 3.2 in RTSS’07*) Bandwidth optimal interface $$\Omega' = (\Pi, \Theta, \Delta), \Delta > \Theta$$ minimum bandwidth for model $$\Omega'$$ Bandwidth optimal interface \[ \Omega = (\Pi, \Theta, \Theta) \] \[ \Theta \text{ can be reduced} \] Bandwidth optimal interface \[ \Omega = (\Pi, \Theta^*, \Theta^*) \] bandwidth optimal model \( \Omega \) Bandwidth-deadline optimal • Choose interface with Largest $\Delta$ among all bandwidth optimal interfaces – Reduced demand for composition • Interface generation procedure – Set $\Delta=\Theta$, compute $\Omega = (\Pi, \Theta^*, \Theta^*)$ – Set $\Theta=\Theta^*$, compute $\Omega^* = (\Pi, \Theta^*, \Delta^*)$ Applying to ARINC 653 - 2-level hierarchical scheduler - Partitions scheduled among themselves at higher level - Processes within each partition scheduled at lower level - Uniqueness of ARINC 653 - Harmonic partition periods - Preemption and blocking overheads - Communication dependencies across partitions - Process workload (dbf) depends on parameters which in turn are determined by these dependencies - Applying to real ARINC workloads obtained from Honeywell - Preliminary results showed an improvement of up to 300% in bandwidth, depending on period of interfaces for 5-6 partitions, with 1-5 tasks each - Tool (called CARTS) development underway to handle more extensive workloads Example: ARINC workload • Process parameters: (O, J, T, C, D) – O = Offset, J = Jitter, T = Period, C = Worst-case execution time, D = Deadline – T, C, D from workload, O added speculatively • Example 1 Partition 1: {(2, 0, 25, 1.4, 25), (3, 0, 50, 3.9, 50)} Partition 2: {(0, 0, 50, 2.8, 50)} Partition 3: {(0, 0, 50, 1.4, 50)} Partition 4: {(3, 0, 25, 1.1, 25), (5, 0, 50, 1.8, 50), (11, 0, 100, 2, 100), (13, 0, 200, 5.3, 200)} Partition 5: {(2, 0, 50, 1.3, 50), (14, 0, 200, 1.5, 200)} Resource Supply Models - ACSR+ - Recurring branching resource supply model - Tree schedule - Cyclic Executive - EDP model - Periodic model - Bounded-delay Resource model 6/2/09 Incremental Analysis Incremental analysis R₃’ should be same irrespective of order in which τ₂’ and τ₄ are added Associative composition guarantees incremental analysis Multicore Processor Virtualization 1. Compositional analysis of hierarchical multiprocessor real-time systems, through component interfaces 2. Using virtualization to develop new component interface for multiprocessor platforms ![Diagram of virtual CPU and scheduler with interfaces to tasks] Partitioned Scheduling \( \tau_{x_1} \cup \tau_{x_2} \ldots \cup \tau_{x_m} = \tau \) \( \tau_{x_i} \cap \tau_{x_j} = \phi \) for all \( i \) and \( j \) Global Scheduling \[ \tau \] Physical processors Single task cluster 6/2/09 S5 40 Multiprocessor Scheduling • **Goal:** Optimal scheduling algorithms and their analysis techniques • **Partitioned vs. Global Scheduling** – Shown using simulations [Baker05] that partitioned performs better – Exists task sets schedulable by global but not by any partitioned algorithm – EDF load bounds: \( \frac{1}{2}(m - (m-1)\delta_{\text{max}}) \) [partitioned] vs. \( (m - (m-1)\delta_{\text{max}})(1-\delta_{\text{max}}) \) [global] • **Our Approach:** Framework for development of scheduling algorithms that support general task-processor mappings through virtualization Virtual Clustering Interface \[ \tau_{x_1} \cup \tau_{x_2} \ldots \cup \tau_{x_k} = \tau \] \[ \tau_{x_i} \cap \tau_{x_j} = \emptyset \text{ for all } i \text{ and } j \] Virtual Clustering Interface For each $\Gamma_i$, $m_i (\leq m)$ is maximum number of physical processors that can be assigned to $\Gamma_i$ at any instant. Virtual Clustering - Task set and number of processors - \( \tau_1 = \tau_2 = \tau_3 = \tau_4 = (3, 2, 3) \), \( \tau_5 = (6, 4, 6) \), and \( \tau_6 = (6, 3, 6) \), \( m = 4 \) - Schedule under clustered scheduling - \( \tau_1, \tau_2, \tau_3 \) scheduled on processors 1 and 2 - \( \tau_4, \tau_5, \tau_6 \) scheduled on processors 3 and 4 Virtual Clusters - Use platform virtualization to provide a trade-off between resource utilization and scheduling complexity Cluster interface: $\Gamma, m$ - $\Gamma$ is the resource model, $m$ is the maximum number of physical processors available - Inter-cluster scheduling is optimal <table> <thead> <tr> <th>Partitioned Scheduling</th> <th>Cluster-based Scheduling</th> <th>Global Scheduling</th> </tr> </thead> <tbody> <tr> <td>low utilization, easy to compute</td> <td>small clusters =&gt; partitioned, large clusters =&gt; global</td> <td>high utilization, hard to compute</td> </tr> </tbody> </table> Virtual Clustering - Two-level hierarchical scheduler - Intra-cluster schedulers for tasks within clusters - Inter-cluster schedulers for clusters on the platform (clusters can share some physical processors) - Concurrency bound for each cluster - Abstract concurrency constraints of tasks within cluster - Minimizes overhead of schedulability analysis (e.g., Global EDF) - Helps regulate resource access (e.g., Caches?) - Have virtual clusters been used before? - Supertasks\textsuperscript{[MoRa99]}, Megatasks\textsuperscript{[ACD06]} - Results restricted to Pfair schedulers (not generalizable) Need for Multiprocessor Periodic Resource (MPR) model Multiprocessor Periodic Resource (MPR) model - $\Gamma = (\Pi, \Theta, m')$ - $\Theta$ units of resource supply guaranteed in every $\Pi$ time units, with concurrency at most $m'$ in any time instant - Consider $\Gamma = (5, 12, 3)$ - Why MPR model? - Periodicity enables transformation of MPR model to periodic tasks which can be scheduled using standard algorithms Virtual Cluster-based Scheduling 1. Split task set $\tau$ into clusters $\tau_{x_1}, \ldots, \tau_{x_k}$ 2. Abstract $\tau_{x_i}$ into MPR interface $\Gamma_i$ (for cluster $VC_i$) 3. Transform each $\Gamma_i$ into periodic tasks - Enables inter-cluster scheduler to schedule $\Gamma_i$ Summary on Virtual Clustering - Virtual cluster-based multiprocessor scheduling - Transforms tasks from constrained to implicit deadline - Optimal inter-cluster scheduling techniques can be employed - Allows processor slack from one cluster to be used by another - Shows promise w.r.t. success of simple clustering techniques - Open issues - Efficient clustering techniques for constrained and arbitrary deadline task systems - With an aim to solve the important open problem of optimal scheduling of arbitrary deadline periodic task systems - Including other resources such as caches CARTS: Compositional Analysis of Real-Time Systems Execution Demands for VM and OS Schedulers - OS Scheduler (EDF) (5, 4.38) - VM Scheduler (RM) (5, 1.86) - Digital Controller (25, 5) - Multimedia (33, 10) - Task 1 (25, 4) - Task 2 (40, 5) System Modeling in **CARTS** - Tree representation System Modeling in **CARTS** - XML representation ``` <system os_scheduler="EDF" min_period="5" max_period="5"> <task name="Digital Controller" p="25" d="25" e="5"> </task> <task name="Multimedia" p="33" d="33" e="10"> </task> <component name="VM Scheduler" criticality="A" vmips="0" scheduler="RM" subtype="tasks" min_period="5" max_period="5"> <task name="task1" p="25" d="25" e="4"> </task> <task name="task2" p="40" d="40" e="5"> </task> </component> </system> ``` Analysis in CART ![Image of a software interface showing XML code and analysis results] - **Resource Model**: Period: 5.0, Bandwidth: 4.141267123287672, Deadline: 4.185445524085139 - **Processed Task Model**: Period: 5.0, Execution Time: 4.141267123287672, Deadline: 5.044178400797468 CARTS Supports • Task & Resource Models – Periodic – Explicit Deadline Periodic (EDP) • Scheduling Policies – Rate monotonic – Earlies Deadline First (EDF) – Others planned • Open architecture Features • Editor for demand-supply XML files • Tree representation of components and tasks • Editing components/tasks in the tree • Conversion from XML to tree representation and vice versa • AADL output planned Summary - Periodic Resource Model - Explicit Deadline Resource (EDP) Model - Incremental Analysis - Resource Optimality - Virtual Clustering for Multicore Processors - Toolset: CARTS - Compositionality in Multimode Real-Time Systems - Looking for Case Studies References • Hierarchical Scheduling Framework for Virtual Clustering of Multiprocessors, Insik Shin, Arvind Easwaran, Insup Lee, ECRTS, Prague, Czech Republic, July 2-4, 2008 (Runner-up in the best paper award) • Robust and Sustainable Schedulability Analysis of Embedded Software, Madhukar Anand and Insup Lee, LCTES, Tucson, AZ, Jun 12-13, 2008 This work was supported in part by AFOSR, NSF and ONR. Thank You! Questions?
{"Source-Url": "https://rtg.cis.upenn.edu/carts/docs/InsupLee_AFOSR09.pdf", "len_cl100k_base": 4651, "olmocr-version": "0.1.53", "pdf-total-pages": 59, "total-fallback-pages": 0, "total-input-tokens": 89455, "total-output-tokens": 7381, "length": "2e12", "weborganizer": {"__label__adult": 0.0004010200500488281, "__label__art_design": 0.0007319450378417969, "__label__crime_law": 0.0004265308380126953, "__label__education_jobs": 0.0019254684448242188, "__label__entertainment": 0.0001214742660522461, "__label__fashion_beauty": 0.00023365020751953125, "__label__finance_business": 0.00047516822814941406, "__label__food_dining": 0.0003883838653564453, "__label__games": 0.0007433891296386719, "__label__hardware": 0.005329132080078125, "__label__health": 0.0009107589721679688, "__label__history": 0.0004620552062988281, "__label__home_hobbies": 0.00019562244415283203, "__label__industrial": 0.0010919570922851562, "__label__literature": 0.00029969215393066406, "__label__politics": 0.00037217140197753906, "__label__religion": 0.0007138252258300781, "__label__science_tech": 0.364990234375, "__label__social_life": 0.00013780593872070312, "__label__software": 0.009765625, "__label__software_dev": 0.60888671875, "__label__sports_fitness": 0.0003402233123779297, "__label__transportation": 0.0011119842529296875, "__label__travel": 0.00023245811462402344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 17960, 0.02811]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 17960, 0.74952]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 17960, 0.714]], "google_gemma-3-12b-it_contains_pii": [[0, 250, false], [250, 900, null], [900, 1305, null], [1305, 1331, null], [1331, 1558, null], [1558, 1700, null], [1700, 2230, null], [2230, 2502, null], [2502, 2697, null], [2697, 2888, null], [2888, 2911, null], [2911, 3171, null], [3171, 3786, null], [3786, 4213, null], [4213, 4431, null], [4431, 4657, null], [4657, 4846, null], [4846, 4885, null], [4885, 4908, null], [4908, 5125, null], [5125, 5455, null], [5455, 5756, null], [5756, 6179, null], [6179, 6409, null], [6409, 6712, null], [6712, 6855, null], [6855, 7488, null], [7488, 7627, null], [7627, 7865, null], [7865, 7988, null], [7988, 8091, null], [8091, 8199, null], [8199, 8520, null], [8520, 9229, null], [9229, 9735, null], [9735, 9922, null], [9922, 10093, null], [10093, 10388, null], [10388, 10544, null], [10544, 10632, null], [10632, 11219, null], [11219, 11392, null], [11392, 11550, null], [11550, 11900, null], [11900, 12471, null], [12471, 13087, null], [13087, 13141, null], [13141, 13515, null], [13515, 13808, null], [13808, 14413, null], [14413, 14464, null], [14464, 14655, null], [14655, 14707, null], [14707, 15194, null], [15194, 15481, null], [15481, 15903, null], [15903, 16164, null], [16164, 17938, null], [17938, 17960, null]], "google_gemma-3-12b-it_is_public_document": [[0, 250, true], [250, 900, null], [900, 1305, null], [1305, 1331, null], [1331, 1558, null], [1558, 1700, null], [1700, 2230, null], [2230, 2502, null], [2502, 2697, null], [2697, 2888, null], [2888, 2911, null], [2911, 3171, null], [3171, 3786, null], [3786, 4213, null], [4213, 4431, null], [4431, 4657, null], [4657, 4846, null], [4846, 4885, null], [4885, 4908, null], [4908, 5125, null], [5125, 5455, null], [5455, 5756, null], [5756, 6179, null], [6179, 6409, null], [6409, 6712, null], [6712, 6855, null], [6855, 7488, null], [7488, 7627, null], [7627, 7865, null], [7865, 7988, null], [7988, 8091, null], [8091, 8199, null], [8199, 8520, null], [8520, 9229, null], [9229, 9735, null], [9735, 9922, null], [9922, 10093, null], [10093, 10388, null], [10388, 10544, null], [10544, 10632, null], [10632, 11219, null], [11219, 11392, null], [11392, 11550, null], [11550, 11900, null], [11900, 12471, null], [12471, 13087, null], [13087, 13141, null], [13141, 13515, null], [13515, 13808, null], [13808, 14413, null], [14413, 14464, null], [14464, 14655, null], [14655, 14707, null], [14707, 15194, null], [15194, 15481, null], [15481, 15903, null], [15903, 16164, null], [16164, 17938, null], [17938, 17960, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 17960, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 17960, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 17960, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 17960, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 17960, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 17960, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 17960, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 17960, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 17960, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 17960, null]], "pdf_page_numbers": [[0, 250, 1], [250, 900, 2], [900, 1305, 3], [1305, 1331, 4], [1331, 1558, 5], [1558, 1700, 6], [1700, 2230, 7], [2230, 2502, 8], [2502, 2697, 9], [2697, 2888, 10], [2888, 2911, 11], [2911, 3171, 12], [3171, 3786, 13], [3786, 4213, 14], [4213, 4431, 15], [4431, 4657, 16], [4657, 4846, 17], [4846, 4885, 18], [4885, 4908, 19], [4908, 5125, 20], [5125, 5455, 21], [5455, 5756, 22], [5756, 6179, 23], [6179, 6409, 24], [6409, 6712, 25], [6712, 6855, 26], [6855, 7488, 27], [7488, 7627, 28], [7627, 7865, 29], [7865, 7988, 30], [7988, 8091, 31], [8091, 8199, 32], [8199, 8520, 33], [8520, 9229, 34], [9229, 9735, 35], [9735, 9922, 36], [9922, 10093, 37], [10093, 10388, 38], [10388, 10544, 39], [10544, 10632, 40], [10632, 11219, 41], [11219, 11392, 42], [11392, 11550, 43], [11550, 11900, 44], [11900, 12471, 45], [12471, 13087, 46], [13087, 13141, 47], [13141, 13515, 48], [13515, 13808, 49], [13808, 14413, 50], [14413, 14464, 51], [14464, 14655, 52], [14655, 14707, 53], [14707, 15194, 54], [15194, 15481, 55], [15481, 15903, 56], [15903, 16164, 57], [16164, 17938, 58], [17938, 17960, 59]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 17960, 0.00867]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
cccf3f00c32f339151decab67151b46a6f75e8e2
Sage: The New BBN Speech Processing Platform Roger Hsiao, Ralf Meermeier, Tim Ng, Zhongqiang Huang, Maxwell Jordan, Enoch Kan, Tanel Alumäe, Jan Silovsky, William Hartmann, Francis Keith, Omer Lang, Manhung Siu and Owen Kimball Raytheon BBN Technologies 10 Moulton Street, Cambridge, MA 02138, USA {whsiao,rmeermei,msiu}@bbn.com Abstract To capitalize on the rapid development of Speech-to-Text (STT) technologies and the proliferation of open source machine learning toolkits, BBN has developed Sage, a new speech processing platform that integrates technologies from multiple sources, each of which has particular strengths. In this paper, we describe the design of Sage, which allows the easy interchange of STT components from different sources. We also describe our approach for fast prototyping with new machine learning toolkits, and a framework for sharing STT components across different applications. Finally, we report Sage’s state-of-the-art performance on different STT tasks. Index Terms: speech recognition toolkit 1. Introduction BBN’s Byblos STT system [1], which has always maintained state-of-the-art performance, has been our main research and application engine for more than 30 years. In addition to its use in research, multiple customized versions have also been successfully developed for commercial STT applications such as broadcast monitoring, keyword search, real-time applications such as speech-to-speech translations and even non-speech applications such as optical character recognition (OCR). Many of these customizations address task specific requirements, such as low-latency or different workflow. The field of STT has undergone tremendous changes over the past few years. The introduction of deep learning has generated substantial and rapid performance advancements rarely seen before. Meanwhile, the increasing popularity of the open-source movement leads to the proliferation of state-of-the-art machine learning and neural network technologies that are available to researchers as free-to-download toolkits, such as Kaldi [2], Tensorflow [3], CNTK [4], Caffe [5] and others. Many of these toolkits come with frequent algorithmic, software and recipe updates contributed by the community. To stay abreast of the continuous innovation, it is advantageous to have the ability to quickly test out these updates on any problem of interest and incorporate the useful ones into our own system. The fast pace of change and proliferation of toolkits and recipe make fast prototyping and easy integration of technology paramount. However, compatibility is a major challenge. Most toolkits are not cross-compatible with each other, and some are not even “self-compatible”, in that different versions or branches within a toolkit are incompatible. Furthermore, recipes and tutorials contributed by the community are often not written in ways that are easy to generalize and apply to new applications. The fast moving technology that is constantly upgrading makes supporting multiple highly customized STT engines difficult. This motivates the design of a single framework that allows flexible application specific customization while sharing the same underlying, evolving STT components. Sage is BBN’s newly developed STT platform for model training and recognition that integrates technologies from multiple sources, each of which has its particular strength. In Sage, we combine proprietary sources, such as BBN’s Byblos, with open source software (OSS), such as Kaldi, CNTK and Tensorflow. For example, Sage’s deep neural networks (DNNs) [6] can be trained using Byblos, Kaldi nnet1 or nnet2, convolutional neural networks (CNNs) [7] using Kaldi or Caffe, and long short-term memory networks (LSTMs) [8] using Kaldi as well as CNTK. The integration of these technologies is achieved by creating wrapper modules around major functional blocks that can be easily connected or interchanged. In addition, Sage software has been designed to make it easy for a group of researchers to use the system, to transfer experiments from one person to another, to keep track of partial runs, etc. Sage includes a cross-toolkit finite state transducer (FST) based recognizer that supports models built using the various component technologies. To quickly prototype with models built using newly released machine learning toolkits, Sage also includes a Python interface that can directly interact with toolkits that supply Python API, such as Tensorflow. To make use of this modularity all the way to the deployed applications our customers receive (both internal and external), we designed the “Godec” framework, which allows us to combine components in a flexible graph, all in one single executable. This executable (or shared library, for embedding into existing projects) is intended to serve the needs of experimenters, developers and customers alike, as it can accommodate batch processing just as well as low-latency real-time applications. For example, the configuration for batch node transcription applications without any latency requirement may include steps such as speaker independent (SI) decoding, adaptation, and then speaker adaptive (SA) decoding. On the other hand, the configuration for processing broadcast media may include components such as speech activity detection, music separation, speaker clustering, etc. as well as the recognition components. Such a framework serves both the needs of application specific customization as well as the sharing of the same underlying software. The rest of the paper is organized as follows. In the next section, we describe the overall design of Sage. Then, we de- scribe the “Godec” framework in section 3. We report experimental results on different recognition tasks in section 4. The paper is then concluded in section 5. 2. Design The design of Sage aims to provide an interface to incorporate technologies from different projects. Sage has to be flexible enough to allow components to be easily interchanged, in order to shorten the time for prototyping. Also, technology transfer is critical and Sage should allow researchers to transfer the latest technologies to applications easily. Figure 1: An overview of Sage’s design Figure 1 is an overview of Sage’s design. At a high level, the Sage Core Library is an extension of BBN proprietary software and open source software including Kaldi. The design is carefully constructed so that updates from the open source projects could be easily transferred to Sage. Using the library, Sage provides the following services to meet the needs of both research and production, - Modular recipes - Python interface - Godec - an all-in-one streaming framework Both the modular design and Python interface are our attempts to enable fast prototyping, and Godec is a highly configurable and efficient message passing framework for fast technology transfer. More details of Godec are available in section 3. 2.1. Modular Recipes Open source projects often come with recipes to build systems on standard data sets. Those recipes are often in a form of separate shell scripts that are not modularized, making it difficult to maintain the recipes or create new recipes from the existing ones. We redesign the recipes into a modular form, in which each module represents a set of interdependent procedures that can be reused. Figure 2 is an example of Sage’s modular recipe that is created based on the Kaldi’s standard nnet1 and nnet2 recipes. Figure 2: An example of Sage’s modular recipe that is created based on Kaldi nnet1 (step 1-2) and nnet2 (step 3-5) recipes This modular design has three advantages. First, it allows regression tests for individual modules and makes it easier for code maintenance. Second, it enables more efficient code reuse and encourages researchers to exploit different recipes to create a better recipe. Third, this framework can bring in different open source technologies outside of the Sage project. These advantages are important for rapid and effective research and software development in a collaborative environment. 2.2. Python Interface As mentioned earlier, the rapid development of speech technologies has resulted in the proliferation of machine learning and neural network toolkits. Many of these tools are available in Python as open source packages. In order to enhance Sage with the powerful Python ecosystem, the Sage APIs are designed to be easily used to adopt new technologies. For example, through the Python Interface, Sage can integrate models trained by Tensorflow. As new technologies become available in Tensorflow, Sage would gain access to those technologies immediately without the need to reimplement them into our platform. This would greatly reduce the time and cost of exploring new techniques on the Sage platform. As a result, this design encourages and enables faster research and prototyping that would ultimately help advance the state-of-the-art in the field. Figure 3 shows a snippet of Python code where Sage decodes with a Tensorflow model. ```python import sys from pySageDecoder import PySageDecoder, PySageDecodable import tensorflow as tf if __name__ == '__main__': if len(sys.argv) < 2: sys.exit('expected arguments: bbn-decoder-args tf_model_file') tf_model_file = sys.argv.pop() tf_model_op = tf.load_model(tf_model_file) decoder = PySageDecoder() decoder.setup(sys.argv) while not decoder.done(): features = decoder.get_features() log_posterior = tf.eval(log_posterior(log_posterior)) decoder = decoder.decodeable decoder.next() decoder.finalize() ``` Figure 3: A snippet of Python code where Sage decodes with a Tensorflow model 3. Godec While Sage’s modularity and Python bindings are mostly geared towards enabling fast and flexible research, we also envisioned having an overarching framework that would allow for rapid transfer of advances in research, be flexible in its configuration, and yet carry little to no processing overhead. We call this framework “Godec” (Godec is our decoder), for which we identified the following specific requirements: - Single executable: Research experiments often create a multitude of small scripts and executables that are hard to transfer into a product. A single executable (or shared library to facilitate JNI and Python bindings) that is highly configurable through one central but modular configuration file speeds up transfer time. - Allow for submodules: As an extension to the above, the framework should allow for clustering of components into submodules that can be reused. • **Parallel processing**: The framework needs to be highly multi-threaded, with each major component running in its own thread, to make use of a CPU’s multiple cores. • **In-memory**: Unless explicitly desired, all intermediate data should be transferred in memory, reducing unnecessary disk I/O. • **Both batch and real-time**: The framework should allow for both streaming and batch input. • **Low latency**: In streaming input mode, the framework should be able to produce low-latency, real-time output. • **Stream-precise**: To allow for repeatable and deterministic offline experiments, the framework needs to be stream-precise, i.e. it needs to recreate the same conditions as during training, even when the input is streaming and the exact internal processing order might differ between otherwise identical runs. ### 3.1. Framework design From the above requirements, we designed a combination of a streaming and messaging network. In this network, components connect to each other via channels, with each component consuming and emitting distinct messages that account for sections of the stream. It is worth noting that a specific message can be consumed by as many components as desired; for example, multiple ASR decoders may operate on the same feature stream. This functionality also facilitates easy debugging, since one can just add an I/O component that “tees off” a certain stream and writes it to disk for detailed inspection. Similarly, it allows for convenient isolation of components during development, since one can simulate the rest of the network through an I/O component that feeds messages into the component to be developed. In such a massively multi-threaded framework, this kind of isolation is crucial for effective development and debugging. Figure 4 uses feature extraction as an example and shows how the messages are passed from one component to another. ### 3.2. Stream synchronization To achieve the above-mentioned “stream-precise” capability, for any given component, the incoming stream messages have to be perfectly synchronized. Unlike in a user interface (UI) framework where the exact time of processing a message (in relation to other ones) is not important as long as it happens fast, here we have to perfectly align the streams, otherwise experiments would not be deterministic. This is achieved by each message carrying a “stream time” counter which says how far this message accounts for in the overall stream. Note that the stream time is completely arbitrary and not globally enforced; usually the first feeding component creates it, and all downstream components work with that definition. One particular aspect of note is that all messages have to be causal, i.e. looking backwards in time. While this is an obvious requirement for feature and audio streams, it however disallows “utterance start/end” messages, since those messages would say “from here on X is true until further notice” instead of “up to this point X is true”. The reason for this is that one cannot be both low-latency and stream-precise when having non-causal messages. To illustrate, imagine a feature extraction component that processes an audio stream, but also gets utterance start/end messages from a Speech Activity Detector (SAD). If it got an utterance-start message and started processing all incoming audio from there on, the scenario could arise where the SAD is slow and issues an utterance-end message for an audio stream position the feature extractor has already gone past. This can cause potentially erroneous feature vectors since utterance ends often require special feature processing. To solve the problem, the feature extraction either would have to wait indefinitely until it sees the utterance-end message (thus dropping the low-latency capability since an utterance can be arbitrarily long), or create erroneous features (which would mean not being stream-precise). The key realization is that one cannot mix causal and noncausal messages when having both these requirements. Applying the requirement of causality to utterance start/end, we instead have “conversation state” messages which essentially say “up to here we are still within an utterance”. Similarly, something like an adaptation matrix message says “this adaptation matrix is valid up to here in the stream”. It is a subtle design decision, but crucial for the proper function of the network. ### 3.3. Stream slicing All components inherit from a common base class that takes care of the synchronization of the incoming messages. In particular, unlike truly asynchronous messaging frameworks, a component will not process small updates to just one of its input streams, but rather wait until it has a contiguous chunk in time that spans all incoming streams. There are several benefits: - Developers of a new component do not have to worry about the asynchronous nature of the framework. The component code only sees a solid chunk in time covering all streams. - The base class can ensure to slice the chunks so that the chunk is “atomic”, e.g. so that it does not contain two separate utterances. This again reduces a major source of errors for the developer. Figure 5 illustrates such a chunk slicing for one component. Figure 5: Slicing out a contiguous chunk from streams queued up in front of a component. Top numbers are stream time. 4. Performance and Benchmarking We evaluated the performance of Sage using a variety of languages and training conditions. In addition to word error rate (WER), we also consider the real-time factor and memory footprint, which are important constraints for real world applications. Table 1 summarizes the data we used in this evaluation. For English, we have two training procedures: the first one used the Switchboard train set that consists of around 370 hours of data, and the second one includes also the Fisher data and the total size of the train set is over 2300 hours. Both English systems use the Switchboard portion of Hub5 2000 evaluation set as the test set. The Russian data comes from a multi-lingual corpus as described in [9]. In contrast to the English data, the Russian train set is very small, which consists of only 50 hours of training data. This condition is similar to the IARPA Babel project [10] so we could test Sage’s performance under low resource condition. The Mandarin data set consists of Mandarin Callhome(LDC96S34), Callfriend(LDC96S55,LDC96S56) and HKUST(LDC2005S15) corpora. All the data sets we used in our experiments are conversational telephone speech (CTS). <table> <thead> <tr> <th>Language</th> <th>Channel</th> <th>Train set</th> <th>Test set</th> </tr> </thead> <tbody> <tr> <td>English</td> <td>CTS</td> <td>370-hr/2300-hr</td> <td>2-hr</td> </tr> <tr> <td>Russian</td> <td>CTS</td> <td>50-hr</td> <td>4-hr</td> </tr> <tr> <td>Mandarin</td> <td>CTS</td> <td>250-hr</td> <td>3-hr</td> </tr> </tbody> </table> We first compared the modular recipe with an open source recipe in Kaldi. This recipe trains a time delay neural network (TDNN) using Switchboard data [11]. The TDNN consists of 4 hidden layers using P-norm as an activation function. The input to the TDNN consists of MFCC and I-vector features. Table 2 shows the results of modular and open source recipe on the Switchboard test set, and they are consistent. <table> <thead> <tr> <th>Language</th> <th>Model(tool)</th> <th>Recipe</th> <th>WER(%)</th> </tr> </thead> <tbody> <tr> <td>English</td> <td>TDNN</td> <td>Open source</td> <td>14.0</td> </tr> <tr> <td>English</td> <td>TDNN</td> <td>Modular</td> <td>14.0</td> </tr> </tbody> </table> We evaluated the speed and memory footprint of Sage’s decoding pipeline. To evaluate the performance, we used the 2300 hours English system. This system adopts two-pass decoding where it uses a Gaussian mixture model for SI decoding and a DNN for SA decoding. The DNN consists of 6 layers and each layer has 2048 sigmoid units. The input to this DNN is the spliced bottleneck features trained on the same data with FM-LLR for speaker adaptation. Table 4 shows the real-time factor and also the memory consumption of two operating points. This result shows that we could build a high performance STT system running at real-time with only 3GB of memory, which has only little degradation compared to the research system. <table> <thead> <tr> <th>Language</th> <th>10x RT</th> <th>1x RT</th> </tr> </thead> <tbody> <tr> <td>English(2300-hr)</td> <td>9.5% (36GB)</td> <td>10.8% (3GB)</td> </tr> </tbody> </table> 5. Conclusions In this paper, we introduce Sage - the latest BBN speech processing platform. The design of Sage aims to satisfy the needs of both research and production. Through its modular design and Python interface, Sage can take advantage of many open source toolkits, each of which has its own strengths. This design allows researchers to quickly experiment with new technologies, and ultimately reduces the cost of prototyping. With Sage, we also introduce Godec, which is an all-in-one streaming framework aimed to support various applications. In this paper, we also show how Sage can combine different open source recipes to create a better system. To demonstrate Sage’s capability as a production system, we built a high performance English system and showed that it can run in real-time with a modest amount of memory consumption. 6. References
{"Source-Url": "http://www.isca-speech.org/archive/Interspeech_2016/pdfs/1031.PDF", "len_cl100k_base": 4205, "olmocr-version": "0.1.50", "pdf-total-pages": 5, "total-fallback-pages": 0, "total-input-tokens": 15645, "total-output-tokens": 5665, "length": "2e12", "weborganizer": {"__label__adult": 0.0005440711975097656, "__label__art_design": 0.0004363059997558594, "__label__crime_law": 0.000640869140625, "__label__education_jobs": 0.0005903244018554688, "__label__entertainment": 0.00020241737365722656, "__label__fashion_beauty": 0.00021660327911376953, "__label__finance_business": 0.00021529197692871096, "__label__food_dining": 0.0004963874816894531, "__label__games": 0.0006322860717773438, "__label__hardware": 0.002017974853515625, "__label__health": 0.0013065338134765625, "__label__history": 0.00023829936981201172, "__label__home_hobbies": 8.392333984375e-05, "__label__industrial": 0.0005745887756347656, "__label__literature": 0.0003979206085205078, "__label__politics": 0.0005092620849609375, "__label__religion": 0.0007047653198242188, "__label__science_tech": 0.126220703125, "__label__social_life": 0.0001418590545654297, "__label__software": 0.013153076171875, "__label__software_dev": 0.849609375, "__label__sports_fitness": 0.0004091262817382813, "__label__transportation": 0.0004968643188476562, "__label__travel": 0.00020766258239746096}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 23327, 0.02523]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 23327, 0.49874]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 23327, 0.88373]], "google_gemma-3-12b-it_contains_pii": [[0, 5660, false], [5660, 10631, null], [10631, 15820, null], [15820, 19714, null], [19714, 23327, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5660, true], [5660, 10631, null], [10631, 15820, null], [15820, 19714, null], [19714, 23327, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 23327, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 23327, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 23327, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 23327, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 23327, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 23327, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 23327, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 23327, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 23327, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 23327, null]], "pdf_page_numbers": [[0, 5660, 1], [5660, 10631, 2], [10631, 15820, 3], [15820, 19714, 4], [19714, 23327, 5]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 23327, 0.11429]]}
olmocr_science_pdfs
2024-11-28
2024-11-28
4512d95193fbbd35d4d93443d86fb7c329ff55da
Tracing Back Log Data to its Log Statement: From Research to Practice Schipper, Daan; Aniche, Maurício; van Deursen, Arie Publication date 2019 Document Version Submitted manuscript Published in Proceedings of the 16th International Conference on Mining Software Repositories Citation (APA) Important note To cite this publication, please use the final published version (if applicable). Please check the document version above. Copyright Other than for strictly personal use, it is not permitted to download, forward or distribute the text or part of it, without the consent of the author(s) and/or copyright holder(s), unless the work is under an open content license such as Creative Commons. Takedown policy Please contact us and provide details if you believe this document breaches copyrights. We will remove access to the work immediately and investigate your claim. Tracing Back Log Data to its Log Statement: From Research to Practice Daan Schipper Adyen N.V. Amsterdam, The Netherlands daan.schipper@adyen.com Mauricio Aniche Software Engineering Research Group Delft University of Technology Delft, The Netherlands m.f.aniche@tudelft.nl Arie van Deursen Software Engineering Research Group Delft University of Technology Delft, The Netherlands arie.vandeursen@tudelft.nl Abstract—Logs are widely used as a source of information to understand the activity of computer systems and to monitor their health and stability. However, most log analysis techniques require the link between the log messages in the raw log file and the log statements in the source code that produce them. Several solutions have been proposed to solve this non-trivial challenge, of which the approach based on static analysis reaches the highest accuracy. We, at Adyen, implemented the state-of-the-art research on log parsing in our logging environment and evaluated their accuracy and performance. Our results show that, with some adaptation, the current static analysis techniques are highly efficient and performant. In other words, ready for use. Index Terms—software engineering, runtime monitoring, log parsing. I. INTRODUCTION Logs record runtime information of computer systems and produce timestamped documentation of events, states and interactions of components. The information gained from logging is used to perform root cause analysis on identified problems, which consists mostly of manual labour. Overall, a log entry is produced by a log printing statement in a system program’s source code. Techniques have been developed to relieve this manual work and to take advantage of the rich information present in logs in an automated manner, such as process mining [8], [12], [25], anomaly detection [6], [10], [11], [28], [27], fault localisation [26], [32], invariant inference [7], performance diagnosis [15], [20], [22], [31], online trace checking [5], and behaviour analysis [21], [29]. In practice, as soon as developers learn something from these log analysis techniques, they often want to go back to the log statement in the source code that produced the log message they just analysed. However, tracing back log messages to their origin is a non-trivial challenge in large-scale systems. While frameworks like Log4j [3] enable developers to print the class name and line number of log statements together with the log message, collecting this information in a production environment at every log statement comes with a loss of performance. Behind the scenes, Log4j collects the log statement line by throwing an exception and capturing the generated stack trace[1]. As there is no direct connection between log messages and source code in the produced (raw) log data, the link must be created afterwards. Previous works propose several approaches based on clustering [10], [23], heuristics [17], [24], longest common sequence method [9], textual similarities [14], evolutionary search [18], and static analysis [28] to solve this challenge. We at Adyen, a payment service provider operating globally and providing over 250 different payment methods, decided to derive an approach based on the state-of-the-art research and apply it in our logging systems. We evaluate our implementation on a dataset consisting of 100,000 log lines, taken directly from our production servers. Our results show that 97.6% of the links were correctly determined (CI=5%, CL=95%). As a consequence, we believe that state-of-the-art research is ready for the real world. This paper makes the following contributions: 1) The description of the architecture as well as the challenges we faced to implement state-of-the-art research on linking log data to their original log statement at Adyen, a large-scale software system. 2) Empirical evidence that Xu et al.’s [28] approach to link log lines to their original log statements works effectively in an industry setting. II. RELATED WORK Typically a log message consists of a constant part, which remains the same for every event occurrence, and a variable part containing dynamic information, which is determined during runtime. The goal of log parsing is to separate the constant and variable parts within a log message. As parsing is the basis for many log analysis techniques, log parsing is an active research area, as shown in the introduction. He et al. [13] performed an evaluation study on the most popular clustering-based methods and found, despite achieving high accuracy, that SLCT [24] and IPLoM [17] do not scale well with the volume of logs, since the clusters are constructed according to the difference in the messages. Furthermore, offline log parsing methods are limited by the memory of a single computer. Therefore, He et al. [14] propose an online method that parses raw log messages in a streaming manner, outperforming previous methods [9], [10], [19], [17]. Another --- [1]Log4j’s developers have experimented with other alternatives, but so far, this is the most efficient way. See https://issues.apache.org/jira/browse/LOG4J2-1029. finding of clustering based methods is that the overall accuracy is improved when log messages are preprocessed with some domain knowledge-based rules to remove obvious numerical parameters, such as numbers, memory and IP addresses [13]. Although beneficial to the effectiveness of the log parsing, this is a manual process. Messaoudi et al. [18] capture the template of a message by applying an evolutionary algorithm. This first of a kind approach significantly outperforming other approaches ([13], [17]). However, approaches based on static analysis have an additional source of information available, the source code itself. Templates are extracted from the logging statements which are then used to match log messages with. This extra knowledge additionally allows the techniques to be completely automated, thus eliminating the need for manual work. Examples of such an approach can be found in Xu et al. [28] and Zhao et al. [30], where authors parse the source code, extract regular expression templates out of the log statements, and match them to the log messages they observe in their log systems. III. FROM RESEARCH TO PRACTICE: OUR APPROACH The overview of the approach is shown in Figure 1, where a square represents a process, and a hexagon represents input or output. All these steps are done automatically by our tool (that we will make available at https://github.com/SERG-Delft/msr19-logs). We start by identifying log statements in the source code, for which we traverse the abstract syntax tree (AST), and analyze nodes related to log statements. Next, we extract a template from the statement along with its severity level and class name. We construct a template in the form of a regular expression that matches all possible log messages produced by it. We then enrich the templates with type analysis information such as the textual representation of objects and type hierarchies to make the templates more precise. To make the templates easily searchable, we conclude this phase by creating an index of the templates. With this template database at hand we then find, for each log message that comes to our production systems, the regular expressions that match, and select the one that has the highest similarity to the constant part of the log message. In the following, we describe each part of our approach in detail. a) Identify Log Statements: We parse the source code to an AST to programmatically search the source code for statements corresponding to log statements. Our implementation uses JavaParser [2], a simple and lightweight AST library. In order to analyze the log statements, we iterate over the individual nodes to find those that represent log statements. Previous work by Zhao et al. [30] identifies log statements by searching for method calls corresponding to the standard logging methods, such as those defined by Log4j [3] (e.g., log.info() and log.warn()). In practice we had to extend this; companies like Adyen create their own logging libraries suited for their needs (e.g., to automatically log transaction IDs). b) Create Template: We construct templates based on the arguments of the log statement; a template that would match any message generated by it. These templates are then used to match the log messages with, providing the trace back to the log statement in the source code. Note that a more precise template will more accurately match the log messages. However, in practice, the arguments of a log statement have restrictions: developers can construct the argument in every way imaginable, as long as it follows the language specification (e.g., messages that contain integers, doubles, Strings, etc). Even non-primitive objects with a custom textual representation can be included. In other words, arguments can vary from a simple literal expression to an interpolation of primitive types together with objects, which all are converted to a single line of text during runtime. We apply static analysis to create templates based on the arguments of the logging statement. Any literal expression is directly copied to the regular expression, while runtime variables are replaced by wildcards (often enhanced by the type of the variable). Suppose we have the following log statement with mixed expressions: log.info("average = " + avg), where "average = " is a String, avg is of type double, and everything is concatenated together, forming a single String. The AST, in a simplified view, contains three types of nodes: one representing the String, one representing the concatenation (+), and one representing the double value. Our approach recognizes the first literal string and copy it directly to the template; then it recognizes the double variable, and it generates a wildcard for double numbers. The final regular expression for that log statement is then average = .*[double]. c) Enrich templates: While capturing the type of primitive variables and generating proper regular expressions for them is trivial, finding a precise regular expression for an object requires more work. In Java, objects are transformed to a String through the toString() method, which exists in any Java object. The toString() method is often overridden by developers, so that objects print useful information. Following the approach of Xu et al. [28], whenever we notice an object as an argument in a log statement, we try to infer its regular expression based on its toString() implementation. We apply it recursively, as an object’s toString() method can also print another object. If no toString() implementation is found, we replace the object with a generic wildcard “.*”. Given that the real type of the object is only known at runtime (i.e., polymorphism), we create one template for each sub-class of the argument’s type in the log statement. Each template contains a regular expression extracted from a sub-class implementation of the toString() method. d) Create Index: Scanning the entire (extensive) template database to find a match for each log message is unfeasible. To solve the problem, we compile the constant part of all templates into a reverse index [4] to make them searchable. Then we query this index to retrieve a set of similar templates based on TF-IDF [16] of the constant part, which has a higher possibility of matching. Implementation-wise, we use Apache Lucene [11] to index the templates, following the approach by Xu et al. [28]. IV. EMPIRICAL STUDY In this section, we evaluate the effectiveness of linking log data to its log statement in the source code with static analysis regarding accuracy and performance. To that aim, we propose the following research questions: **RQ_1**: What is the accuracy of the approach when dealing with extensive log data? **RQ_2**: What is the performance of our approach? A. Studied Sample We evaluate the effectiveness of the approach in real life conditions and will use log data taken directly from the production servers of Adyen. The logs are produced by a software system which has the purpose of processing payments from all over the world. At the moment of writing the codebase consists of millions of lines of code written by over 150 developers. Of those lines, approximately tens of thousands of log statements generate log messages. The percentage of lines of log statements is on the lower end compared to that of other systems, normally about 1%-5% [23], as developers try to be as efficient as possible in their logging. The dataset used to evaluate the approach consists of logs produced during normal operations, and no filtering was applied to the messages. We obtained 100,000 messages from a normal (i.e. non-holiday) weekday. B. Methodology To answer RQ_1, we match the log messages from the dataset to the source code and evaluate whether the link provided by the approach is indeed correct. In the 100,000 messages in our sample, our approach generates 676 links (i.e., connected the log messages to 676 different log statements in the source code). To identify whether the link was correctly made, we manually analyze a statistically significant sample of 245 links, with a confidence level of 95% and confidence interval of 5%. For each link, we select one random matched message to evaluate the link. More specifically, we check whether the statement could have produced the message by taking into account the structure of the message, the severity, and the accompanying class name. Furthermore, we evaluate the log messages of which the approach provides a link to an incorrect log statement. We manually inspect these log messages to inspect why the approach was unable to provide a correct link. We explain and show the underlying cause for the misidentified messages. To answer RQ_2, we apply the approach ten times on the dataset and measure the performance to eliminate any bias of external programs influencing the execution time. The machine used has two cores @ 3.1GHz from a Intel Core i7 CPU, and 16GB RAM. We analyze the execution time per individual step of the creation process and report the mean execution time of the ten runs. Finally, we link the log messages from the dataset to the templates and analyze the execution time needed per individual log message. We evaluate the distribution of the execution time according to the mean, quartiles, and quantiles. C. Results 1) **RQ_1**: What is the accuracy of the approach when dealing with extensive log data?: Overall, the approach achieves 97.6% accuracy (239 out of 245 analyzed log statements) on tracing back the origin of log data to its log statement in the source code. All but two log messages have been linked to log statements in the source code. These two failures can be explained by the fact that they have been both produced by the same log statement, which logs a message that is too large (approximately 17k characters) to be handled by our logging facilities. This log statement has already been modified in a future release. Out of the 676 log statement identified as the source of all log messages, six of those have proven to be incorrect. The misidentifications occur due to the following underlying causes: **JSON-based logs**: Before querying the index, we strip the JSON data out of the message since we consider this to be variable information. Therefore, when the message consists of JSON data only, the resulting query is an empty string. We also observed our tool failing due to bad JSON stripping. In future versions, we should propose better ways to deal with JSON-only log messages. **Unknown logging method:** Adyen also uses custom-made logging methods to construct logs in specific formats. Since our implementation was unaware of them, no templates were created for log statements using these methods. However, since the implementation is easily configurable, these logging methods can be added in future versions. **Inaccuracies in the creation process of templates:** The approach uses static analysis to create templates of log statements that predict what the messages will look like at runtime. Unfortunately, not all predictions are completely accurate. The inaccuracy often happens when the message is constructed outside the log statement itself, e.g., String logMsg = "..." + variable; log.info(logMsg); 2) *RQ2. What is the performance of our approach?* Table I shows the execution time per individual process of the template creation process at Adyen’s codebase. The total execution time took on average approximately 40 minutes across all ten runs. Most of this time is spent searching the codebase for methods that correspond to log statements, on average 92.1%. The actual execution time of creating indexing templates only takes 3 minutes and 16 seconds, around 7.9% of the total execution time. The results are in line with a similar approach by Zhao et al. [30], whose static analysis takes less than two minutes to run for systems ranging from 100.000 to 300.000 lines of code. In the matching process, the median execution time to process a single log message is only 4 milliseconds. Table II details the statistics, which shows that for 99% of the log messages are processed in under 132ms. However, the total execution time to process all log messages is 01h13m19.969, which is much higher than expected. We observed that the maximum time to process a single log message is exceptionally high: 02m19.922, or 35,000 times the median. The approach derived an incorrect template from the statement in question. Two wildcards are missing from the template, which results in a template not able to match the log messages produced by the statement. This results that all templates are evaluated to try to find a matching log statement for this specific message, thus causing such a long execution time. Therefore, it is most important to create as precise as possible templates which significantly reduces the time needed to match the log messages. Given this finding, we implemented a fail-safe mechanism in our approach so that it gives up if the search for a matching template takes too long. **Threats to Validity.** Our data sample is collected from a single random day. This sample exercises 676 different log statements of our system. After manually analyzing these log statements, we observe that log statements were quite diverse in terms of the number of literals, variables, variable types, and importance to our system. Therefore, while a replication would strengthen the validity of our findings, our results already give us a high degree of certainty and interesting insights. V. CONCLUSION This paper presented our implementation of the state-of-the-art research on log parsing and its evaluation for Adyen’s large-scale software system. Our results show that our approach (and consequently, the state-of-the-art research) is highly effective in tracing back the origin of log data to its log statement in the source code, on average in 4 milliseconds per log message and with an accuracy of 97.6% (CL=95%, CI=5%). We thus believe that state-of-the-art research is ready for the real world. We also learned that, for such state-of-the-art research to be applied in companies, implementations have to be: - **Non-intrusive:** Companies will not afford changes in their existing source code for any technique to work. It also cannot have any negative impact on the performance of the software. In our implementation, our parser makes sure it understands the specifics of the source code, and all the parsing, template enriching, and matching process happen on separate machines. - **Adaptable:** Companies have their logging utilities, and tooling needs to adapt to it. Our implementation provides an easy way for developers to add support for different log libraries. - **Extendable:** Complex software makes use of operations other than simple concatenation to build a log statement. Our tool currently supports log messages consisting of any combination of primitive objects, non-primitive objects (including class polymorphism), formatted strings and referenced strings for Java. In the future, we plan to provide better JSON support as well as a more complex log building code. **Acknowledgments** This work is partially funded by the research projects STAMP ICT-16-10 No. 731529 (EC H2020) and NWO EW MIPL No. 628.008.003. REFERENCES
{"Source-Url": "https://pure.tudelft.nl/portal/files/52060635/paper.pdf", "len_cl100k_base": 4367, "olmocr-version": "0.1.50", "pdf-total-pages": 6, "total-fallback-pages": 0, "total-input-tokens": 18452, "total-output-tokens": 7066, "length": "2e12", "weborganizer": {"__label__adult": 0.0002593994140625, "__label__art_design": 0.0001931190490722656, "__label__crime_law": 0.0003046989440917969, "__label__education_jobs": 0.0005011558532714844, "__label__entertainment": 4.172325134277344e-05, "__label__fashion_beauty": 0.00011545419692993164, "__label__finance_business": 0.00017178058624267578, "__label__food_dining": 0.00021588802337646484, "__label__games": 0.0003275871276855469, "__label__hardware": 0.00063323974609375, "__label__health": 0.00032711029052734375, "__label__history": 0.00014722347259521484, "__label__home_hobbies": 6.473064422607422e-05, "__label__industrial": 0.00023794174194335935, "__label__literature": 0.0001671314239501953, "__label__politics": 0.0001556873321533203, "__label__religion": 0.0002808570861816406, "__label__science_tech": 0.01010894775390625, "__label__social_life": 7.432699203491211e-05, "__label__software": 0.00647735595703125, "__label__software_dev": 0.978515625, "__label__sports_fitness": 0.0002123117446899414, "__label__transportation": 0.0003020763397216797, "__label__travel": 0.00014591217041015625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 28165, 0.03471]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 28165, 0.17312]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 28165, 0.87277]], "google_gemma-3-12b-it_contains_pii": [[0, 1089, false], [1089, 6251, null], [6251, 12678, null], [12678, 16660, null], [16660, 21598, null], [21598, 28165, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1089, true], [1089, 6251, null], [6251, 12678, null], [12678, 16660, null], [16660, 21598, null], [21598, 28165, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 28165, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 28165, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 28165, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 28165, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 28165, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 28165, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 28165, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 28165, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 28165, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 28165, null]], "pdf_page_numbers": [[0, 1089, 1], [1089, 6251, 2], [6251, 12678, 3], [12678, 16660, 4], [16660, 21598, 5], [21598, 28165, 6]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 28165, 0.0]]}
olmocr_science_pdfs
2024-11-28
2024-11-28
c55cb7138f63fbd3c368e2dda0b00232e3953e2b
Heuristics for Efficient SAT Solving As implemented in GRASP, Chaff and GSAT. The $K$-Coloring problem: Given an undirected graph $G(V,E)$ and a natural number $k$, is there an assignment $\text{color}$: \[ V \rightarrow \{1, \ldots, k\} \text{ s.t. } \forall i, j, (i, j) \in E, \text{color}(i) \neq \text{color}(j) \] Formulation of famous problems as SAT: $k$-Coloring (2/2) $x_{i,j} =$ node $i$ is assigned the ‘color’ $j$ ($1 \leq i \leq n$, $1 \leq j \leq k$) **Constraints:** i) At least one color to each node: $(x_{1,1} \lor x_{1,2} \lor \ldots x_{1,k} \lor \ldots)$ \[ \bigwedge_{i=1}^{n} \bigvee_{j=1}^{k} (x_{i,j}) \] ii) At most one color to each node: \[ \forall \forall \forall (\neg x_{i,j} \lor \neg x_{i,t}) \] iii) Coloring constraints: \[ \forall \forall \forall (i, j) \in E. (\neg x_{i,c} \lor \neg x_{j,c}) \] Given a property $p$: (e.g. “always signal_a = signal_b”) Is there a state reachable within $k$ cycles, which satisfies $\neg p$ ? The reachable states in $k$ steps are captured by: $$I(s_0) \land \rho(s_0, s_1) \land \rho(s_1, s_2) \land \ldots \land \rho(s_{k-1}, s_k)$$ The property $p$ fails in one of the cycles $1..k$: $$\neg p_1 \lor \neg p_2 \lor \ldots \lor \neg p_k$$ The safety property $p$ is valid up to cycle $k$ iff $\Omega(k)$ is unsatisfiable: $$\Omega(k): \quad I_0 \land \bigwedge_{i=0}^{k-1} \rho(s_i, s_{i+1}) \land \bigvee_{i=0}^{k} \neg p_i$$ Formulation of famous problems as SAT: *Bounded Model Checking (3/4)* Formulation of famous problems as SAT: Bounded Model Checking (4/4) Example: a two bit counter Initial state: $I_0: \neg l \land \neg r$ Transition: $\rho: l' = (l \neq r), r' = \neg r$ Property: always $(\neg l \lor \neg r)$. For $k = 2$: $\varphi: (\neg l_0 \land \neg r_0) \land \begin{align*} \ell_1 &= (l_0 \neq r_0) \land r_1 = \neg r_0 \\ \ell_2 &= (l_1 \neq r_1) \land r_2 = \neg r_1 \end{align*}$ For $k = 2$, $\Omega(k)$ is unsatisfiable. For $k = 4$ $\Omega(k)$ is satisfiable What is SAT? Given a propositional formula in CNF, find an assignment to Boolean variables that makes the formula true: \[ \omega_1 = (x_2 \lor x_3) \] \[ \omega_2 = (\neg x_1 \lor \neg x_4) \] \[ \omega_3 = (\neg x_2 \lor x_4) \] \[ A = \{ x_1=0, x_2=1, x_3=0, x_4=1 \} \] Why SAT? - Fundamental problem from theoretical point of view - Numerous applications: - CAD, VLSI - Optimization - Bounded Model Checking and other type of formal verification - AI, planning, automated deduction A Basic SAT algorithm Given $\varphi$ in CNF: $(x,y,z),(-x,y),(-y,z),(-x,-y,-z)$ Decision tree: - $x$: $(y),(-y,z),(-y,-z)$ - $y$: $(z),(-z)$ - $z$: $(y),(-y)$ - $-x$: $(y,z),(-y,z)$ - $y$: $(z),(-z)$ - $z$: $(y),(-y)$ Resolve Conflict: - $x$: $y$ is decided as $1$ - $-x$: $y$ is decided as $0$ A Basic SAT algorithm While (true) { if (!Decide()) return (SAT); while (!Deduce()) if (!Resolve_Conflict()) return (UNSAT); } Choose the next variable and value. Return False if all variables are assigned Apply unit clause rule. Return False if reached a conflict Backtrack until no conflict. Return False if impossible Basic Backtracking Search - Organize the search in the form of a decision tree - Each node corresponds to a decision - Depth of the node in the decision tree $\rightarrow$ decision level - Notation: $x=\nu@d$ $x \in \{0,1\}$ is assigned to $\nu$ at decision level $d$ Backtracking Search in Action \[ \omega_1 = (x_2 \lor x_3) \] \[ \omega_2 = (\neg x_1 \lor \neg x_4) \] \[ \omega_3 = (\neg x_2 \lor x_4) \] \[ x_1 = 0 \iff 1 \] \[ x_2 = 0 \iff 2 \] \[ x_3 = 1 \iff 2 \] \[ x_4 = 0 \iff 1 \] \{ (x_1, 0), (x_2, 0), (x_3, 1) \} \{ (x_1, 1), (x_2, 0), (x_3, 1), (x_4, 0) \} No backtrack in this example! Backtracking Search in Action Add a clause \( \omega_1 = (x_2 \lor x_3) \) \( \omega_2 = (\neg x_1 \lor \neg x_4) \) \( \omega_3 = (\neg x_2 \lor x_4) \) \( \omega_4 = (\neg x_1 \lor x_2 \lor \neg x_3) \) \( x_2 = 0 @ 2 \Rightarrow x_3 = 1 @ 2 \) \{(x_1,0), (x_2,0), (x_3,1)\} \begin{align*} x_1 &= 1 @ 1 \\ \Rightarrow x_4 &= 0 @ 1 \\ \Rightarrow x_2 &= 0 @ 1 \\ \Rightarrow x_3 &= 1 @ 1 \end{align*} **Decision heuristics** - **DLIS** (Dynamic Largest Individual Sum) - For a given variable $x$: - $C_{x,p}$ – # unresolved clauses in which $x$ appears positively - $C_{x,n}$ – # unresolved clauses in which $x$ appears negatively - Let $x$ be the literal for which $C_{x,p}$ is maximal - Let $y$ be the literal for which $C_{y,n}$ is maximal - If $C_{x,p} > C_{y,n}$ choose $x$ and assign it TRUE - Otherwise choose $y$ and assign it FALSE - Requires $l$ (#literals) queries for each decision. - (Implemented in e.g. Grasp) Decision heuristics Jeroslow-Wang method Compute for every clause \( \omega \) and every variable \( l \) (in each phase): - \( J(l) := \sum_{l \in \omega, \omega \in \varphi} 2^{-|\omega|} \) - Choose a variable \( l \) that maximizes \( J(l) \). - This gives an exponentially higher weight to literals in shorter clauses. Decision heuristics MOM (Maximum Occurrence of clauses of Minimum size). - Let $f^*(x)$ be the # of unresolved smallest clauses containing $x$. Choose $x$ that maximizes: \[ ((f^*(x) + f^!(x)) \times 2^k + f^*(x) \times f^!(x) \] - $k$ is chosen heuristically. - The idea: - Give preference to satisfying small clauses. - Among those, give preference to balanced variables (e.g. $f^*(x) = 3$, $f^!(x) = 3$ is better than $f^*(x) = 1$, $f^!(x) = 5$). Decision heuristics **VSIDS** (Variable State Independent Decaying Sum) 1. Each variable in each polarity has a counter initialized to 0. 2. When a clause is added, the counters are updated. 3. The unassigned variable with the highest counter is chosen. 4. Periodically, all the counters are divided by a constant. (Implemented in **Chaff**) Decision heuristics VSIDS (cont’d) • **Chaff** holds a list of unassigned variables sorted by the counter value. • Updates are needed only when adding conflict clauses. • Thus - decision is made in constant time. Decision heuristics VSIDS is a ‘quasi-static’ strategy: - static because it doesn’t depend on current assignment - dynamic because it gradually changes. Variables that appear in recent conflicts have higher priority. This strategy is a conflict-driven decision strategy. “..employing this strategy dramatically (i.e. an order of magnitude) improved performance ... “ Variable ordering (Abstract dependency graphs) A (CNF) dependency graph $D (V,E)$: A partitioning $C_1..C_n$: An *abstract* dependency graph $D'(V', E')$: Variable ordering (The natural order of $\Omega(k)$) For $\Omega(k)$ there exists a partition $C_1..C_n$ s.t. the abstract dependency graph is linear $$\Omega(k) : \quad I(s_0) \land \bigwedge_{i=1}^{k-1} \rho(s_i, s_{i+1}) \land \neg p(s_k)$$ Variable ordering (\(\Omega(k)\) should satisfy \(I_0\)) Riding on unreachable states... \(\neg P_k\) Riding on legal executions... \(\Omega(k)\) should satisfy \(\neg P_k\) Implication graphs and learning Current truth assignment: \{x_9 = 0 @ 1, x_{10} = 0 @ 3, x_{11} = 0 @ 3, x_{12} = 1 @ 2, x_{13} = 1 @ 2\} Current decision assignment: \{x_1 = 1 @ 6\} \begin{align*} \omega_1 &= \neg x_1 \lor x_2 \\ \omega_2 &= \neg x_1 \lor x_3 \lor x_9 \\ \omega_3 &= \neg x_2 \lor \neg x_3 \lor x_4 \\ \omega_4 &= \neg x_4 \lor x_5 \lor x_{10} \\ \omega_5 &= \neg x_4 \lor x_6 \lor x_{11} \\ \omega_6 &= \neg x_5 \lor \neg x_6 \\ \omega_7 &= x_1 \lor x_7 \lor \neg x_{12} \\ \omega_8 &= x_1 \lor x_8 \\ \omega_9 &= \neg x_7 \lor \neg x_8 \lor \neg x_{13} \end{align*} We learn the conflict clause \(\omega_{10} : (\neg x_1 \lor x_9 \lor x_{11} \lor x_{10})\) Implication graph, flipped assignment \( \omega_1 = (\neg x_1 \lor x_2) \) \( \omega_2 = (\neg x_1 \lor x_3 \lor x_9) \) \( \omega_3 = (\neg x_2 \lor \neg x_3 \lor x_4) \) \( \omega_4 = (\neg x_4 \lor x_5 \lor x_{10}) \) \( \omega_5 = (\neg x_4 \lor x_6 \lor x_{11}) \) \( \omega_6 = (\neg x_5 \lor x_6) \) \( \omega_7 = (x_1 \lor x_7 \lor \neg x_{12}) \) \( \omega_8 = (x_1 \lor x_8) \) \( \omega_9 = (\neg x_7 \lor \neg x_8 \lor \neg x_{13}) \) \( \omega_{10} : (\neg x_1 \lor x_9 \lor x_{11} \lor x_{10}) \) Non-chronological backtracking Which assignments caused the conflicts? \[ \begin{align*} x_9 &= 0 @ 1 \\ x_{10} &= 0 @ 3 \\ x_{11} &= 0 @ 3 \\ x_{12} &= 1 @ 2 \\ x_{13} &= 1 @ 2 \end{align*} \] These assignments are sufficient for causing a conflict. Backtrack to decision level 3 More engineering aspects of SAT solvers Observation: More than 90% of the time SAT solvers perform Deduction(). Deduction() allocates new implied variables and conflicts. How can this be done efficiently? Grasp implements Deduction() with counters Hold 2 counters for each clause $\pi$: $val1(\pi)$ - \# of \underline{negative} literals assigned 0 in $\pi$ + \# of \underline{positive} literals assigned 1 in $\pi$. $val0(\pi)$ - \# of \underline{negative} literals assigned 1 in $\pi$ + \# of \underline{positive} literals assigned 0 in $\pi$. **Grasp** implements Deduction() with counters \[ \begin{align*} \pi \text{ is satisfied} & \quad \text{iff} \quad \text{val}_1(\pi) > 0 \\ \pi \text{ is unsatisfied} & \quad \text{iff} \quad \text{val}_0(\pi) = |\pi| \\ \pi \text{ is unit} & \quad \text{iff} \quad \text{val}_1(\pi) = 0 \land \text{val}_0(\pi) = |\pi| - 1 \\ \pi \text{ is unresolved} & \quad \text{iff} \quad \text{val}_1(\pi) = 0 \land \text{val}_0(\pi) < |\pi| - 1 \\ \end{align*} \] Every assignment to a variable \(x\) results in updating the counters for all the clauses that contain \(x\). **Backtracking:** Same complexity. Chaff implements Deduction() with a pair of observers - Observation: during Deduction(), we are only interested in newly implied variables and conflicts. - These occur only when the number of literals in $\pi$ with value ‘false’ is greater than $|\pi| - 2$ - Conclusion: no need to visit a clause unless $(\text{val0} (\pi) > |\pi| - 2)$ - How can this be implemented? Chaff implements Deduction() with a pair of observers - Define two ‘observers’: $O1(\pi)$, $O2(\pi)$. - $O1(\pi)$ and $O2(\pi)$ point to two distinct $\pi$ literals which are not ‘false’. - $\pi$ becomes *unit* if updating one observer leads to $O1(\pi) = O2(\pi)$. - Visit clause $\pi$ only if $O1(\pi)$ or $O2(\pi)$ become ‘false’. Both observers of an implied clause are on the highest decision level present in the clause. Therefore, backtracking will un-assign them first. Conclusion: when backtracking, observers stay in place. Backtracking: No updating. Complexity = constant. Chaff implements Deduction() with a pair of observers The choice of observing literals is important. Best strategy is - the least frequently updated variables. The observers method has a learning curve in this respect: 1. The initial observers are chosen arbitrarily. 2. The process shifts the observers away from variables that were recently updated (these variables will most probably be reassigned in a short time). In our example: the next time v[5] is updated, it will point to a significantly smaller set of clauses. Given a CNF formula $\alpha$, choose \texttt{max\_tries} and \texttt{max\_flips} \begin{verbatim} for i = 1 to \texttt{max\_tries} { T := randomly generated truth assignment for j = 1 to \texttt{max\_flips} { if T satisfies $\alpha$ return TRUE choose v s.t. flipping v's value gives largest increase in the \# of satisfied clauses (break ties randomly). T := T with v's assignment flipped. } } \end{verbatim} Improvement # 1: clause weights Initial weight of each clause: 1 Increase by $k$ the weight of unsatisfied clauses. Choose $v$ according to max increase in weight Clause weights is another example of conflict-driven decision strategy. Improvement # 2: Averaging-in Q: Can we reuse information gathered in previous tries in order to speed up the search? A: Yes! Rather than choosing T randomly each time, repeat ‘good assignments’ and choose randomly the rest. Let $X_1$, $X_2$ and $X_3$ be equally wide bit vectors. Define a function \texttt{bit\_average} : $X_1 \times X_2 \rightarrow X_3$ as follows: \[ b_3^i := \begin{cases} b_1^i & \text{if } b_1^i = b_2^i \\ \text{random} & \text{otherwise} \end{cases} \] (where $b_j^i$ is the $i$-th bit in $X_j$, $j \in \{1,2,3\}$) **Improvement # 2: Averaging-in (cont’d)** Let $T_i^{\text{init}}$ be the initial assignment ($T$) in cycle $i$. Let $T_i^{\text{best}}$ be the assignment with highest # of satisfied clauses in cycle $i$. - $T_1^{\text{init}} := \text{random assignment}$. - $T_2^{\text{init}} := \text{random assignment}$. - $\forall i > 2, T_i^{\text{init}} := \text{bit\_average}(T_{i-1}^{\text{best}}, T_{i-2}^{\text{best}})$
{"Source-Url": "http://www.cs.cmu.edu/~emc/15-820A/reading/sat_cmu.pdf", "len_cl100k_base": 4435, "olmocr-version": "0.1.53", "pdf-total-pages": 38, "total-fallback-pages": 0, "total-input-tokens": 66949, "total-output-tokens": 6084, "length": "2e12", "weborganizer": {"__label__adult": 0.0004563331604003906, "__label__art_design": 0.0004286766052246094, "__label__crime_law": 0.0007419586181640625, "__label__education_jobs": 0.0009760856628417968, "__label__entertainment": 0.00012022256851196288, "__label__fashion_beauty": 0.00022971630096435547, "__label__finance_business": 0.0004549026489257813, "__label__food_dining": 0.0005159378051757812, "__label__games": 0.0015459060668945312, "__label__hardware": 0.0018367767333984375, "__label__health": 0.0007171630859375, "__label__history": 0.00038552284240722656, "__label__home_hobbies": 0.00016498565673828125, "__label__industrial": 0.0010900497436523438, "__label__literature": 0.000324249267578125, "__label__politics": 0.00048232078552246094, "__label__religion": 0.000629425048828125, "__label__science_tech": 0.1397705078125, "__label__social_life": 0.00011926889419555664, "__label__software": 0.0072784423828125, "__label__software_dev": 0.83984375, "__label__sports_fitness": 0.0006060600280761719, "__label__transportation": 0.0011281967163085938, "__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, 12830, 0.02969]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 12830, 0.6819]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 12830, 0.69715]], "google_gemma-3-12b-it_contains_pii": [[0, 79, false], [79, 322, null], [322, 843, null], [843, 975, null], [975, 1225, null], [1225, 1486, null], [1486, 1981, null], [1981, 2258, null], [2258, 2480, null], [2480, 2788, null], [2788, 3129, null], [3129, 3408, null], [3408, 3748, null], [3748, 4155, null], [4155, 4708, null], [4708, 5037, null], [5037, 5501, null], [5501, 5846, null], [5846, 6063, null], [6063, 6435, null], [6435, 6595, null], [6595, 6841, null], [6841, 7020, null], [7020, 7701, null], [7701, 8213, null], [8213, 8508, null], [8508, 8715, null], [8715, 9059, null], [9059, 9662, null], [9662, 10033, null], [10033, 10368, null], [10368, 10619, null], [10619, 11148, null], [11148, 11607, null], [11607, 11846, null], [11846, 12073, null], [12073, 12416, null], [12416, 12830, null]], "google_gemma-3-12b-it_is_public_document": [[0, 79, true], [79, 322, null], [322, 843, null], [843, 975, null], [975, 1225, null], [1225, 1486, null], [1486, 1981, null], [1981, 2258, null], [2258, 2480, null], [2480, 2788, null], [2788, 3129, null], [3129, 3408, null], [3408, 3748, null], [3748, 4155, null], [4155, 4708, null], [4708, 5037, null], [5037, 5501, null], [5501, 5846, null], [5846, 6063, null], [6063, 6435, null], [6435, 6595, null], [6595, 6841, null], [6841, 7020, null], [7020, 7701, null], [7701, 8213, null], [8213, 8508, null], [8508, 8715, null], [8715, 9059, null], [9059, 9662, null], [9662, 10033, null], [10033, 10368, null], [10368, 10619, null], [10619, 11148, null], [11148, 11607, null], [11607, 11846, null], [11846, 12073, null], [12073, 12416, null], [12416, 12830, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 12830, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 12830, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 12830, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 12830, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 12830, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 12830, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 12830, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 12830, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 12830, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 12830, null]], "pdf_page_numbers": [[0, 79, 1], [79, 322, 2], [322, 843, 3], [843, 975, 4], [975, 1225, 5], [1225, 1486, 6], [1486, 1981, 7], [1981, 2258, 8], [2258, 2480, 9], [2480, 2788, 10], [2788, 3129, 11], [3129, 3408, 12], [3408, 3748, 13], [3748, 4155, 14], [4155, 4708, 15], [4708, 5037, 16], [5037, 5501, 17], [5501, 5846, 18], [5846, 6063, 19], [6063, 6435, 20], [6435, 6595, 21], [6595, 6841, 22], [6841, 7020, 23], [7020, 7701, 24], [7701, 8213, 25], [8213, 8508, 26], [8508, 8715, 27], [8715, 9059, 28], [9059, 9662, 29], [9662, 10033, 30], [10033, 10368, 31], [10368, 10619, 32], [10619, 11148, 33], [11148, 11607, 34], [11607, 11846, 35], [11846, 12073, 36], [12073, 12416, 37], [12416, 12830, 38]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 12830, 0.0]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
ed3d2dcee75d054199afad8f6724e9a899140b46
Quantity Checking through Unit of Measurement Libraries, Current Status and Future Directions Steve McKeever, Gökrem Paçaci and Oscar Bennich-Björkman Department of Informatics and Media, Uppsala University, Sweden Keywords: Units of Measurement, Units Checking, Unit Libraries, Quantity Pattern. Abstract: Unit errors are known to have caused some costly software engineering disasters, most notably the Mars Climate Orbiter back in 1999. As unit annotations are not mandatory for execution only dramatic events become newsworthy. Anecdotally however, there is evidence to suggest that these kinds of errors are recurrent and under-reported. There are an abundance of tools and most notably libraries to aid scientific developers manage unit definitions. In this paper we look in detail at how a number of prominent libraries in the most popular programming languages support units. We argue that even when these libraries are based on a sound design pattern, their implementation becomes too broad. Each library is distinct with varying features, lacking a core API, compromising both interoperability and thereby usage. We claim that further library or tool development is not needed to further adoption, but that a greater understanding of developers requirements is. 1 INTRODUCTION In scientific applications, physical quantities and units of measurement are used regularly. However few programming languages provide direct support for managing them. The technical definition of a physical quantity is a “property of a phenomenon, body, or substance, where the property has a magnitude that can be expressed as a number and a reference” (Joint Committee for Guides in Metrology (JCGM), 2012). To explain this further, each quantity is declared as a number (the magnitude of the quantity) with an associated unit (Bureau International des Poids et Mesures, 2014). For example you could assert the physical quantity of length with the unit metre and the magnitude 1.0 (10m). However, the same length can also be expressed using other units such as centimetres or kilometres, at the same time changing the magnitude (1000cm or 0.01km). Although these examples are all based on the International System of Units (SI), which is the most used and well known unit system, there exists several other systems that these physical quantities can be expressed in, each with different units for the same quantity. Other examples include the Imperial system, the Atomic Units system, and the CGS (centimetre, gram, second) system. These have evolved over time and branched off from each other. Some well known and expensive errors have arisen due to unit inconsistencies when operating over values of differing unit systems or differing representations of dimensions. The most famous of which is the Mars Climate Orbiter (Stephenson et al., 1999). The orbiter had malfunctioned, causing it to disintegrate in the upper atmosphere. A later investigation found that the root cause of the crash was the incorrect usage of Imperial units in the probe’s software. However for the most part, scientific developers have been able to manage their code without tool or static checking support. The burden of cost for such errors has been contained within the scope of their endeavours. Several popular software modelling languages include representations of physical units, such as Modelica (Modelica, 2018) or VSL in the MARTE standard (Ribeiro et al., 2016), but these form part of the specification and are not a requirement for derived executables, much as cardinality annotations in UML diagrams. With greater interoperability, industrial use of computational simulations and penetration of digitalisation through cyber-physical systems; it seems pertinent to faithfully represent key properties of physical systems such as units of measurement in code bases. This can be achieved through the use of domain specific languages (Garny et al., 2008) or programming languages that support units of measurement, tools that detect unit inconsistencies or libraries that provide units to existing languages. Adding units to conventional programming languages has a rich history going back to the 1970s and early 80s, with proposals to extend Fortran (Gehani, 1977) and then Pascal (Dreiheller et al., 1986). The pioneering foundational work was undertaken by Wand and O’Keefe (Wand and O’Keefe, 1991). They revealed how to add dimensions to the simply-typed lambda calculus, such that polymorphic dimensions can be inferred in a way that is a natural extension of Milner’s polymorphic type inference algorithm. In terms of initial library support for modular or object-oriented languages, Hilfinger (Hilfinger, 1988) showed how to exploit Ada’s abstraction facilities, namely operator overloading and type parameterisation, to assign attributes for units of measurement to variables and values. All of the aforementioned solutions require either migration to a new language or annotating the source code, both of which are burdens on the developers. A more lightweight methodology is presented in (Ore et al., 2017) that uses an initial pass to build a mapping from attributes in shared libraries to units. The shared libraries contain unit specifications so this mapping is used to propagate into a source programme and, as the authors show, detect inconsistencies. An alternative pathway is to introduce physical units into an object oriented modelling platform, along with a compilation workflow that leverages OCL expressions (Mayerhofer et al., 2016) or staged computation (Allen et al., 2004) to derive units where possible at compile-time. These elegant abstractions lift the declaration and management of units into software models but do not solve the interoperability problem due to the lack of agreed conventions for scientific, medical and financial applications of the Quantity pattern. Unfortunately we lack an authoritative estimate of how frequently unit inconsistencies occur or their cost. Anecdotally we can glean that it is not negligible from experiments described in certain papers. Cooper (Cooper and McKeever, 2008) developed a validation tool for CellML, a domain specific language for modelling biological systems. He applied it to the repository of CellML models and, of those that were found to be invalid, 60% had dimensionally inconsistent units. Similarly, the Osprey type system type system (Jiang and Su, 2006) provides an advanced unit checker and inference engine for C. In their paper they describe having applied it to mature scientific application code and found hitherto unknown errors. Unfortunately they do not describe the prevalence or magnitude of these errors. A more telling statistic is found in (Ore et al., 2017) where they apply their lightweight unit inconsistency tool to 213 open-source systems, finding inconsistencies in 11% of them. There are many libraries that provide support for units in all of the popular programming languages. However no standard has emerged. In this paper we argue that the existing design pattern is too broad and open to interpretation. The rest of this paper is structured as follows. In Section 2 we provide an introduction to units of measurement and the Quantity pattern that provides a standard object oriented solution. In Section 3 we describe the underlying implementation strategy of some of the most used unit libraries in the most popular programming languages. In Section 4 we surmise as to why the Quantity pattern has failed to galvanise the scientific programming community, and suggest areas of future work required to promote better software engineering with regards to units of measurement. Finally in Section 5 we articulate our position and contextualise our study further. # 2 Describing Units of Measurement Here, we will first introduce the problem by means of an example scenario. Two programmers are working on a system that manages physical quantities using a popular language such as C#, Java, or Python. The first programmer wants to create two quantities that will be used by the second at a later stage. Because the language does not have support for this type of construct, he or she decides to do it using integers and adding comments, like this: ```markdown int mass = 10; // in tonnes int acceleration = 10; // in m.s^-2 ``` Now the second programmer wants to use these values to calculate force using the well-known equation \( F = m \times a \): ```markdown int force = mass * acceleration; // 100N ``` The variable `force` will now have the value of 100, assumed to be 100 N. The issue is that the variable `mass` is actually representing 10 tonnes, not 10 kilograms. This means that the actual value of the force should be 100000 N (instead of 100 N), off by a factor of one thousand. Because the quantities in this example are represented using integers there is no way for the compiler to know this information and therefore it is up to the programmers themselves to keep track of it. The only reliable way to solve this is try to remove the human element by having a systematic means of checking the units of calculations to ensure that they are handled correctly. This type of automatic check is potentially something that could be undertaken at compile time in a strongly typed language, but unfortunately very few languages have support for units of measurement and only one of those is in the top twenty most popular programming languages, according to the TIOBE index (TIOBE, 2018). In all other languages, it is up to the software developers to create these checks themselves. One example of how this can be achieved is to make sure the compiler knows what quantities are being used by encapsulating this into a class hierarchy, with each unit having its own class. The scenario above would then look like this instead: ```java Tonne mass = 10; Acceleration acceleration = 10; // in m.s^{-2} Force force = mass * acceleration; // 100000N ``` Compared to the previous example, here the compiler now knows exactly what it is dealing with and thus the information that the mass is in tonnes is kept intact and the correct force can be calculated in the end. This type of solution not only means that differences in magnitude and simple conversions are taken care of but also that any erroneous units being used in an equation can be caught at compile time. However, making a class hierarchy similar to the one illustrated above could potentially involve hundreds of units and thousands of conversions. A more abstract approach is to bind the value along with the unit in what is known as the Quantity pattern (Fowler, 1997). ```java class Quantity { private float value; private Unit unit; .... } ``` We can include arithmetic operations to the `Quantity` class that ensures addition and subtraction only succeed when their units are equivalent, or multiplication and subtraction generate a new unit that represents the derived value correctly. Moreover we can include other useful behaviour such as printing and parsing to this class. Units can be defined in the most generic form using an algebraic definition that includes two types, base quantities and derived quantities. The base quantities are the basic building blocks, and the derived quantities are built from these. The base quantities and derived quantities together form a way of describing any part of the physical world (Sonin, 2001). For example length (metre) is a base quantity, and so is time (second). If these two base quantities are combined they express velocity (metre/second or metre × second^{-1}) which is a derived quantity. The International System of Units (SI) defines seven base quantities (length, mass, time, electric current, thermodynamic temperature, amount of substance, and luminous intensity) as well as a corresponding unit for each quantity (The National Institute of Standards and Technology, 2015). These physical quantities are also organised in a system of dimensions, each quantity representing a physical dimension with a corresponding symbol (L for length, M for mass, T for time etc.). ```java type base = L | M | T ... ``` Any derived quantity can be defined by a combination of one or several base quantities raised to a certain power. These are called dimensional exponents (Bureau International des Poids et Mesures, 2014). ```java type derived = Base of base | Times of (derived * derived) | Exp of (derived * int) ``` Dimensional exponents are not a type of unit or quantity in themselves but rather another way to describe an already existing quantity in an abstract way. Using the same example of velocity as before, it can be expressed as: ```java Times (L, Exp {T,-1}) ``` In concrete syntax this is instead expressed as $L \times T^{-1}$, where L represents length and $T^{-1}$ represents the length being divided by a certain time. Representing units in this manner is not always optimal as a normal form exists which makes storage and, more importantly, comparison a lot easier. Any system of units can be derived from the base units as a product of powers of those base units: $base_1^{e_1} \times base_2^{e_2} \times ... base_n^{e_n}$, where the exponents $e_1, ..., e_n$ are rational numbers. Thus an SI unit can be represented as a 7-tuple $(e_1, ..., e_7)$ where $e_i$ denotes the $i$-th base unit; or in our case $e_1$ denotes length, $e_2$ mass, $e_3$ time and so on. Thus 3 Newtons would be represented as $(1,1,−2,0,0,0,0)$, or $3 \text{ kg.m.s}^{-2}$. Dimensionless units are represented by a tuple whose 7 components are all 0. Interestingly any unit from any other system can be expressed in terms of SI units. Conversions can be undertaken using mostly multiplication factors, but in some cases offsets are required too. This suggests implementing units through the following class outline: ```java class Unit { private int [7] dimension private float [7] conversionFactor private int [7] offset private String name ... boolean isCompatibleWith (Unit u) } ``` boolean equals (Unit u) Unit multiplyUnits (Unit u) Unit divideUnits (Unit u) } The dimension array contains the 7-tuple of base unit exponentials. The attributes conversionFactor and offset enable conversions from this unit system to the SI units, while name is so that users can define their own unit system. The class Unit also defines operations to compare and combine units. The method isCompatibleWith checks whether two units are compatible for being combined, such as miles and centimetres. While equals returns true if the units are exactly the same, which is used when adding or subtracting quantities. When two quantities are multiplied then multiplyUnits adds the two dimension arrays. Correspondingly, divideUnits subtracts each of the elements of the dimension array. The idea behind a software design pattern is a general, reusable solution to a commonly occurring problem. Due to the lack of an agreed interface to the Quantity pattern, non-compatible domain specific instantiations have proliferated as we shall demonstrate in the next section. 3 ANALYSIS A study of Unit of Measurement libraries (Bennich-Björkman and McKeever, 2018) has shown that there is a lot of reinvention and little collaboration. By analysing popular open-source repositories, the authors discovered close to 300 active libraries for the top twenty programming languages. A further reduction based on features, reputation and development status brought this number down to 82 as shown in Figure 1. We have looked in more detail at a number of these prominent libraries to elucidate how they operate, their feature set and potential for interoperability. All of the libraries we analysed implemented the Quantity pattern, albeit in a number of different ways. How each library in each specific language implemented the pattern is detailed below. 3.1 Java Two of the most prominent libraries written in Java are CaliperSharp and the JSR 385 project (github.com/point85/CaliperSharp, github.com/unitsofmeasurement/unit-api). CaliperSharp implements the Quantity pattern through the use of the class Quantity in which the Amount is used to model the magnitude of the quantity and UnitOfMeasure is used to specify the unit for the quantity. In CaliperSharp, UnitOfMeasure is defined as an enumeration which contains all unit definitions that the library supports. On the other hand JSR 385 implements the Quantity pattern through the generic interface Quantity<T> which each defined (specific) quantity then implements. For example: Acceleration extends Quantity<Acceleration> The quantity interface itself contains a definition of a unit through the use of the interface, Unit. This Unit interface also utilises the concept of physical dimensions to define the unit. 3.2 C++ The leading library for C++ is BoostUnits (github.com/boostorg/units). It is in effect the de facto standard and is actively developed, has very good documentation, supports many units as well as numerous different constants. BoostUnits is also part of a big development team (Boost.org). However Boost exploits the C++ template meta-programming library so it is more than just a library as it supports a staged computation model similar to MixGen (Allen et al., 2004). None of the other prominent programming languages have this flexible compilation strategy so it is an anomaly and even though it implements dimensional analysis in a general and extensible manner, treating it as a generic compile-time meta-programming problem, this style of software development is radically different than a single stage compilation. The key advantage of this staged approach is that with appropriate compiler optimisation, no runtime execution cost is introduced, encouraging the use of this library to provide dimension checking in performance-critical code. Nonetheless, the core feature set is not too distinct from other libraries. 3.3 Python The Astropy library (github.com/astropy/astropy) has the single most commits out of all those presented in (Bennich-Björkman and McKeever, 2018), which implies that it is also one of the most well-developed. Like the previously presented libraries, Astropy has the Quantity pattern at its root and, as it has so many commits and contributors, it is feature rich. Much of the functionality is built on top of its well engineered core. Another popular Python library is Pint (github.com/hgrecco/pint). It implements the Quantity pattern explicitly as the central unit in the library is the `Quantity` class with a magnitude and a unit of measurement and this is how all units are defined. For example: ```python >>> import pint >>> ureg = pint.UnitRegistry() >>> 3 * ureg.meter + 4 * ureg.cm <Quantity(3.04, 'meter')> ``` ### 3.4 C# Looking at the number of commits, contributors, comprehensiveness of the documentation as well as adoption, UnitsNet (github.com/angularsen/UnitsNet) is one of the best libraries overall, not only for C#. Although UnitsNet also implements the same pattern through the `IQuantity` interface, this is achieved in a slightly different manner to other libraries shown here. The type of the quantity and the value for the seven base dimensions are the only attributes that are defined in the interface. The magnitude (or value) of the quantity is added later as an operation for a specific unit that is calculated. The type for each quantity is defined as `QuantityType` which is an enumeration containing all the quantities that the library supports. This is similar to how it is handled in the CaliperSharp Java library mentioned earlier. In UnitsNet each specific unit is defined as its own class and utilises operator overloading to convert between units. The library also employs automatic code generation to produce all the different conversions between different units. Another capable library written in C# is Gu.Units (github.com/GuOrg/Gu.Units). Similar to UnitsNet it implements the Quantity pattern through the `IQuantity` interface which defines a value (SiValue) and a unit (SiUnit). The unit of a quantity is defined through the interface `IUnit` which contains information about the symbol for the unit, the base unit and ways to convert the value of unit to its base value (kilometre to metre for example) or from the base value. Another similarity to UnitsNet is that Gu.Units also uses code generation which leverages these interfaces to make concrete quantities. ### 3.5 Javascript A popular library for JavaScript is JS Quantities (github.com/gentooboontoo/js-quantities). With over 300 commits, it is one of libraries with the most commits for the JavaScript language. The library is also based upon another popular physical quantity library called Ruby Units (github.com/olbrich/ruby-units) which is also quite mature. Similar to Pint, JS Quantities implements the Quantity pattern through a generic class called `Qty`, which represents a generic quantity. A user can then create whatever quantity they want through this class. ```javascript qty = Qty(‘1m’); qty = Qty(‘1 N*m’); qty = Qty(‘1 m/s’); qty = Qty(‘1 m^2/s^2’); qty = Qty(‘1 m^2 kg^2 J^-2/s^2 A’); qty = Qty(‘1 attoparsec/microfortnight’); ``` In the example above, the use of dimensions and dimensional exponents in JS Quantities is also show- cased through the use of the Qty class. Similar to other libraries, all the available quantities are defined in an enumeration. 4 EVALUATION AND FUTURE WORK In this section we postulate as to why we have arrived at this state of affairs when the underlying computing science is well understood and Fowler (Fowler, 1997) provided an effective object model for units of measurement some years ago. The Quantity pattern has been shown to be applicable to mathematical calculations, medical observations and financial conversions. A more detailed and specialised version of this pattern is provided by the Physical Quantity pattern (Krisper et al., 2017) that looks in more depth at the requirements of the physical and mathematical sciences, presenting interfaces to enforce the use of explicit quantity types. The key aspect is that the research challenges are not technical in nature, more work is required to create robust interfaces from the Quantity pattern that engage the respective communities and gather traction. Even if these well engineered interfaces existed, we suggest two other reasons that hamper uptake. The first reason was put forward by Damevski (Damevski, 2009) and is that scientific programmers should not be burdened by units at each statement in their programs, but that units should be present in software component interfaces. This makes sense when you consider that research groups in, say, physics and chemistry departments have evolved their own conventions, methodologies and ontologies. Problems can arise when they try to collaborate over energy conversions, for instance. While the physicist works in terms of electron volts per formula unit, the chemist thinks in terms of kilojoules per mole. In such cases not only are the units different but so are the magnitudes. In this mode, each research group should be free to develop their codes without unit annotations but when they come to combining their codes with others, the conversions need to be explicitly introduced. The Logic of Collective Action (Olson, 2009) develops a theory of political science and economics of concentrated benefits versus diffuse costs. Its central argument is that concentrated minor interests will be overrepresented and diffuse majority interests due to a free-rider problem that is stronger when a group becomes larger. This is perhaps an explanation as to why some of the libraries have continued to exist and prosper when there are equally good ones for that particular language. Once developed and a user base has accrued, due to the open-source nature of the endeavour, it becomes necessary to keep supporting the library as vital code has become dependent on its existence. There are two central avenues of further work in this area. We will interview scientific, medical and financial developers to elucidate their requirements. Some users might be content with very lightweight support, as envisaged by Damevski (Damevski, 2009). This would allow diverse teams to collaborate even if their domain specific environments or choice of unit systems were to some extent incompatible. However other users might require a more robust environment in which all variables are given an explicit unit or are dimensionless, and a checker will ensure operational unit correctness. In-between we might allow static or dynamic unit conversions, the ability to define new domain specific unit systems and a degree of flexibility that unit variables allow. Whether all of these features need to be supported, and to what extent, is an open question that we hope to address in the near future so that the Quantity pattern can be enriched with an effective API for modelling and implementing units of measurement. A second avenue that is urgently required is an understanding of the true cost of unit of measurement errors. The big disasters grab the headlines but it is the more mundane day to day outlay of defective code, leading to incorrect results that could be more costly yet is not reported. We mentioned earlier some informal figures describing the extent of the problem but a more accurate understanding is needed. An open source repository of defective unit error code would allow researchers to explore techniques to detect, assist and possibly recover from some form of unit errors. 5 CONCLUSION Our initial study of unit libraries (Bennich-Björkman and McKeever, 2018) highlighted an abundance of similar contributions without a clear standard emerging. Unit libraries allow developers to faithfully represent quantities in their code and provide assurances over correctness. These features are desirable from both model and software engineering perspectives as they reduce errors and encourage maintainability. However they are not a requirement for creating executable code. In order to escape from this impasse we need to know how people actually work with units. Are unit libraries sufficient? How can we ensure that they are used unless mandated by the organisation. Modern development workflows might favour separate unit inferencing tools or unit checking to be undertaken through testing instead. The needs of modern commercial systems, deployed on a vast number of distinct devices, developed with a plethora of languages, evolving daily through continuous integration is rather different to those of an academic research group. Numerous stakeholders, from developers upwards to project managers in both small and large organisations need to be interviewed. Rather than focusing on unit library or tool support, the purpose of our current ongoing research is to delve into these broader topics using questionnaires to understand the underlying issues and causes. REFERENCES
{"Source-Url": "https://www.scitepress.org/Papers/2019/75247/75247.pdf", "len_cl100k_base": 5534, "olmocr-version": "0.1.50", "pdf-total-pages": 7, "total-fallback-pages": 0, "total-input-tokens": 22863, "total-output-tokens": 7368, "length": "2e12", "weborganizer": {"__label__adult": 0.0004458427429199219, "__label__art_design": 0.00047469139099121094, "__label__crime_law": 0.00044465065002441406, "__label__education_jobs": 0.0012006759643554688, "__label__entertainment": 0.00012981891632080078, "__label__fashion_beauty": 0.0002503395080566406, "__label__finance_business": 0.0003504753112792969, "__label__food_dining": 0.0006489753723144531, "__label__games": 0.00063323974609375, "__label__hardware": 0.001598358154296875, "__label__health": 0.0010194778442382812, "__label__history": 0.0006575584411621094, "__label__home_hobbies": 0.00017535686492919922, "__label__industrial": 0.0010395050048828125, "__label__literature": 0.0007038116455078125, "__label__politics": 0.0005097389221191406, "__label__religion": 0.0009331703186035156, "__label__science_tech": 0.310302734375, "__label__social_life": 0.00018346309661865232, "__label__software": 0.00885772705078125, "__label__software_dev": 0.66748046875, "__label__sports_fitness": 0.0004525184631347656, "__label__transportation": 0.001255035400390625, "__label__travel": 0.00029754638671875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 31359, 0.02969]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 31359, 0.77421]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 31359, 0.90196]], "google_gemma-3-12b-it_contains_pii": [[0, 4095, false], [4095, 9160, null], [9160, 14064, null], [14064, 18421, null], [18421, 21354, null], [21354, 26303, null], [26303, 31359, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4095, true], [4095, 9160, null], [9160, 14064, null], [14064, 18421, null], [18421, 21354, null], [21354, 26303, null], [26303, 31359, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 31359, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 31359, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 31359, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 31359, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 31359, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 31359, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 31359, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 31359, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 31359, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 31359, null]], "pdf_page_numbers": [[0, 4095, 1], [4095, 9160, 2], [9160, 14064, 3], [14064, 18421, 4], [18421, 21354, 5], [21354, 26303, 6], [26303, 31359, 7]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 31359, 0.0]]}
olmocr_science_pdfs
2024-12-01
2024-12-01
1c08a16ef9bbd15e933e3db7d26eeadec2fac26b
TEST AUTOMATION PRACTICE WITH SELENIUM WEBDRIVER Csapó Péter Mikó Szilárd EPAM Systems, Budapest, 2015 Basics Agenda 1. Assertion 2. Navigation 3. Interrogation 4. Manipulation Assertion Fail method ``` fail(error_message) ``` Conditional assert ``` assertTrue(error_message, boolean_condition) ``` Equality assert ``` assertEquals(error_message, expected, actual) ``` Provide meaningful messages in assertions! Assertion Identity assert ```java assertSame(error_message, expected_object, actual_object) ``` Custom assert ```java assertThat(actual_object, Matcher<object> matcher) ``` String assert ```java assertThat("myString", containsString("ring")) ``` Click here for more JUnit assertions Benefits of `assertThat` Basics 2 NAVIGATION Navigation Loading a web page in current browser window - driver.get(java.lang.String) - driver.navigate().to(java.lang.String) - driver.navigate().to(java.net.URL) Navigation Move back & forward - Driver.Navigate().Back() - Driver.Navigate().Forward() Refresh page - Driver.Navigate().Refresh() Basics 3 INTERROGATION Interrogation **Window Title** - `driver.getTitle()` **Current URL** - `driver.getCurrentUrl()` **Page Source** - `driver.getPageSource()` Interrogation Locating web elements • `driver.findElement(org.openqa.selenium.By)` - 0 match -> throws exception - 1 match -> returns a WebElement instance - 2+ matches -> returns only the first match from web page • `driver.findElements(org.openqa.selenium.By)` - 0 match -> returns an empty list - 1 match -> returns a list with one WebElement - 2+ matches -> returns list with all matching WebElements Interrogation By class • Supports various locator strategies • By locating mechanisms – Id – ClassName – LinkText – PartialLinkText – Name – TagName – CssSelector – XPath Interrogation Inspecting elements in web browsers - Firefox - Firebug add-on (Right click -> Inspect element / F12) - Firefinder add-on (Try out your CSS & Xpath expressions) - Chrome - Built-in (Right click -> Inspect element / F12) - IE - Built-in (Tools -> Developer Tools / F12) Interrogation Id • `driver.findElement(By.id("some_id"));` • Ideal solution, however... – Ids don’t always exist – Their uniqueness is not enforced – Used by developers as well ClassName • `driver.findElement(By.className("some_class_name"));` Interrogation **Linktext** - `driver.findElement(By.linkText("Sign in"));` - `driver.findElement(By.partialLinkText("Sign"));` **Name** - `<input id="modCustLoginPassword" name="password">` - `driver.findElement(By.name("password"));` Interrogation tagName - `<label>Email address</label>` - `driver.findElement(By.tagName("label"));` Support classes - Return all that matches each of the locators in sequence - `driver.findElements(new ByChained(by1, by2))` - Return all that matches any of the locators in sequence - `driver.findElements(new ByAll(by1, by2))` Interrogation **CssSelector** - **Absolute path** - `driver.findElement(By.cssSelector("html>body>div>p>input"));` - **Relative path** - `driver.findElement(By.cssSelector("input"));` - **Attribute selection** - `driver.findElement(By.cssSelector("button[name]"));` - `driver.findElement(By.cssSelector("button[name='cancel']"));` - `driver.findElement(By.cssSelector("img:not[alt]"));` Interrogation **CssSelector** - **Id selection** - `driver.findElement(By.cssSelector("#save"));` - **Class selection** - `driver.findElement(By.cssSelector(".login"));` - **Combined selection** - `driver.findElement(By.cssSelector("button#save"));` - `driver.findElement(By.cssSelector("input.login"));` Interrogation **CssSelector** - First matching child of the specified tag - `driver.findElement(By.cssSelector("div#students:first-child"));` - Nth matching child of the specified tag - `driver.findElement(By.cssSelector("#loginForm:nth-child(3)"));` - First matching enabled tag - `driver.findElement(By.cssSelector("button:enabled"));` Interrogation **XPath** - Absolute path ```java driver.findElement(By.xpath("html/body/p/input")); ``` - Relative path ```java driver.findElement(By.xpath("//input")); ``` - Attribute selection ```java driver.findElement(By.xpath("//input[@id='username']"); ``` ```java driver.findElement(By.xpath("//*[id='myId']"); ``` Interrogation Element interrogation - `element.getText();` - `element.getAttribute();` - `element.getTagNamed();` - `element.isDisplayed();` - `element.isEnabled();` - `element.isSelected();` - checkbox is selected or not - `selectElement.isMultiple();` - multi select listbox or not - `selectElement.getOptions();` - listbox select options Basics 4 MANIPULATION Manipulation Click - `element.click()` - Button - Link - Checkbox - Combobox Submit - `form.submit()` - Form Manipulation **Shift + Click** - `Actions(driver).keyDown(Keys.SHIFT).click(element).keyUp(Keys.SHIFT).build().perform();` **Special Actions** - `Actions(driver).moveToElement(element).build().perform();` - `Actions(driver).contextClick().build().perform();` - `Actions(driver).doubleClick().build().perform();` - `Actions(driver).clickAndHold().build().perform();` - `Actions(driver).release().build().perform();` Manipulation **Type text** - `element.sendKeys("string")` - Input field **Clear text** - `element.clear()` Manipulation **Listbox Selection** - `new Select(element).selectByIndex(elementCount)` **Listbox Manipulating Commands** - `select[ByIndex, ByVisibleText, ByValue]` - `deselect[ByIndex, ByVisibleText, ByValue]` - `deselectAll()` Questions Advanced Agenda 1. Synchronization 2. Window Handling 3. Screenshots 4. Browser Profile 5. Cookies SYNCHRONIZATION Synchronization Page Load Timeout • Sets the amount of time to wait for a page load to complete • Global setting of the Webdriver object • Negative value means indefinite wait time Example • `driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);` Synchronization **Implicit Wait** - Specifies the waiting time for element not immediately visible - Global setting of the Webdriver object - 0 by default **Example** ``` driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); ``` Synchronization Explicit Wait • Waiting for a certain condition • Poor alternative – Thread.sleep(1000); • Recommended – WebDriverWait class Example • WebDriverWait wait = new WebDriverWait(driver, TIME_OUT); • wait.until(ExpectedConditions.method); Synchronization **ExpectedConditions class** - `presenceOfElementLocated(By locator)` - `textToBePresentInElement(WebElement element, java.lang.String text)` - `titleContains(java.lang.String title)` - `visibilityOf(WebElement element)` - `invisibilityOfElementLocated(By locator)` - `elementToBeSelected(WebElement element)` - `elementToBeClickable(By locator)` [Click here for more ExpectedConditions](#) Advanced 2 WINDOW HANDLING Window Handling **Size** - `driver.manage().window().getSize().getHeight(); .getWidth();` - `driver.manage().window().setSize(Dimension d);` - `driver.manage().window().maximize();` **Position** - `driver.manage().window().getPosition().getX(); .getY();` - `driver.manage().window().setPosition(Point p);` Window Handling **Handles** - String windowHandle = driver.getWindowHandle(); - Iterator<String> windowIterator = browser.getWindowHandles(); **Switch To** - driver.switchTo().window(windowHandle); Screenshots **Advantages** - Keep track of changing UI - Store pages with error **Example** - File screenshot = ```java ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); ``` - `FileUtils.copyFile(screenshot, new File(fileSource));` BROWSER PROFILE Introduction • c:\Users\[user]\AppData\Roaming\Mozilla\Firefox\Profiles\n • Unlimited number of profiles • Stores many user attributes – Passwords – Bookmarks – Browser history – Settings – Etc. Browser Profile Usages - Set preferred language - Change User Agent - Set trusted sites - Disable confirmation dialog - Enable Firefox extensions, e.g. Firebug and Firefinder - Enable native events for drag-and-drop Browser Profile Set preferred language - var profile = new FirefoxProfile(); - profile.setPreference("intl.accept_languages", "de"); - IWebDriver driver = newFirefoxDriver(profile); - Search for preference keys on Firefox by about:config - Get all special pages about:about Changing user agent - var profile = new FirefoxProfile(); - profile.setPreference(USERAGENT_OVERRIDE, "Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10"); Browser Profile Enable Extension - var profile = new FirefoxProfile(); - profile.addExtension(new File(PATH_TO_FIREBUG)); - profile.setPreference("extensions.firebug.currentVersion", "2.0.12"); Cookies Introduction • Useful for testing the login feature • Getting or setting session IDs • Cookie attributes – Name – Value – Domain – Path – Expiry – Secure – Http only Cookies Interrogation • Get all cookies from the current session – driver.manage().getCookies(); • Get cookie with a given name – driver.manage().getCookieNamed(cookieToTest); Cookies Manipulation • Delete all cookies from the current session – driver.manage().deleteAllCookies() • Delete a specific cookie – driver.manage().deleteCookie(TestCookie); • Delete cookie with a given name – driver.manage().deleteCookieNamed(cookieToTest); Cookies Manipulation • Add a specific cookie – Cookie cookie = new Cookie("mycookie", "123456"); – driver.manage().addCookie(cookie); • Domain attribute is the current document by default Questions Test Design Agenda 1. Data Driven Testing 2. Page Object Model DATA DRIVEN TESTING Data Driven Testing **Concept** - Use pre-stored data as input and expected output - Run your script to get actual output and compare them - Continue testing with the next set of data Data Driven Testing Possible data sources • Database • XML file • Property file • Etc. Pros of Data Driven Testing • Repeatability and reusability • Separation of test code and data • Reduction in number of tests Data Driven Testing Where to use - Testing different localizations of a site - `< testData lang="en" phone="(+36-1) 444 44 99" /> - `< testData lang="hu" phone="06 (40) 49 49 49" /> ![Flag icons of different countries] Data Driven Testing How to use • Use JUnitParamsRunner class – @RunWith(JUnitParamsRunner.class) – public class Testclass { ... } • Add test parameters – @Parameters(method = "testData") – public void testCase(String param1, String param2) { ... } Test Design 2 PAGE OBJECT MODEL Page Object Model Agenda • New Approach • @FindBy annotation • PageFactory class • Page Flow • Best practices Page Object Model New Approach • Every UI change could cause a lot of test maintenance work • We have to keep maintenance changes as low as possible • We minimize the change sensitive automation code Page Object Model How to do it • We accept that the application and its elements are bound to change • We create a new layer which contains change prone data • This way we can adapt to changes with minimal refactoring cost Page Object Model Rules • What describes one page should be in one class • Use class methods to interact with your page • This class represents your page in the test code • Divide complex pages into smaller components called widgets • Create widgets with the same approach as pages @FindBy Annotation - We mark elements with the @FindBy annotation - FindBy directs Webdriver to locate an element 1. `@FindBy(how = How.ID, using = "i")` ```java public WebElement routeFrom; ``` 2. `@FindBy(id = "i")` ```java public WebElement routeFrom; ``` 3. `public WebElement i;` Page Object Model PageFactory Class - You can instantiate page/widget WebElements using the PageFactory class - Use static method initElements - WebElements are evaluated lazily Example - PageFactory.initElements(WebDriver driver, java.lang.Class PageObjectClass); - initElements returns PageObjectClass Page Object Model Page Flow • We want to describe the logical relationship between pages • Manipulation methods should reflect these relationships • We should return a page object class after each method • Return itself if we stay at the same page (e.g. typing) • Return next page if we navigate (e.g. submit) Page Object Model Best practices • Create base pages to represent common parts – E.g. same header, footer, sidebar • Reuse common widgets in each affected pages • Use your pages to initiate and confirm the success of navigation • Put your verification methods inside the page object as well Cucumber agenda 1. Understanding Cucumber 2. Syntax 3. Best practices UNDERSTANDING CUCUMBER BDD Quick Recap • BDD is TDD done right • Encourages communication between business, QA and dev teams • Driven by business value • Extends TDD by using natural language understandable for non technical people (Given When Then) • Test cases can even be created by product owners, business analysts, TPMs. • Cucumber is the most well known BDD framework. Used technologies Cucumber Java Page/widget model Se [Diagram of used technologies: Cucumber, Java, Page/widget model, Se] Pros and Cons Advantages - Provides a form of documentation (feature file) - Focus on functionality, operation and behavior - Test cases are understandable for non-tech stakeholders - common language with business - New tests are easy to create by reusing exiting steps - Plays nicely with TDD, BDD Disadvantages - More layers for testers - More time consuming Feature: A feature would describe the current test script which has to be executed. Scenario: Scenario describes the steps and expected outcome for a particular test case. Scenario Outline: Same scenario can be executed for multiple sets of data using scenario outline. The data is provided by a tabular structure separated by (| |). Given: It specifies the context of the text to be executed. And: use this keyword when multiple steps are of the same type are required When: "When" specifies the test action that has to performed Then: The expected outcome of the test can be represented by "Then" But: another way to start your step In the feature file: Given the following animals: cow, horse, sheep Translates to the following code: @Given("the following animals: (.*)") public void the_following_animals(List<String> animals) { //do something terrible } Cucumber in Eclipse Add JARs to your project ![Image of Eclipse showing JARs in the build path](image-url) Cucumber in Eclipse Help -> Install New Software Work with: Cucumber [Image of Eclipse menu showing "Install New Software"] [Image of Eclipse dialog box showing "Available Software" and "Update Site: http://cucumber.github.com/cucumber-eclipse/update-site"] Basic scenario @basic Scenario: Create a search between two cities Given I open Elvira page When I create a search from "Székesfehérvár" to "Sopron" And I submit the search from Then the search result title should contain "Székesfehérvár" and "Sopron" Scenario: Create a search between two cities using tables Given I open Elvira page When I create a search with the following parameters | from | Szolnok | | to | Debrecen | | via | Hajdúszoboszló| And I submit the search from Then the search result title should contain the following city names | Szolnok | | Debrecen | | Hajdúszoboszló | Advanced tables scenario **Scenario Outline:** Create an advanced search between two cities **Given** I open Elvira page **When** I create a search with the following parameters <table> <thead> <tr> <th>from</th> <th>&lt;fromCity&gt;</th> </tr> </thead> <tbody> <tr> <td>to</td> <td>&lt;toCity&gt;</td> </tr> <tr> <td>via</td> <td>&lt;viaCity&gt;</td> </tr> </tbody> </table> **And** I submit the search from **Then** the search result title should contain the following city names | <fromCity> | | <toCity> | | <viaCity> | @tag1 **Examples:** <table> <thead> <tr> <th>fromCity</th> <th>toCity</th> <th>viaCity</th> </tr> </thead> <tbody> <tr> <td>Szolnok</td> <td>Debrecen</td> <td>Hajdúszoboszló</td> </tr> </tbody> </table> @tag2 **Examples:** <table> <thead> <tr> <th>fromCity</th> <th>toCity</th> <th>viaCity</th> </tr> </thead> <tbody> <tr> <td>Budapest</td> <td>Sopron</td> <td>Tata</td> </tr> </tbody> </table> Cucumber 3 BEST PRACTICES Cucumber tips 1 1. Keep a feature file feature specific 2. Use tags (dependencies, test levels, environments) Cucumber tips 2 1. Create independent and deterministic scenarios 2. Don’t forget non-happy paths Cucumber tips 3 1. Follow the one step one thing rule 2. Use nested steps sparsely (calling steps from steps) Cucumber tips 4 1. Use an object (table) for multiple test data values - Helps adding, removing test data 2. Use global containers for data used by multiple scenarios - Helps fast changes (e.g. passwords, ids) Cucumber tips 5 1. Refactor and Reuse Step Definitions 2. Look for opportunities to generalize Questions
{"Source-Url": "http://compalg.inf.elte.hu/~attila/materials/Webdriver_Java_2015.pdf", "len_cl100k_base": 4350, "olmocr-version": "0.1.53", "pdf-total-pages": 86, "total-fallback-pages": 0, "total-input-tokens": 115378, "total-output-tokens": 7579, "length": "2e12", "weborganizer": {"__label__adult": 0.0003502368927001953, "__label__art_design": 0.00035190582275390625, "__label__crime_law": 0.0002624988555908203, "__label__education_jobs": 0.002666473388671875, "__label__entertainment": 5.048513412475586e-05, "__label__fashion_beauty": 0.00013768672943115234, "__label__finance_business": 0.00015413761138916016, "__label__food_dining": 0.0002727508544921875, "__label__games": 0.0004394054412841797, "__label__hardware": 0.00040841102600097656, "__label__health": 0.00023031234741210935, "__label__history": 0.0001671314239501953, "__label__home_hobbies": 0.00010323524475097656, "__label__industrial": 0.0002446174621582031, "__label__literature": 0.0001760721206665039, "__label__politics": 0.00015544891357421875, "__label__religion": 0.0003337860107421875, "__label__science_tech": 0.00138092041015625, "__label__social_life": 0.00012731552124023438, "__label__software": 0.005645751953125, "__label__software_dev": 0.9853515625, "__label__sports_fitness": 0.0003573894500732422, "__label__transportation": 0.0003216266632080078, "__label__travel": 0.00021719932556152344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 17045, 0.00759]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 17045, 0.36274]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 17045, 0.55188]], "google_gemma-3-12b-it_contains_pii": [[0, 105, false], [105, 180, null], [180, 180, null], [180, 422, null], [422, 738, null], [738, 759, null], [759, 928, null], [928, 1063, null], [1063, 1087, null], [1087, 1229, null], [1229, 1649, null], [1649, 1838, null], [1838, 2133, null], [2133, 2391, null], [2391, 2630, null], [2630, 2967, null], [2967, 3383, null], [3383, 3709, null], [3709, 4066, null], [4066, 4424, null], [4424, 4767, null], [4767, 4790, null], [4790, 4913, null], [4913, 5332, null], [5332, 5445, null], [5445, 5678, null], [5678, 5688, null], [5688, 5788, null], [5788, 5804, null], [5804, 6069, null], [6069, 6312, null], [6312, 6573, null], [6573, 6983, null], [6983, 7011, null], [7011, 7321, null], [7321, 7524, null], [7524, 7524, null], [7524, 7778, null], [7778, 7794, null], [7794, 8001, null], [8001, 8219, null], [8219, 8499, null], [8499, 8754, null], [8754, 8952, null], [8952, 8952, null], [8952, 9144, null], [9144, 9327, null], [9327, 9606, null], [9606, 9805, null], [9805, 9815, null], [9815, 9879, null], [9879, 9899, null], [9899, 10085, null], [10085, 10302, null], [10302, 10528, null], [10528, 10787, null], [10787, 10820, null], [10820, 10936, null], [10936, 11140, null], [11140, 11367, null], [11367, 11655, null], [11655, 11962, null], [11962, 12270, null], [12270, 12586, null], [12586, 12885, null], [12885, 12885, null], [12885, 12956, null], [12956, 12979, null], [12979, 13338, null], [13338, 13463, null], [13463, 13828, null], [13828, 13828, null], [13828, 14465, null], [14465, 14694, null], [14694, 14803, null], [14803, 15065, null], [15065, 15322, null], [15322, 15688, null], [15688, 16371, null], [16371, 16398, null], [16398, 16510, null], [16510, 16610, null], [16610, 16721, null], [16721, 16939, null], [16939, 17036, null], [17036, 17045, null]], "google_gemma-3-12b-it_is_public_document": [[0, 105, true], [105, 180, null], [180, 180, null], [180, 422, null], [422, 738, null], [738, 759, null], [759, 928, null], [928, 1063, null], [1063, 1087, null], [1087, 1229, null], [1229, 1649, null], [1649, 1838, null], [1838, 2133, null], [2133, 2391, null], [2391, 2630, null], [2630, 2967, null], [2967, 3383, null], [3383, 3709, null], [3709, 4066, null], [4066, 4424, null], [4424, 4767, null], [4767, 4790, null], [4790, 4913, null], [4913, 5332, null], [5332, 5445, null], [5445, 5678, null], [5678, 5688, null], [5688, 5788, null], [5788, 5804, null], [5804, 6069, null], [6069, 6312, null], [6312, 6573, null], [6573, 6983, null], [6983, 7011, null], [7011, 7321, null], [7321, 7524, null], [7524, 7524, null], [7524, 7778, null], [7778, 7794, null], [7794, 8001, null], [8001, 8219, null], [8219, 8499, null], [8499, 8754, null], [8754, 8952, null], [8952, 8952, null], [8952, 9144, null], [9144, 9327, null], [9327, 9606, null], [9606, 9805, null], [9805, 9815, null], [9815, 9879, null], [9879, 9899, null], [9899, 10085, null], [10085, 10302, null], [10302, 10528, null], [10528, 10787, null], [10787, 10820, null], [10820, 10936, null], [10936, 11140, null], [11140, 11367, null], [11367, 11655, null], [11655, 11962, null], [11962, 12270, null], [12270, 12586, null], [12586, 12885, null], [12885, 12885, null], [12885, 12956, null], [12956, 12979, null], [12979, 13338, null], [13338, 13463, null], [13463, 13828, null], [13828, 13828, null], [13828, 14465, null], [14465, 14694, null], [14694, 14803, null], [14803, 15065, null], [15065, 15322, null], [15322, 15688, null], [15688, 16371, null], [16371, 16398, null], [16398, 16510, null], [16510, 16610, null], [16610, 16721, null], [16721, 16939, null], [16939, 17036, null], [17036, 17045, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 17045, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 17045, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 17045, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 17045, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 17045, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 17045, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 17045, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 17045, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, true], [5000, 17045, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 17045, null]], "pdf_page_numbers": [[0, 105, 1], [105, 180, 2], [180, 180, 3], [180, 422, 4], [422, 738, 5], [738, 759, 6], [759, 928, 7], [928, 1063, 8], [1063, 1087, 9], [1087, 1229, 10], [1229, 1649, 11], [1649, 1838, 12], [1838, 2133, 13], [2133, 2391, 14], [2391, 2630, 15], [2630, 2967, 16], [2967, 3383, 17], [3383, 3709, 18], [3709, 4066, 19], [4066, 4424, 20], [4424, 4767, 21], [4767, 4790, 22], [4790, 4913, 23], [4913, 5332, 24], [5332, 5445, 25], [5445, 5678, 26], [5678, 5688, 27], [5688, 5788, 28], [5788, 5804, 29], [5804, 6069, 30], [6069, 6312, 31], [6312, 6573, 32], [6573, 6983, 33], [6983, 7011, 34], [7011, 7321, 35], [7321, 7524, 36], [7524, 7524, 37], [7524, 7778, 38], [7778, 7794, 39], [7794, 8001, 40], [8001, 8219, 41], [8219, 8499, 42], [8499, 8754, 43], [8754, 8952, 44], [8952, 8952, 45], [8952, 9144, 46], [9144, 9327, 47], [9327, 9606, 48], [9606, 9805, 49], [9805, 9815, 50], [9815, 9879, 51], [9879, 9899, 52], [9899, 10085, 53], [10085, 10302, 54], [10302, 10528, 55], [10528, 10787, 56], [10787, 10820, 57], [10820, 10936, 58], [10936, 11140, 59], [11140, 11367, 60], [11367, 11655, 61], [11655, 11962, 62], [11962, 12270, 63], [12270, 12586, 64], [12586, 12885, 65], [12885, 12885, 66], [12885, 12956, 67], [12956, 12979, 68], [12979, 13338, 69], [13338, 13463, 70], [13463, 13828, 71], [13828, 13828, 72], [13828, 14465, 73], [14465, 14694, 74], [14694, 14803, 75], [14803, 15065, 76], [15065, 15322, 77], [15322, 15688, 78], [15688, 16371, 79], [16371, 16398, 80], [16398, 16510, 81], [16510, 16610, 82], [16610, 16721, 83], [16721, 16939, 84], [16939, 17036, 85], [17036, 17045, 86]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 17045, 0.03473]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
df1b217e5511034526de60949f9c1611a806a127
Optimising Shared Reduction Variables in MPI Programs A.J. Field, P.H.J. Kelly and T.L. Hansen Department of Computing, Imperial College 180 Queen's Gate, London SW7 2BZ, U.K. {ajf,phjk,tilh}@doc.ic.ac.uk Abstract. CFL (Communication Fusion Library) is an experimental C++ library which supports shared reduction variables in MPI programs. It uses overloading to distinguish private variables from replicated, shared variables, and automatically introduces MPI communication to keep replicated data consistent. This paper concerns a simple but surprisingly effective technique which improves performance substantially: CFL operators are executed lazily in order to expose opportunities for run-time, context-dependent, optimisation such as message aggregation and operator fusion. We evaluate the idea using both toy benchmarks and a 'production' code for simulating plankton population dynamics in the upper ocean. The results demonstrate the software engineering benefits that accrue from the use of the library and show that performance close to that of manually optimised code can be achieved automatically in many cases. 1 Introduction In this paper we describe an experimental abstract data type for representing shared variables in SPMD-style MPI programs. The operators of the abstract data type have a simple and intuitive semantics and hide any required communication. Although there are some interesting issues in the design of the library, the main contribution of this paper is to show how lazy evaluation can expose run-time optimisations that may be difficult, or even impossible, to spot using conventional compile-time analysis. The paper makes the following contributions: - We present a simple and remarkably useful prototype class library which simplifies certain kinds of SPMD MPI programs - We discuss some of the design issues in such a library, in particular the interpretation of the associated operators - We show how lazy evaluation of the communication needed to keep replicated variables consistent can lead to substantial performance advantages - We evaluate the work using both toy examples and a large-scale application This paper extends our brief earlier paper [2] in providing better motivation and further experimental results, as well as a more thorough description of the technique. 2 The Idea Figure 1 illustrates the basic idea. This is a toy C++ application which computes the sample variance of \( N \) batches of \( M \) data items, stored in an \( N \times M \) array. The data is replicated over \( P \) processors and each processor computes its contribution to the sum and sum-of-squares of each batch of data using appropriately defined methods. An MPI reduction operation sums these contributions. The main loop fills the variance array (\( \text{var} \)). This program suffers two drawbacks. Firstly, the code is convoluted by the need to code the communication explicitly—an artefact of all MPI programs. Secondly, it misses an optimisation opportunity: the two reduction operations can be fused (i.e. resolved using a single communication to sum the contributions to \( s1 \) and \( s2 \) at the same time) since the evaluation of \( \text{sumsq} \) does not depend on that of \( \text{sum} \). If the two reduction operations are brought out of the methods \( \text{sum} \) and \( \text{sumsq} \) and combined into a single reduction over a two-element vector in the outer loop a performance benefit of around 43% is achieved using four 300MHz UltraSparc processors of a Fujitsu AP3000 with \( N=M=3000 \). Further results for this benchmark are reported in Section 5. Spotting this type of optimisation at compile time requires analysing across method boundaries. While perfectly feasible in this case, in general these op- erations may occur deep in the call graph, and may be conditionally executed, making static optimisation difficult. The alternative we explore in this paper is to attempt the optimisation at run-time, requiring no specialist compiler support. We have developed a prototype library called CFL (Communication Fusion Library) designed to support shared reduction variables. The library can be freely mixed with standard MPI operations in a SPMD application. C++ operator overloading is used to simplify the API by using existing operators (e.g. +, *, += etc.). Where an operation would normally require communication e.g. when a shared reduction variable is updated with the value of a variable local to each processor, the communication is handled automatically. Figure 1 shows how the CFL library can be used to model the shared quanti- ties $a_1$ and $a_2$ in the previous example. This eliminates all the explicit com- munication, in the spirit of shared-memory programming. However, the main benefit comes from CFL’s lazy evaluation: just prior to the assignment to $var[4]$ no communication has yet taken place. The assignment forces both delayed com- munications and resolves them using a single reduction operation, akin to the manual optimisation outlined above. There are some overheads associated with the maintenance of these shared variables, so we would not expect to achieve the performance of the manually optimised code. Nonetheless, this very sim- ple example, with scope for just two fusions per iteration, yields a performance improvement of around 37% when compared to the original code on the same platform. Again more detailed results are presented in Section 5. In the remainder of this paper we present some relevant background to the work (Section 3), discuss the semantics of shared variables in the context of MPI programs (Section 4) and present some performance benchmarks for both contrived test programs and a production oceanography simulation (Section 5). The conclusions are presented in Section 6. 3 Related work The idea of delaying execution in order to expose optimisation opportunities has appeared before. POOMA [4] uses expression templates in C++ to support explicit construction and then evaluation of expressions involving arrays and communication. A delayed-evaluation self-optimising (DESO) numerical library for a distributed memory parallel computer is described in [7]. By delaying the evaluation of operations, the library is able to capture the data-flow graph of the computation. Knowing how each value is to be used, the library is able to calculate an optimised execution plan by propagating data placement constraints backwards through the DAG. This means that the library is able to calculate a very efficient initial distribution for the data across the processors, and hence fewer redistributions of the data will be necessary. A related idea, which is exploited in BSP [3] and KeLP [10], is to organ- ise communication in a global collective operation. This allows multiple small messages to be aggregated, and also provides the opportunity to schedule communication to avoid network and buffer contention. A shared-memory programming model can be supported on distributed-memory hardware using a page-based consistency protocol; sophisticated implementations such as TreadMarks [5] support some run-time adaptation, for example for pages with multiple writers. However, Treadmarks offers no special support for reductions. 4 Shared variables in SPMD programs In a data-parallel SPMD program, a large data structure is distributed across each processor, and MPI is used to copy data to where it is needed. In contrast, we focus in this paper on the program's global state variables. In a distributed-memory implementation, each processor holds its own copy of each shared variable. When the variable is updated, communication is needed to ensure that each processor's copy is up to date. In the context of this paper we focus exclusively on scalar double-precision floating-point variables. The semantics of arithmetic operations on private variables are very well-understood, but are not so straightforward for shared variables as an operation on a shared double will be executed on several processors. The interesting case concerns the assignment of the result of an arithmetic expression to a variable. In what follows, $x$, $y$, and $z$ will refer to (global) shared variables (i.e. of type `CFL_Double`) and $a$, $b$ to local variables private to each processor. Each processor maintains a local copy of each shared variable and the library must ensure that after each operation these copies are consistent. If the target variable of an assignment is local, as in $a = x - b$ then the assignment can be performed concurrently on each processor without (additional) communication. However, if the result is stored in a shared variable then the behaviour depends on the operator arguments. If both operator arguments are shared, as in $x = y * z$ then again the assignment can be effected locally. However, if one of the arguments is local and the other shared, as in $x += a$ or $x = y + a$, then our interpretation is that each processor contributes its own update to $x$, implying a global reduction operation, with the rule that $x -= a$ is interpreted as $x += (-a)$. Because CFL is lazy, one or more of the shared variables on the right-hand side of an assignment may already contain a pending communication, either from an earlier assignment or an intermediate expression on the same right-hand side, as in $x = y + a - z$. Any new required communication is simply added to those currently pending. Similar rules apply to the other operators $-$, $*$, / etc. and combined operations like $+=$ have the same meaning as their expanded equivalents, e.g. $x += a$ and $x = x + a$. Assignment and reduction. Note that the way the assignment $v += e$ is implemented now depends on the nature of $v$ and $e$. It is tempting to think that any potential confusion can be overcome by using a different operator symbol when a global reduction is intended, for instance \( x \leftarrow a \) instead of \( x = a \). However the assignment \( x = x + a \) should have the same meaning so we would also need special versions of + (and the other operators) to cover all combinations of argument types. We thus choose to stick to the familiar symbols using the overloading, but propose the use of naming conventions to distinguish shared from local variables where any confusion may arise. An attempt to assign a local variable to a shared variable either directly (e.g. \( x = a \)) or as a result of a calculation involving only local variables (e.g. \( x = a - b \)) is disallowed. ### 4.1 Delaying communication The parallel interpretation of some operator uses such as \( x \leftarrow a \) means that at any point a shared variable may need to synchronise with the other processors. Because each processor sees the variable in the same state every processor will know that the variable needs synchronisation. Moreover, as operations are executed in the same order on all the processors (the SPMD model), shared variables will acquire the need for synchronisation in the same order on every processor. This means that, in order to delay communication, we need only maintain a list of all the variables that need to be synchronised, and in what way. When communication is forced (see below) these synchronisations are piggybacked onto a single message with an associated reduction operator. An alternative would be to initiate a non-blocking communication instead; although this might be appropriate for some hardware, little or no computation/communication overlap is possible in most current MPI implementations. An assignment of a shared variable to a local variable constitutes a **force point**. At this point a communications manager marshalls all CFL variable updates into a single array and performs a single global reduction operation over that array. On completion, the resulting values are used to update all CFL_Doubles which were previously pending communication. In principle, the synchronisation of a shared variable may be delayed until its global value is required (force point), but in practice the synchronisation may be forced earlier than this, e.g. when another shared variable synchronisation is forced before it. Forcing any delayed synchronisation will force all such synchronisations. **Limitations** In the prototype implementation of CFL only ‘additive’ operators (+, -, +=, -=) are handled lazily at present. This is sufficient for experimental evaluation of the basic idea. The other operators (and the copy constructor) are all supported but they force all pending communication. Implementing the remaining operators lazily requires a little more work to pack the data for communication and to construct the associated composite reduction operation, but is otherwise straightforward. This is left as future work. Table 1. AP3000 execution times (in seconds) for Figure 1 for various problem sizes, with percentage speedup relative to the original, unoptimised code. <table> <thead> <tr> <th>N</th> <th>AP3000 (P=4) Execution time(s)</th> </tr> </thead> <tbody> <tr> <td></td> <td>Original</td> </tr> <tr> <td>500</td> <td>0.341</td> </tr> <tr> <td>1000</td> <td>0.748</td> </tr> <tr> <td>1500</td> <td>1.159</td> </tr> <tr> <td>3000</td> <td>2.544</td> </tr> </tbody> </table> 5 Evaluation Our performance results are from dedicated runs on three platforms: a Fujitsu AP3000 (80 nodes, each a 300MHz Sparc Ultra II processor with 128 RAM, with Fujitsu's 200MB/s AP-Net network), a Quadrics/COMPAQ cluster (16 nodes, each a Compaq DS20 dual 667MHz Alpha with 1GB RAM), and a cluster of dual 400MHz Celeron PCs with 128MB RAM on 100Mb/s switched Ethernet. In each case there was one MPI process per node. 5.1 Toy Benchmark Table 1 shows the execution times for the toy benchmark of Figure 1 for four problem sizes for the AP3000 platform using 4 processors. Here the data matrix is assumed to be square, so the problem size defines both M and N. The figures in parentheses show the reduction in execution time, relative to the original unoptimised code. The results show that a significant performance improvement can be achieved by fusing the communications, even though only two such communications can be fused at any time. The results also show, as one would expect, diminishing returns for the CFL library, relative to the hand-optimised code, as the problem size increases. This is because larger problems incur a smaller communication overhead, so the overhead of maintaining the shared variable state takes greater effect. We would intuitively expect the performance of the CFL library to improve, relative to the hand-optimised code, for platforms with slower communication networks (measured by a combination of start-up cost and bandwidth) and vice versa. This is borne out by Table 2 which shows the performance of the same benchmark on our three reference platforms, using 4 processors in each case and with a problem size of 3000. Relative to the hand-optimised code, the CFL library performs extremely well on the PC cluster. However, on the COMPAQ platform, which has a very fast communication network, the overheads of supporting lazy evaluation outweigh the benefits of communication fusion. The example of Figure 1 enables exactly two reductions to be fused on each iteration of the loop. In some applications (see below, for example) it may be possible to do better. The variance example was therefore generalised artificially. Figure 2. Variance calculation (3000 x 3000 array) on 4 processors: performance of original MPI code versus CFL library. by introducing an extra loop that called the sum function (only) a given number of times, \( n \), on each iteration of the outer \( (i) \) loop. The results were stored in an array and later summed (again arbitrary, but this has the effect of forcing communication in the CFL case). The objective was to measure the cost of performing repeated (explicit) MPI reduction operations relative to the cost of fusing them within CFL. The results for 4 processors on each platform with \( N = 3000 \) are shown in Figure 2. Note that the slope of the two curves (original MPI vs. CFL) in each case expose these relative costs and we can see why CFL wins out on both the AP3000 and PC cluster. Conversely, on the COMPAQ platform no amount of fusion opportunity can buy back the performance overheads inherent in the current CFL implementation. 5.2 Oceanography Simulation We now present the results obtained when the CFL library was used to model shared variables in a large-scale simulation of plankton population dynamics in the upper ocean using the Lagrangian Ensemble method [9]. Some discussion of the code structure is in order. The simulation is based on a one-dimensional water column which is stratified into 500 layers each 1 m deep. The plankton are grouped into \textit{particles} each of which represents a sub-population of identical individuals. The particles move by a combination of turbulence and sinking/swimming and interact with their local environment according to rules derived from laboratory observation. The simulation is built by composing modules each of which models an aspect of the physics, biology or chemistry. The exact configuration may vary from one simulation to the next. To give a flavour for the structure of a typical code, the dominant (computationally speaking) component of a particular instance called "ZF" models phytoplankton by the sequential composition of four modules: \texttt{Move()}, \texttt{Energy()}, \texttt{Nutrients()} and \texttt{Evolve()} (motion, photosynthesis, nutrient uptake and birth/death). A similar structure exists for zooplankton. The model essentially involves calling these (and the many other) modules in the specified order once per time-step. In parallelising the model a vertical partitioning strategy is used to divide the plankton particles among the available processors. The processors cooperate through \textit{environment variables} which represent the chemical, physical and biological attributes of each layer. The parallelisation strategy requires that each processor sees the same global environment at all times. <table> <thead> <tr> <th>Platform</th> <th>Execution time(s) ((N=3000))</th> <th>Original</th> <th>Hand optimised</th> <th>CFL</th> </tr> </thead> <tbody> <tr> <td>AP3000</td> <td>2.544</td> <td>1.463((42.8%))</td> <td>2.119((46.7%))</td> <td></td> </tr> <tr> <td>Cluster</td> <td>7.154</td> <td>3.670((48.7%))</td> <td>3.968((44.5%))</td> <td></td> </tr> <tr> <td>COMPAQ</td> <td>0.263</td> <td>0.161((38.9%))</td> <td>1.418((-58.8%))</td> <td></td> </tr> </tbody> </table> Table 2. Execution times for Figure 1 for various platforms. The various modules have been developed independently of the others, although they must fit into a common framework of global variables, management structures etc. Within these modules there are frequent updates to the shared variables of the framework and it is common for these to be assigned in one module and used in a later one. This relatively large distance between the producer and consumer provides good scope for message aggregation. However, manual optimisation will work only for that particular sequence of modules: adding a new module or changing the order of existing modules changes the data dependency. This is where the CFL library is particularly beneficial: it will automatically fuse the maximum possible number of reduction operations (i.e. those that arise between force points). We begin with the original (parallel) version of ZB and then hand-optimised it by manually working out the data dependencies between the global shared quantities and identifying force points. The fusion was actually achieved by building a lazy version of MPI_All Reduce [1]. This simplified the implementation significantly but introduced some overheads, very similar in fact to those in CFL. The MPI code was then rewritten using the CFL library, simply by marking the shared environment variables as CFL doubles. The original code uses exclusively MPI reduction operations so the immediate effect of using CFL is to remove all explicit communication from the program. The effect of the message aggregation (both manual and using CFL) is to reduce the number of synchronisations from 27 to just 3 in each time step. In one of these no less than 11 reduction operations were successfully fused between force points. AP3000 timing results for the execution of the ZB model before and after CFL was incorporated are shown in Table 3 for a problem size of 320,000 particles. Both hand-optimised and CFL versions of the model have very similar performance but this is not surprising given the way the hand-optimisation was done. **Remarks** In order to use the CFL library in this case study, we had to turn off one feature of the model. During nutrient uptake the required reduction operation is actually **bounded** in the sense that the `=` operator would not normally allow the (shared) nutrient variable to become negative; instead the uptake would be reduced so as to exactly deplete the nutrient. It is perfectly possible to build such bounded reductions into CFL but they are not currently supported. 6 Conclusions This paper presents a simple idea, which works remarkably well in many cases. We have built a small experimental library on top of MPI which enables shared scalar variables in parallel SPMD-style programs to be represented as an abstract data type. By implementing the library in C++ and using C++'s operator overloading, the familiar arithmetic operator symbols, such as +, -, * etc. can be used on shared variables. Some operators have a parallel reading when the target of an assignment is another shared variable. Because the operations are abstract, dynamic run-time optimisations can be built into their implementation. We have shown how delayed evaluation can be used to piggyback communications on top of earlier, as yet unevaluated, parallel operations. This means that the communication associated with a global reduction, for example, may actually take place as a side-effect of another reduction operation in a different part of the code. This avoids reliance on sophisticated compile-time analyses and can exploit opportunities which arise from dynamic data dependencies. Using a contrived test program and a realistic case study we have demonstrated very pleasing performance improvements on some platforms. Unsurprisingly, the greatest performance benefits are seen on platforms with slower communication networks. In essence, what we have done is to implement an application-specific cache coherence protocol, in the spirit of, among others, [11]. This hides consistency issues, and the associated communication, from the programmer, with obvious benefits in software engineering terms. Could we achieve the reduction fusion optimisation by executing standard MPI functions lazily? Not without compiler support, since the results of the MPI operation are delivered to normal private data so we don’t know when to force communication. The library is currently very much a prototype. Nonetheless, the current implementation is robust and has proven to be of surprising utility, both in performance and ease of use. We are now seeking to extend the library (for example to handle arrays as well as scalars) and to focus on internal optimisations to reduce management overheads. References 7. O. Beckmann, P. H. J. Kelly: Efficient Interprocedural Data Placement Optimisation in a Parallel Library. LCR ’98
{"Source-Url": "http://www.doc.ic.ac.uk/~phjk/Publications/SharedReductionVarsEuroPar2002.pdf", "len_cl100k_base": 4942, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 51644, "total-output-tokens": 6103, "length": "2e12", "weborganizer": {"__label__adult": 0.0003685951232910156, "__label__art_design": 0.00031685829162597656, "__label__crime_law": 0.00036978721618652344, "__label__education_jobs": 0.000492095947265625, "__label__entertainment": 9.763240814208984e-05, "__label__fashion_beauty": 0.00018453598022460935, "__label__finance_business": 0.00023245811462402344, "__label__food_dining": 0.00046133995056152344, "__label__games": 0.000522613525390625, "__label__hardware": 0.00182342529296875, "__label__health": 0.0007762908935546875, "__label__history": 0.00033545494079589844, "__label__home_hobbies": 0.00012993812561035156, "__label__industrial": 0.0006804466247558594, "__label__literature": 0.0002446174621582031, "__label__politics": 0.0003709793090820313, "__label__religion": 0.0005645751953125, "__label__science_tech": 0.088134765625, "__label__social_life": 0.0001132488250732422, "__label__software": 0.008331298828125, "__label__software_dev": 0.89404296875, "__label__sports_fitness": 0.00044345855712890625, "__label__transportation": 0.0007920265197753906, "__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, 25481, 0.03741]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 25481, 0.38305]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 25481, 0.9045]], "google_gemma-3-12b-it_contains_pii": [[0, 2328, false], [2328, 3631, null], [3631, 6830, null], [6830, 9890, null], [9890, 12804, null], [12804, 15471, null], [15471, 15592, null], [15592, 18698, null], [18698, 20972, null], [20972, 23804, null], [23804, 25481, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2328, true], [2328, 3631, null], [3631, 6830, null], [6830, 9890, null], [9890, 12804, null], [12804, 15471, null], [15471, 15592, null], [15592, 18698, null], [18698, 20972, null], [20972, 23804, null], [23804, 25481, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 25481, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 25481, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 25481, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 25481, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 25481, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 25481, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 25481, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 25481, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 25481, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 25481, null]], "pdf_page_numbers": [[0, 2328, 1], [2328, 3631, 2], [3631, 6830, 3], [6830, 9890, 4], [9890, 12804, 5], [12804, 15471, 6], [15471, 15592, 7], [15592, 18698, 8], [18698, 20972, 9], [20972, 23804, 10], [23804, 25481, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 25481, 0.09756]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
ab6d7c31c60b4cd38ea410234c8b30468089b103
Virtual Machines Should Be Invisible Stephen Kell Department of Computer Science University of Oxford stephen.kell@cs.ox.ac.uk Conrad Irwin* Corpus Christi College University of Cambridge ctji2@cantab.net Abstract Current VM designs prioritise implementor freedom and performance, at the expense of other concerns of the end programmer. We motivate an alternative approach to VM design aiming to be unobtrusive in general, and prioritising two key concerns specifically: foreign function interfacing and support for runtime analysis tools (such as debuggers, profilers etc.). We describe our experiences building a Python VM in this manner, and identify some simple constraints that help enable low-overhead foreign function interfacing and direct use of native tools. We then discuss how to extend this towards a higher-performance VM suitable for Java or similar languages. Categories and Subject Descriptors D.3.4 [Programming Languages]: Processors—run-time environments, debuggers, compilers General Terms Languages 1. Introduction Virtual machines exist to support language implementations. As Cliff Click noted in last year’s workshop keynote, a modern virtual machine (VM) is packed with services, covering most of what interests a language implementor: code generation, memory management, linking, loading, optimisation, profiling, and more. End programmers care about languages and libraries, not about virtual machines. While the languages a VM supports can bring valuable abstractions to the programmer, virtual machines themselves bring costly distractions. Each class of VM brings its own set of invocation interfaces, configuration mechanisms, foreign function interfacing (FFI) conventions, and suite of tools for debugging and profiling. Developers are familiar with VMs because their peculiarities are entangled with practicalities of various languages. Ideally, however, VMs would be invisible: they would exist as libraries silently supporting the languages and libraries required by programmers, as unobtrusively as possible. In this paper we argue that VMs may be made far less obtrusive than they currently are. Our conception of an “invisible” VM is neither fully achievable nor precisely defined, but is intended to draw attention to a general phenomenon: that the concerns of end programmers fail to align with those of implementors. Implementors are usually motivated to build a system which executes a single language (or a suite of benchmarks) as fast as possible. By contrast, end programmers want a system which is fast enough (which varies according to deployment scenario), which lets them analyse their code using familiar and powerful tools, and which lets them re-use whatever existing code will shorten their task. For most of this paper we focus on two specific issues where current VMs are especially obtrusive: foreign function interfacing and run-time tool support. By the latter, we refer to debuggers, profilers, race detectors and similar dynamic analysis tools. For the former problem, our goal is to give programmers the ability to treat language as a per-function implementation choice, with negligible interfacing effort in most common cases. For the latter, our goal is a design that bestows on existing whole-program analysis tools, given only minor modifications, a first-class understanding of code running on our VMs. Our approach is to consider a minimal set of “reasonable constraints” on VM authors, in the form of conventions and skeleton structures, that can allow cooperation across native–VM and VM–VM boundaries. This includes sharing of code, data and metadata, and a shared metamodel. Where possible, we “embrace and extend” existing facilities in operating systems and native-code compilers in preference to reinventing them at the VM level. By contrast, current designs have arisen from giving implementors free rein to reinvent, customise and optimise. This is the author’s version of the work. It is available here by permission of ACM for your personal use. Not for redistribution. The definitive version will be published in SPLASH'11 Workshops. Copyright © ACM [to be supplied] . . . $10.00 Specifically, this paper presents the following contributions. - We describe our efforts implementing the Python language in invisible fashion, detailing various techniques for minimising FFI overhead and cooperating with debugging tools. - We generalise these experiences to identify three design invariants: supporting linkage, data representation, and runtime metadata. Together these allow VMs to share a core object model and descriptive framework with native code, while retaining freedom to support diverse source languages, intermediate representations, and code generation. - We discuss the evolution of our design towards whole-program dynamic optimisation, arguing that the wealth of code transformations within modern VMs should be broken out into a system-wide service integrated into the dynamic linker. 2. Building an invisible Python Predating the grandiose ideal of invisible VMs, our original goal was to build an implementation of our chosen dynamic language, Python, which could be used to write scripts against native libraries interactively and dynamically. Whereas conventional wisdom was that interfacing with native libraries required glue code, generated either from annotated header files (the approach of Swig [1]) or metaprogramming (as with other tools such as the approach of Boost.Python), we considered how to make our implementation less obtrusive by dispensing with this step. 2.1 Parathon Our insight was that compiled-generated debugging information necessarily offers descriptions of native libraries’ interfaces at run time. The burden of interpreting native objects could be shouldered by the interpreter itself, dynamically interpreting this information much like a debugger, rather than by ahead-of-time glue coding. We adopted the DWARF format [6], de facto standard on Unix platforms, and include a brief introduction as an Appendix. The result was Parathon, an implementation of a usable subset of Python which understands two kinds of object: those it created, described by an internal metamodel, and those created by native code, described by DWARF. Garbage was collected by the conservative Boehm collector [2], co-existing well with the C library’s heap. Numerous limitations remained: a Pythonic rendering of functions’ output parameters was impossible without extra annotation; lists and arrays remained largely incompatible; Pythonic structural treatment of objects was conspicuously unsupported when making native calls. However, Parathon was sufficient to prove the concept of supporting native Python coding using debugging information. Fig. 1 shows a simple C API that became an early test-case, and the CPython wrapper code that would ordinarily be used. In Parathon, our interpreter performs these operations, or their analogues, without any such direction, using only the DWARF information: a DWARF database replaces explicitly managed type objects (comment 1); underlying functions are called through libffi (2), and garbage collection makes reference count adjustments unnecessary (3). Arguments are extracted directly from the calling stack frame, and marshalling is either unnecessary or inferred by comparing DWARF types. Fig. 2 shows a sample session, which runs without any wrapper code generation. However, Parathon was not entirely satisfactory. There was no way to debug code at the Python source level. Backtraces did not exhibit the Python call stack. Internally, a lot of complexity derived from the split between the two kinds of object. Passing callbacks to native code involved allocating closures generated by libffi, but it was not clear when these could be deallocated. Native objects were not first-class: for example, Python-style dynamic field insertions or removals could not be performed on them. To build a proper Python without huge escalation in complexity, a more uniform approach was required. 2.2 Towards DwarfPython Our next insight was that the same DWARF metamodel used to describe native code and its data could also be Figure 2. A trivial Parathon session ```python import c # ensure libc (+DWARF) loaded s = stat() # construct a stat object stat("/etc/passwd", s) # call through libffi print s {s.st_dev = 42, ... (snipped) } # access fields using DWARF def bye(): # defining a Python function don{... print "Goodbye, world!"} atexit(bye) # construct libffi closure import m # import another library print log2(s.st_size) # call some more functions Figure 3. Using process context as interpreter context --- scribe Python code and its data. Moreover, the dynamism of the Python language could be supported modern operating systems' and compilers' existing debugging infrastructure. (Any gaps in this would also be weaknesses encountered during debugging, hence worth fixing within DWARF.) In other words, Python's main distinction is not its machine model but its language semantics, and this can be isolated within our Python interpreter, where it is invisible to other code in the process—Python becomes an implementation detail that can be hidden inside a function's implementation. One illustration of the shift from Parathon to DwarfPython is in its notion of execution context. Like many interpreters, Parathon threads an environment and other shared state through its internal calls, by a ParathonContext* pointer. In DwarfPython, there is no such environment; to a first approximation, "the process context is the context". The local name environment is discovered by examining the stack, looking up the DWARF information for the current frame, and discovering the bindings recorded for frames of this type. Fig. 3 illustrates this contrast. Another key difference is our notion of data. In Parathon, we had a class ParathonValue representing all objects in the program, comprising 9 fields and 25 methods, and ParathonValue* pointers were ubiquitous. When modifying Parathon towards DwarfPython, one of our first changes replaced this with typedef void ParathonValue;—instead of defining our own notion of object, now an "object" is simply the referent of any pointer, and we rely on run-time availability of debugging information to support interaction with these objects. A key property of the Dwarf model is its inherent flexibility, arising from the need to accommodate diverse compilers and peculiar architectures. This allows it to accommodate quirky structures, such as noncontiguous objects and functions with multiple start addresses, which turn out to prove useful. Most importantly, however, Dwarf is understood by debuggers and other tools, so by maintaining a dynamic metamodel of our program as it executes, these tools are able to understand our program's state with only minor modifications. 2.3 Unifying object models (and metamodels) A key property of our design is that it unifies the "native" object model with that adopted by a VM (DwarfPython in this case). It does so using several techniques, and these also contribute towards the debuggability of DwarfPython using native tools. Native entry points All functions defined in Python have one or more native entry points generated for them. This makes them indistinguishable from native functions in a backtrace (assuming that symbols can be located—we discuss this in §3.2). In fact, all calls made by our interpreter, regardless of target, are implemented the same way: using libffi to call a native entry point. Heap instrumentation We instrument the C library's allocator to record the allocation site of each heap block. Using heuristics, we map this to the Dwarf type allocated by a particular site. This is sufficient to recover a precise Dwarf description of dynamically allocated objects, without relying on imprecise static type information. For objects allocated by Python, type information (not the allocation site) is stored directly in the heap metadata, but treatment is otherwise similar. Tree-structured object storage Python has an atomic notion of objects, where substructure is pushed out into the heap using references to other objects. By contrast, the native world, exemplified by C and C++, adopts a more general model where objects are tree-structured: they may be contained recursively within another object. We unify these models by considering a tree-structured object to contain implicit references to its subobjects. In languages with a Python-like flat object model, these fields have the semantics (but not the representation) of read-only pointers to the contained objects. This means our Python implementation must hide the distinction between these "implicit pointers" and the usual kind. Fig. 4 illustrates the two views. The only significant exception is the list of top-level imported namespaces. Another implementation of non-contiguous objects is virtual inheritance. We describe, unless stated otherwise. (Henceforth in this paper we do not claim a working implementation of systems we describe, unless stated otherwise.) Dynamic DWARF information Just as dynamic and reflective languages keep a mutable model of their own objects’ structures, so DwarfPython keeps a mutable database of debugging information. To accommodate dynamic code definition, we require a protocol much like that for notifying debuggers of code generated by a JIT compiler, notifying the debugger of accommodate dynamic updates to the available metadata. We have developed a cleaner approach to this than current protocols, and describe it in §3.2. To allow per-object layout changes, such as field additions and removals, data types are treated in a copy-on-write fashion: modifications to an object’s schema fork its descriptive information. This allows sharing in the common case, but allows unique objects to be treated uniformly. Non-contiguous objects To support field addition even on native objects, we must support tied storage. This is separately allocated heap storage whose lifetime is linked with that of a pre-existing object. Tying to manually-managed heap objects is easily implemented by interposing on free(). For GC’d heap objects, some cooperation with the collector may be required to prevent early reclamation of parts of an object (since there is no reference from the tied-to object to later-added storage). We can tie storage to stack allocations by redirecting their on-stack return address to a special handler. Since DWARF allows object locations to be non-contiguous, the resulting object layouts remain describable. DWARF extensions DWARF is not always expressive enough for our needs. One example is source code locations: DWARF encodes a mapping from program counters to source code coordinates, but this is insufficient since any location in the interpreter might map to any Python source file. A small extension to DWARF solves this by effectively pushing additional arguments (in our case the current AST node pointer) into the line-number lookup key. Another extension is required to capture output parameters written through stack pointers. In general, this kind of DWARF extension (which we envisage exploiting through programmer-supplied annotations) invariably helps debugging use-cases too. For example, an extended line-number lookup assists with source-level debugging across code generators (e.g. generalising yacc’s use of #line directives), while capturing output parameters enables more meaningful “value returned” reports when stepping through a function exit. 3. Generalising the approach DwarfPython is an ongoing effort, but seems promising enough that we may wonder whether it transfers to other settings. We consider a Java-like setting. Clearly, the same benefits of a low FFI coding overhead and native debuggability could be useful here. This raises several questions which we consider in this section. - What are the principles underlying the approach? - What generic shared infrastructure is required? - How can we deal with the constrained object models offered by Java-like languages, e.g. the requirement that each object implements a monitor and a suite of virtual calls? Can we share the resulting objects across VM–VM boundaries? What happens to statically-enforced invariants on such objects? - What are the implications for garbage collection? Can we still obviate the need for FFI code in the presence of higher-performance, less conservative garbage collection? - What are the implications for traditional (dynamic) optimisations done by VMs? Can we optimise code across VM–VM and VM–native boundaries? 3.1 Principles In essence, the whole design of DwarfPython rests on a few simple invariants. Invariant 1. There is a shared concept of functions. This is embodied in the fact that all functions have at least one native entry point. Functions are named, belong to a loaded module, and may have multiple entry points corresponding to alternative calling conventions (such as C versus Pascal versusfastcall). There is no separate concept of “foreign” functions. (Confusingly, “foreign” and “native” are often used synonymously. We will use “native” to mean code compiled ```c struct ellipse { x, y; ctr; } ``` ahead-of-time to the host architecture, and “foreign” as a relative term: to a given VM, both native code and other VMs’ code are foreign.) Multiple entry points may arise not only from alternative calling conventions, but alternative signatures (such as pass-by-reference or pass-by-value of a given argument) and contracts (such as “arg0 is not null” or “arg1 points to at least a Widget”). Multiple signatures and contracts accommodate differing expectations of diverse callers. Dynamic code naturally accepts arguments by reference, using this run-time indirection to dynamically discover the concrete objects pointed to, and assuming minimal precondition (instead raising exceptions dynamically when errors occur). Static-typed and/or optimised callers, by contrast, may wish to pass arguments immediately on the stack (for speed) and to call through a faster path which elides dynamic checks on the strength of static reasoning (such as Java-style bytecode verification enforcing type bounds on particular arguments). Our approach relies on dynamically generating distinct entry points to suit such diverse callers. Invariant 2. There is a shared descriptive metamodel spanning native code and all VMs. This is embodied in our pervasive use of DWARF, and is necessary for tool support to span VMs and native code. It is also an enabler of the final invariant. Invariant 3. An implementation of a particular language on a particular VM will define mappings between its data types and their representations in the common DWARF-based metamodel. This is an obligation on language implementations, in order to preserve the usefulness of a shared metamodel. In the Python case, the mapping is straightforward, since essentially any native object may be interpreted as a Python object (modulo the nontrivial treatment of tree-structured objects). We must consider how to apply our approach to more constrained scenarios, e.g. in Java where java.lang.Object brings certain requirements. 3.2 Shared infrastructure Each of our invariants is maintained by some piece of run-time infrastructure. Encouragingly, each piece generalises from some familiar infrastructure. Dynamic loader The first invariant entails a run-time service for tracking what code is loaded. This already exists; it is the dynamic loader provided (essentially) by the operating system, such as libdl on Unix platforms. We extend this in the same spirit as other extensions, such as dlvsym() (which adds symbol versioning on GNU and Solaris systems). Our dcreate(), ddestroy() and dlbind() calls allow guest VMs to dynamically manage named “objects” containing entry points. We also define a four-argument dlresolve() analogous to dlvsym() but providing also for a token describing calling convention and signature requirements, and for multiple namespaces. This extended dynamic loader obsoletes the ad-hoc protocols for registering dynamically generated code as described in §2.4, since debuggers already track dynamic changes to the link map on dlopen() and dlcose() events; our extensions generalise this support in minimally invasive fashion. We have a prototype of libd1 for GNU/Linux which can create new objects with a fixed-size text segment and dynamically populate them (using Linux-specific libdl options). This is sufficient for backtraces to show symbols for dynamic code. (A full implementation would lift the fixed-size constraint, likely requiring a modified ld.so.) Metadata interface We have described DwarfPython’s use of heap instrumentation and run-time debugging information to understand the running program (§2.4). Our core interface for this is implemented by a library libpmirror, which we had already created for an earlier project. As its name suggests, this library conforms (mostly) to the design principles of mirrors [4], but reflects a whole process rather than a single VM. It is separately encapsulated from the process it describes; like DWARF debugging information generally, is stratified in that it may be omitted from processes not requiring it; and inherits the DWARF metamodel’s fairly direct structural correspondence with the code it models. (This means libpmirror is a cross-language reflection facility, although predictably, it only unifies multiple languages to the extent that DWARF does, which is limited—see the Appendix.) Memory infrastructure For tracking heap metadata, we have implemented a fast associative data structure called a memtable, which resembles a hash table but uses a very large linear region of lazy-committed virtual address space, rather than an array indexed by low-order hash bits, as its primary look-up. This exploits underlying virtual memory hardware’s implementation of sparse, clustered address-keyed mappings; it is both more space-efficient and faster than a hash table in our experience. Entries are chained by threading a list through heap blocks (but could be kept less invasively in a separate shadow heap, or more efficiently in reclaimed malloc header space). Chains are short since each lookup entry covers a small (1KB) region of address space. Memtables are also used for tracking tied storage regions; a small library libmemtie provides a runtime interface for this, and adds the necessary instrumentation to the host C library’s free() call (but currently no collector cooperation, cf. §2.4). Language implementations The third invariant is handled by the language implementations themselves. The ap- Language implementations are also concerned with selecting which function to call, i.e. with dispatch. Dispatch occurs through data structures; we consider these structures logically part of an object layout. Moreover, their contents may logically be defined by queries over the DWARF metamodel. For example, “the vtable for class $C$ contains all functions declared lexically within $C$, left-merged with like-signature methods in inherited classes, transitively, excluding methods with the final attribute”. Although this elides some details (e.g. allocation of vtable slots), in general such queries can embody the overriding rules of a particular language, while subtly separating them from the data structure’s core definition. Imagine that the debugging information for our ellipse data type lexically includes some nonvirtual C++ method declarations. Our Java query would populate a vtable with these methods, whereas in C++ these calls would be early-bound. (This seems reasonable in preserving the dynamism trade-offs of different languages, but arguably weakens encapsulation by risking misuse of the original ellipse implementation. We would welcome discussion of this issue in the workshop.) We discussed the illusion of internal references within tree-structured objects in §2.3. In Python this entailed runtime overhead to distinguish an implicit pointer from a stored field. In languages with nominal subtyping it incurs no such overhead because the distinction is apparent statically in the defining type’s layout. 3.4 FFI coding and garbage collection As in DwarfPython, our design pushes the load of foreign function interfacing away from hand-coding done by the end programmer, and towards code generation done by the VM. We believe this to be appropriate; whereas APIs such as JNI are invariably convoluted by the desire to accommodate all conceivable implementations of the VM, VM implementors are uniquely aware of their own implementations, so are best placed to bear this effort. We have considered already the construction and accessing of VM-specific data representations. The other major source of FFI code is interaction between garbage collection and foreign code. In JNI [10], several calls exist to cooperate with moving collectors, namely calls to “get” and “release” array contents and manage long-lived references (GlobalRef) to objects. Several techniques allow relieving the programmer of this burden. In the simplest, for deployments (such as DwarfPython) where a moving collector is not used, these operations are simply redundant. In a semi-conservative approach, we may sweep a widened set of roots (e.g. including the malloc-managed heap) and only move objects having no ambiguous references (at some cost in fragmentation). Alternatively we may dynamically trap the escape of these pointers into imprecise roots, by memory-protecting these regions before calling out to native code. To optimise this, we may accept annotations (perhaps derived by analysis) that a given function saves no pointers, then omit memory protection on --- 9 Since earlier parts of the structure reserve no space for forward pointers, “forward” navigation between non-contiguous parts of an object can be supported by associative look-up through a memtable, the same structure used for heap metadata. such calls. Without experimental results we cannot propose a definitive technique; we are arguing that some combination of these techniques is likely to allow VMs to shoulder the burden at reasonable cost. (If this seems unpalatable, we remind the reader that this is, after all, the spirit of garbage collection: using dynamic analyses to take the place of burdensome programmer effort.) This meshes well with generational approaches. For example, we might have a conservatively- or semiconservatively-collected heap shared with C and C++ code, but then use a single precise compacting collector for objects that have not been shared, so can still be relocated. Since foreign code is typically “distant” code, we hypothesise that objects that need to be moved into the conservative heap are probably long-lived; short-lived objects may stay in heaps that are collected precisely. 3.5 Optimisation Most intraprocedural optimisations are unaffected by our approach because they are hidden by the implementation of a particular language. Meanwhile, most interprocedural optimisations are also unaffected (or trivially uneffected) because JITs only optimise across code which they themselves generated. We consider two “interesting” cases as (unimplemented) thought experiments. Firstly, there are optimisations which are textually intraprocedural, but whose correctness relies on program-wide knowledge. Secondly, there are optimisations which we would like to support but currently do not: those that cross VM–VM and VM–native boundaries. Program-wide knowledge Consider devirtualization by class hierarchy analysis. This relies on whole-program knowledge (namely the value set of a vtable entry). Since these optimisations are performed on a per-call-site basis, using a particular dispatch infrastructure, they appear to be local to a VM. However, recalling our approach (§3.3) to generating dispatch structures from shared DWARF information, the queries which were used to generate these structures are open to invalidation by code loading. This forces our shared dynamic loading infrastructure (§3.2) to get involved: queries must be persistent, and when their results are affected by code loading events, this should trigger reoptimisation. Whole-program dynamic optimisation In last year’s keynote, Cliff Click observed that profile-guided optimization in ahead-of-time compilers is trapped in a cycle of underuse and immaturity. In stark contrast, many JVMs contain a wealth of complex dynamic compilation techniques which are continuously exercised and improved. The infrastructure we have outlined is an ideal platform for breaking out this complexity into a shared service of profile-guided dynamic optimization across whole programs. Our dynamic loader tracks loaded code; a whole-program profiler built on this can track hot paths across multiple VMs and native code. For example, consider optimising some native code by inlining some VM-generated code which itself rests on some change-prone class hierarchy analysis. It would not normally be safe to perform this inlining because if the analysis is invalidated, the native optimiser will not be notified. Given persistent queries, we can solve this by propagation of dependencies: the native-code optimiser registers (with the dynamic loader) a dependency on the VM-generated code. When the analysis underlying the latter is invalidated, the native optimiser is also notified, and can replace the now-unsafe inlined code. At the heart of this approach is the separation of whole-program facts (query output, and data gathered by analysis and profiling), which are concerns managed by the shared infrastructure, from language and code generation, which remain concerns of individual VMs. To dynamically optimise native code we may build on the link-time optimisation and low-level JIT compilation pioneered by the LLVM project [8]. Finally, by discouraging premature optimisation of native code, this may help with the currently poor deoptimisation support in native toolchains—familiar to gdb users as frustrating “value optimized out” messages. 4. Related work Many tools exist for making FFI code easier to write, but few provide direct sharing of data, and none addresses debugging results. Swig [1] is a popular tool for generating wrappers from C APIs; Boost.Python [10] and SIP [11] are similar Python-specific tools focussing more on C++. Java Native Access [12] offers lower overheads but still requires programmers to transcribe native interfaces into Java (rather than generating them from a unified metamodel). The GNU implementation of Java [3] integrates Java into an existing compiler infrastructure, and allows native libraries to be accessed using a much more usable interface (CNI) than Java’s usual JNI. Roughly, our approach generalises this towards multiple VMs and dynamic languages. One implementation of Scheme [12] is an interesting relative of DwarfPython. It provides a similar degree of wrapper-free integration, but no specific contribution to tool support, is C-specific, and does not support dynamism such as object schema update. Cross-language debugging tools overlap somewhat with our goals. Blink [9] uses a controlling master process to provide a consistent interface onto multiple runtime-specific debuggers, at a cost of per-environment integration effort (since each new environment brings another debugger which must be integrated by hand). In essence, Blink embraces diversity of environments, whereas we attempt to synthesise a single underlying environment. 10 http://www.boost.org/doc/libs/1_35_0/libs/python 11 http://riverbankcomputing.co.uk/software/sip/ 12 http://github.com/twall/jna There is a clear demand for cross-language and cross-VM tool support, as witnessed by extant patches to Valgrind\(^{13}\) and gdb\(^{14}\), machine-level Python heap profiling\(^{15}\), cross-language Java debugging information\(^{16}\), per-VM “providers” for the DTrace tool [5] and many others. These approaches are “point fixes” for some pairing of tool and VM, rather than direct solutions. There is also considerable demand for sharing objects across VMs; the most relevant existing system is CoLoRS [13]. This extends stock VMs with shared objects, but does not support sharing with native code, nor unifying run-time tool support. VMKit [7] has a similar approach of factoring managed runtimes, but instead of providing for sharing across multiple colocated VMs, considers constructing and experimenting with individual specialised VMs. A philosophically similar approach is that of subject-oriented composition [11], which considers reconciling multiple overlapping views of the same application domain model. Our approach is essentially its analogue at machine-rather than application-level. 5. Concluding remarks We have argued that virtual machines can and should be made far less obtrusive for end programmers to use. We have focused on FFI and debugging issues; there remain other ways in which VMs are obtrusive, especially their configuration (e.g. code search paths, resource limits, security models), which are worth rethinking. In any case, our immediate plans are: to produce a complete, optimised implementation of DwarfPython; then to apply our techniques within VMKit’s j3 JVM [7], including whole-program dynamic optimizations. We are also interested in embracing functional languages (especially with lazy evaluation, which remain difficult to debug), moving a wide range of VMs closer to the invisible ideal. Acknowledgments The authors acknowledge Manuel J. Simoni for an idea which seeded the work in this paper, and helpful comments from Max Bolingbroke, Nishanth Sastry and Jukka Lehtosalo. Stephen Kell was supported in part by the Oxford Martin School Institute for the Future of Computing. References \(^{13}\) https://spideroak.com/code \(^{14}\) http://llvm.org/docs/DebuggingJITedCode.html \(^{15}\) http://us.pycon.org/2011/schedule/presentations/25/ \(^{16}\) http://jcp.org/en/jsr/detail?id=45 A. A brief introduction to DWARF Debugging information describes compiled code in sufficient detail to recover a source-level abstraction of a running program. This includes the ability to resolve source-level names, decode values, traverse data structures, walk the stack, and map instruction addresses back to source locations. Since it must support many machine architectures and compiler implementations, it is a rich and flexible medium. In this paper we focus on the DWARF format [6], which is common on contemporary Unix platforms. Overall structure DWARF information is presented as a heterogeneous tree whose structure generally reflects the nesting relation in the source code. The top level records compilation units; under these are file-level definitions (e.g. classes and functions); similarly fields, formal parameters, variables, nested data types and nested functions all fall in the expected positions. Tree nodes are decorated with attributes which carry the descriptive payload: name, size and layout in memory, position in memory (relative to some implied base address such as a frame pointer or start-of-object), source code coordinates of their declaration, types of fields or variables, and so on. Although presented as a tree, the structure encodes cross-references (most commonly to data-type definitions, from definitions which instantiate them). It is therefore a graph and is frequently cyclic (e.g. for a recursive data type). Fig. 6 shows a skeleton C++ program together with a schematic overview of its DWARF description. Language features DWARF is mostly independent of language, and DWARF-emitting compilers exist for many languages including C, C++, Fortran, Objective-C, Java and others. Compilation units are tagged with their originating language. Most obvious deduplications among languages have been effected (e.g. structure_type includes C structs, Pascal Records and so on), but there is no deeper unification (e.g. interface_type is currently particular to Java-generated code). Location descriptions DWARF is particularly flexible in mapping objects (including arguments, local variables, fields within objects, etc.) to memory locations. This is done with “location expressions” defined abstractly in terms of a stack machine. The expressions can source values from the running program (most typically register contents) and do arbitrary computations on them. Our implementation relies heavily on these expressions, notably to support objects split across multiple storage locations. Figure 6. Simple C++ code and schematic DWARF description
{"Source-Url": "http://www.cl.cam.ac.uk/~srk31/research/papers/kell11virtual-author-preprint.pdf", "len_cl100k_base": 7248, "olmocr-version": "0.1.50", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 31063, "total-output-tokens": 8397, "length": "2e12", "weborganizer": {"__label__adult": 0.00032973289489746094, "__label__art_design": 0.0002465248107910156, "__label__crime_law": 0.00022494792938232425, "__label__education_jobs": 0.0005321502685546875, "__label__entertainment": 4.976987838745117e-05, "__label__fashion_beauty": 0.00012922286987304688, "__label__finance_business": 0.00015103816986083984, "__label__food_dining": 0.00031685829162597656, "__label__games": 0.0003380775451660156, "__label__hardware": 0.0008363723754882812, "__label__health": 0.0004048347473144531, "__label__history": 0.00020885467529296875, "__label__home_hobbies": 7.814168930053711e-05, "__label__industrial": 0.00032711029052734375, "__label__literature": 0.00022602081298828125, "__label__politics": 0.00024819374084472656, "__label__religion": 0.0004949569702148438, "__label__science_tech": 0.00948333740234375, "__label__social_life": 7.873773574829102e-05, "__label__software": 0.0034961700439453125, "__label__software_dev": 0.98095703125, "__label__sports_fitness": 0.000270843505859375, "__label__transportation": 0.000530242919921875, "__label__travel": 0.00020134449005126953}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 38972, 0.01951]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 38972, 0.49919]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 38972, 0.90605]], "google_gemma-3-12b-it_contains_pii": [[0, 4189, false], [4189, 8212, null], [8212, 12933, null], [12933, 17311, null], [17311, 22783, null], [22783, 26108, null], [26108, 31814, null], [31814, 36378, null], [36378, 38972, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4189, true], [4189, 8212, null], [8212, 12933, null], [12933, 17311, null], [17311, 22783, null], [22783, 26108, null], [26108, 31814, null], [31814, 36378, null], [36378, 38972, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 38972, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 38972, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 38972, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 38972, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 38972, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 38972, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 38972, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 38972, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 38972, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 38972, null]], "pdf_page_numbers": [[0, 4189, 1], [4189, 8212, 2], [8212, 12933, 3], [12933, 17311, 4], [17311, 22783, 5], [22783, 26108, 6], [26108, 31814, 7], [31814, 36378, 8], [36378, 38972, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 38972, 0.0]]}
olmocr_science_pdfs
2024-11-28
2024-11-28
deffa692e676698e4cc42929ea680750784dd8d3
Using Reference Attribute Grammar-Controlled Rewriting for Energy Auto-Tuning Bürger, Christoff; Mey, Johannes; Schöne, René; Karol, Sven Published in: CEUR Workshop Proceedings (CEUR-WS.org) Published: 2015-01-01 Citation for published version (APA): Using Reference Attribute Grammar-Controlled Rewriting for Energy Auto-Tuning Christoff Bürger¹, Johannes Mey², René Schöne², Sven Karol³, and Daniel Langner² ¹ Department of Computer Science, Faculty of Engineering, Lund University, Sweden christoff.burger@cs.lth.se ² Professur Softwaretechnologie, Institut für Software- und Multimediatechnik, Fakultät Informatik, Technische Universität Dresden, Germany (johannes.mey@|rene.schoene@|daniel.langner@mailbox.)tu-dresden.de ³ Chair for Compiler Construction, Center for Advancing Electronics Dresden, Technische Universität Dresden, Germany sven.karol@tu-dresden.de Abstract. Cyber-physical systems react on events reported by sensors and interact with objects of the real world according to their current state and their view of the world. This view is naturally represented by a model which is continuously analysed and updated at runtime. Model analyses should be ideally concise and efficient, requiring well-founded, comprehensible implementations with efficient reasoning mechanisms. In this paper, we apply reference attribute grammar controlled rewriting to concisely implement the runtime model of an auto-tuning case study for energy optimization. Attribute functions are used to interactively perform analyses. In case of an update, our system incrementally—and, thus, efficiently—recomputes depending analyses. Since reference attribute grammar controlled rewriting builds the required dependency graphs automatically, incremental analysis comes for free. Keywords: energy auto-tuning, cyber-physical system, runtime model, attribute grammar, graph rewriting, incremental analyses 1 Introduction Developing software for cyber-physical systems is a major challenge in software and systems engineering [2,4,11]. A cyber-physical system steadily monitors its environment, interacts with real-world entities and other systems, and reconfigures itself according to its current view of the world. To implement these tasks, executable world models enriched with runtime analyses and update events (e.g., from sensors) are a common approach [3,19]. To ensure reliability and integrity of cyber-physical systems, such models need to be well-founded, interactive and comprehensible. In particular, model analyses (e.g., to react on events accordingly) should not only be easy to implement but also efficient—especially in the presence of continuous model updates at runtime [1]. Hence, an important concern is to avoid unnecessary or redundant reevaluations of the analyses. Essentially, if not affected by updates, previously computed results should be reused in such a way that model analyses become incremental. A second challenge for cyber-physical systems is the energy scarcity, demanding for energy-efficient systems [2]. In this paper, we demonstrate how a novel combination of reference attribute grammars [10] and rewriting [14,17]—both well-known compiler-compiler tech- niques [17,9,13]—can improve on the challenge of incremental model analysis. Reference attribute grammar controlled rewriting (RAG-controlled rewriting) [6] leverages dynamic dependency tracking to make attribute evaluation (i.e., model analyses) incremental in the presence of rewrite-based model updates. We present an energy auto-tuning case study whose runtime model is incrementally updated using RAG-controlled rewriting. Our example scenario is an interactively trig- gered energy-efficient indexing of text documents that runs on a changeable network of independently powered computers. The paper is structured as follows: first, the energy auto-tuning scenario of our case study is presented (Section 2), followed by a short introduction to RAG-controlled rewriting (Section 3); afterwards, the implementation of the actual runtime model based on RAG-controlled rewriting is presented (Section 4); an evaluation of the presented solution concludes the paper (Section 5). 2 Case Study: Energy-efficient Document Indexing Case Study Overview: Our case study to evaluate the applicability of RAG- controlled rewriting for runtime models is the energy-efficient indexing of text documents using a network of embedded computers. Indexing a text document in our context means to construct a hash-table that counts the frequency of each word in the document. A typical application of this indexer may be instant search or case-based reasoning in a network of robots [20]. Each indexing request has two parameters: a text document of a certain size to index and a hard deadline until which the result must be computed. Indexing requests are interactive (i.e., occur randomly); at any moment, only previous requests are known but nothing about future requests, including their frequency, deadlines and document sizes. Given an arbitrary stream of indexing requests and a network of independent computers available for indexing (called workers), the objective is to dispatch the processing of requests in such a way that the total energy consumed to process the stream is minimized. To save energy, single devices or complete network parts—including their switches, attached workers and subnetworks—can be deactivated. Furthermore, indexing can be prolonged as long as the corresponding deadlines are met. All devices are exclusively available for indexing and not occupied with other tasks. The start-up and shut-down times of devices are not constant however; sometimes toggling them may even fail and require retries. Furthermore, devices can be removed interactively or new ones added, requiring reschedules to still meet deadlines and optimise energy consumption. \footnote{This is a realistic problem that happens with some of our devices (CubieBoards).} Fig. 1: Cyber-physical system of the indexing case study. **Setup and Solution Overview:** Figure 1 summarises the hard- and software components of our solution. The hardware (real-world circle) comprises two switches (*Conrad FX-08Mini*: 8 RJ45 ports à 100 MBit/s), five worker devices (*CubieBoard2: Allwinner A20* (*ARM Cortex-A7 Dual Core*), 1GB DDR3), a remote-controllable power supply (*Cambrionix USB*: 8 USB ports à max. 5.2V, 2.1A) and a master device (*CubieTruck: Allwinner A20*, 2GB DDR3). Each port of the power supply powers a single switch or worker (blue power links), and is controlled by the master for power measurement and toggling (purple power control link). The two switches are connected in sequence (green network links): the first is directly connected to the master and three workers; the second to two. The software includes a controller that dispatches events and interacts with devices (control loop), a runtime model including analyses to schedule indexing requests and deduce reconfigurations, a web interface to visualise power consumption and schedules, a concurrent implementation of an actual indexing algorithm, and communication links between master and both, workers and power supply. The controller, runtime model and web interface run on the master (Fig. 1, left side). Thus, only the master has a view on the real world and can interact with it. It is responsible for runtime model updates and reconfigurations, i.e. the propagation of such an update into the real world. All other devices have no knowledge about the world’s current state. Moreover, the actual indexing requests issued by external entities are exclusive events to the master. Because these requests occur concurrently, they are collected in a queue by the controller for dispatching. The web interface observes this queue and visualises its history. Three kinds of instruction events and respective acknowledgements for device communication exist: to start indexing of a text document on a certain worker (master ↔ worker), to start-up/shut-down devices (master ↔ power supply and/or workers) and power measurements (master ↔ power supply). Devices are either idle and ready for instructions, or busy, in which case they cannot process new instructions (indexing cannot be suspended and each worker processes at most one request at a time, thus resulting in a virtual request queue stored in the runtime model). If ready, received instructions are immediately performed; their start and result is acknowledged to the master. The controller performs two main tasks in its control loop. First, it dispatches the event queue and updates the runtime model according to acknowledgement events; in case of indexing requests it delegates to the runtime model to incorporate a schedule (such updates are provided by the runtime model in the form of rewrite rules, cf. Section 4). Second, it periodically checks for devices that can be shut down, indexing tasks that must be started, and new or failed devices. These periodic tasks use runtime model analyses for reasoning. Our runtime model combines a scheduling and energy policy. Consolidating workload, the scheduling satisfies deadlines using as less resources as possible. The energy analysis deduces unused, and in the future most likely not required, devices—it saves energy by shutting them down taking into account reactivity for emerging requests (energy-awareness). Both analyses are well-balanced; it is their combination that saves energy while still processing as many indexing request as possible (cf. Section 5). 3 RAG-Controlled Rewriting Background A well-known formalism for the specification of semantic analyses are attribute grammars [15]. Their main advantage is to relieve users from manual traversals of analysed models and scheduling of analyses. Given a concrete attribute grammar, an highly optimised evaluator can be generated based on a static analysis of the grammar’s attribute dependencies [16]; essentially, incremental model analysis is achieved. However, attribute grammars are specified w.r.t. tree structure, for which reason their graph analysis capabilities are inconvenient. Reference attribute grammars (RAGs) improve on this by extending attribute grammars with so called reference attributes, attributes evaluating to nodes of the tree being analysed [10], enabling the deduction of abstract syntax graphs (ASGs) from abstract syntax trees (ASTs) [7] and reasoning about ASGs [12]. The viability of this technique to specify semantics for metamodels, like EMF Ecore [8], has been shown [7]. The main disadvantage of RAGs is, that reference attributes hinder static dependency analyses and therefore incremental evaluation. To still achieve incremental evaluation, recent research proposed the tracking of attribute dependencies at evaluation time, i.e., dynamically [6,18]. We even go one step further and comprehend AST changes in terms of graph rewriting [6], thus combining incremental RAG-based analyses and rewriting-based model transformations, either interactive, deduced or a combination thereof. RAG-controlled Rewriting for Models@runtime (1) A new request that has to be scheduled is inserted in the queue of requests of a running worker. (2) ASG of an example configuration. Nonterminals are rounded rectangles including their child terminals and some of their attributes, denoted with an \( \ast \). (3) The updated configuration after the insertion of the new request into the model. Fig. 2: Upon arrival of a new request (1), the attribute schedule is evaluated (2) and the request is inserted into the queue of a worker (3). 4 A Runtime Model based on RAGs and Rewriting In the following, we present a RAG-controlled rewriting-based runtime model for the case study of Section 2. Our implementation uses RACR \([5,6]\), a reference implementation of RAG-controlled rewriting in Scheme\(^5\). Using RAGs, we represent the runtime model (cf. Fig. 1) as an abstract syntax graph (ASG) with an underlying abstract syntax tree (AST) as a distinct spanning tree. Using RACR, we define the corresponding AST grammar as follows: \[ \begin{align*} 1 & (\text{ast}\text{-\text{rule}} \ 'Root\text{->}scheduler\text{--}backupworkers\text{--}CompositeWorker) \\ 2 & (\text{ast}\text{-\text{rule}} \ 'AbstractWorker\text{->}id\text{--}state\text{--}timestamp) \\ 3 & (\text{ast}\text{-\text{rule}} \ 'CompositeWorker:AbstractWorker\text{->}AbstractWorker*) \\ 4 & (\text{ast}\text{-\text{rule}} \ 'Switch:CompositeWorker->) \\ 5 & (\text{ast}\text{-\text{rule}} \ 'Worker:AbstractWorker->devicetype->Request*<Queue) \\ 6 & (\text{ast}\text{-\text{rule}} \ 'Request->id->size->deadline->dispatchtime) \end{align*} \] Each line describes one nonterminal that corresponds to a possible node type in the AST. For example, Line 5 defines a Worker inheriting from AbstractWorker and therefore comprising an ID, a current state, the most recent alternation date, the type of worker and any number of Requests called Queue. A concrete ASG (i.e., an AST with evaluated attributes) is shown in Fig. 2b. Analyses are concisely specified using attributes. The main attribute schedule of the scheduling algorithm is depicted below while its evaluation is exemplified in --- \(^5\) The implementation of our solution can be found at https://github.com/2bt/haec. the upper part of Fig. 2b. The attribute is defined for Root—the start symbol in the AST grammar, which defines virtual root components in our runtime model, and does a dynamic dispatch to determine which scheduler to use. It reads the terminal scheduler using ast-child and invokes the another attribute via att-value. We employ two basic scheduling strategies. The first one always chooses the worker with the shortest queue (shortest-queue scheduler) whereas the second tries to fill the request queues of running workers as much as possible in order to consolidate the load (load-consolidating scheduler). Another analysis is the energy-aware adaptation strategy, which periodically computes the ideal number of online workers and switches off everything else, trying to keep at most one worker with an empty queue running as backup for further incoming tasks. Figure 2 shows an example of a rewrite that creates a new Request and inserts it in the request queue of a selected worker. In RACR, such model transformations can be specified as below. After each rewrite application, the cache of every attribute depending on values of the rewritten part of the ASG is automatically flushed, flagging those attributes for reevaluation. The actual computation of the new attribute value is lazy, which prevents unnecessary work and thus enables fast, incremental analyses of the runtime model. An additional use case for rewrites is the failure of a physical worker. In this case, the current and all pending requests are removed from the worker in the ASG and simply scheduled again—now without considering the failed worker. As described in Section 2, we use a socket-based communication protocol between the devices. Figure 3 sketches the processing of a request. Upon arrival at the controller, a request event is created and added to the runtime model, where a scheduler is used to determine a processing worker. A command to process the request is first sent to the controller, which relays it to the appropriate worker. Once finished, the controller is notified and invokes event-work-complete to let the runtime model update accordingly. 5 Evaluation To evaluate the presented approach, the applied measurement techniques are introduced, followed by a discussion of the acquired data. These very use-case specific results are followed by a more general investigation of the applicability of RAG-controlled rewriting for runtime models. **RAG-controlled Rewriting for Models@runtime** ![Diagram of models and components] **Fig. 3:** After arrival of a request, the controller dispatches events. **Performance and Energy Savings** As mentioned in Section 2, the controller constantly monitors the state of the workers and their energy consumption, and protocols them as well as the events it processes. For the evaluation, periods of running the same workload in different system configurations have been selected to compare the energy-consumption properties of them. Figure 4 shows three different runs using both implemented scheduling and worker adaptation strategies. The bar charts associated with the three runs show how the same set of work requests (displayed as grey triangles) are scheduled. While the shortest-queue schedulers in Fig. 4b and 4c schedule events to run as soon as possible, the load-consolidating scheduler tries to fill the request queue as much as possible, resulting in less workers being used. Additionally, runs in Fig. 4c and 4d use the energy-aware adaptation strategy (cf. Section 4) with three workers kept running to handle the assumed base load. Each device has a lane in the diagram, the brightness of its colour determines its state: very bright means the worker is switched off, fairly bright means it is currently booting or shutting down, and a dark colour represents an active worker connected to the master. Currently processed work requests are shown as grey boxes on the respective worker. The power consumption of all three runs is shown in Fig. 4a. A dashed line depicts the average power consumption which is proportional to the required energy. As summarised in Table 1, with the best heuristics used in run 4d, only 82.5% of the simple scheduling heuristics are used, amounting to savings of 17.5%. An important effect of the load-consolidating scheduler is that less workers are needed while the deadlines are kept. **Benefits of a RAG-based Runtime Model** Besides the energy savings described in the last section, a RAG-controlled rewriting-based approach offers qualitative benefits for developers. Even though context-free grammars describe tree structures, RAGs can express arbitrary graphs through their reference attributes. No name resolution tables have to be defined explicitly and navigation in a RAG-based model can be performed easily. Furthermore, the declarative nature of the grammar and its attribute definitions makes modifications of both fairly simple. Also, the runtime models described by a RAG can be modified easily with direct rewrite commands or with pattern-based techniques using different strategies [6]. While these properties of RAGs make them an option for the description of runtime models, the approach must also be easily usable. **RACR** provides not only a lightweight solution without any dependencies other than a running *Scheme* implementation, but also allows a compact and concise specification of runtime models. As shown in Table 2, our main programming effort went into the controller and worker programs while the model including all scheduling heuristics contains only about 500 lines of code. Our use case shows RAG-controlled rewriting to be an adequate concept to manage a small runtime configuration. But while the size of the demo is limited due to technical constraints, for the concept to be practically useful, large systems must be treated consistently and efficiently. This is possible through *incremental evaluation*. Consistency of attribute values (and therefore scheduling heuristic) is given automatically, because whenever an attribute value is required, our approach makes sure that the value is up-to-date and consistent with the model. In general, consistency comes at a price: it threatens either the efficiency of a system (each attribute is recalculated on every call) or the simplicity (problem-specific bookkeeping is needed to determine which attributes to recompute in the event of model changes). These problems do not exist in RAG-controlled rewriting. While attribute values are cached, necessary re-computations due to model changes are triggered automatically with an attribute-dependency analysis. This enables the application of the presented approach in larger systems and also the future use of more complex and computationally expensive scheduling and adaptation algorithms. Thus, reference attribute grammars prove to be an adequate modelling formalism for cyber-physical systems. ### 6 Conclusion We addressed two cyber-physical system challenges: (1) the development of well-founded, interactive and comprehensible runtime models with efficient, easily implementable analyses and (2) energy auto-tuning for energy-efficient computations. The latter requires the first; to auto tune regarding energy-efficiency requires a runtime model that can be used to deduce beneficial reconfigurations. We proposed RAG-controlled rewriting as a solution to implement such a model and presented an indexing case study, whose challenges are representative for cyber-physical systems and energy auto-tuning. The evaluation of our solution showed energy savings of up to 17.5%. It is lightweight, extensible, declarative and efficient (comprehensible specifications yielding incremental analyses). In the future, we intend to apply our approach to larger use cases and more complex cyber-physical systems to show its scalability. Acknowledgments: This work is supported by the German Research Foundation (DFG) in the SFB 912 “Highly Adaptive Energy-Efficient Computing”. References
{"Source-Url": "http://lup.lub.lu.se/search/ws/files/3857069/8057664.pdf", "len_cl100k_base": 4363, "olmocr-version": "0.1.53", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 33194, "total-output-tokens": 5710, "length": "2e12", "weborganizer": {"__label__adult": 0.0003974437713623047, "__label__art_design": 0.000392913818359375, "__label__crime_law": 0.00032806396484375, "__label__education_jobs": 0.000652313232421875, "__label__entertainment": 9.351968765258788e-05, "__label__fashion_beauty": 0.00019359588623046875, "__label__finance_business": 0.0003523826599121094, "__label__food_dining": 0.0003440380096435547, "__label__games": 0.0005044937133789062, "__label__hardware": 0.0014123916625976562, "__label__health": 0.0007243156433105469, "__label__history": 0.0002918243408203125, "__label__home_hobbies": 0.00011718273162841796, "__label__industrial": 0.0006108283996582031, "__label__literature": 0.00037288665771484375, "__label__politics": 0.00031495094299316406, "__label__religion": 0.0005078315734863281, "__label__science_tech": 0.0906982421875, "__label__social_life": 0.0001074671745300293, "__label__software": 0.00897979736328125, "__label__software_dev": 0.89111328125, "__label__sports_fitness": 0.00031065940856933594, "__label__transportation": 0.0007390975952148438, "__label__travel": 0.0002219676971435547}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 24045, 0.01869]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 24045, 0.253]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 24045, 0.87161]], "google_gemma-3-12b-it_contains_pii": [[0, 510, false], [510, 510, null], [510, 2982, null], [2982, 6217, null], [6217, 8081, null], [8081, 11328, null], [11328, 13585, null], [13585, 16034, null], [16034, 18431, null], [18431, 18431, null], [18431, 20854, null], [20854, 24045, null]], "google_gemma-3-12b-it_is_public_document": [[0, 510, true], [510, 510, null], [510, 2982, null], [2982, 6217, null], [6217, 8081, null], [8081, 11328, null], [11328, 13585, null], [13585, 16034, null], [16034, 18431, null], [18431, 18431, null], [18431, 20854, null], [20854, 24045, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 24045, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 24045, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 24045, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 24045, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 24045, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 24045, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 24045, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 24045, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 24045, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 24045, null]], "pdf_page_numbers": [[0, 510, 1], [510, 510, 2], [510, 2982, 3], [2982, 6217, 4], [6217, 8081, 5], [8081, 11328, 6], [11328, 13585, 7], [13585, 16034, 8], [16034, 18431, 9], [18431, 18431, 10], [18431, 20854, 11], [20854, 24045, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 24045, 0.0]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
03d73543eca76da047a3587f0e7d53e0200490dc
Success factors of agile programming – example of HaMIS Karolina Piwowarczyk Cracow University of Economics Abstract: The article raises the issue of the information system implementation using agile programming in the public sector. This subject is one of the emerging trends today on the basis of management science. It turns out that it is new on account of the fragmentary knowledge in literature on this subject. It is difficult to find examples of the implementation of this method in the Polish public sector. This article aims at identifying the factors that are necessary for effective implementation of public projects with the use of Scrum. Additionally, it also focuses on identifying evidence tending to apply Agile methods. The article is based on literature on the subject as well as reports on the HaMIS implementation. The literature review showed that the effectiveness of the projects by Scrum is affected among others by time, coordinating a team and the resignation of excessive documentation. The analysis shows two main conclusions. Agile methods enabled to achieve better benefits and their effectiveness suggest creating more legal possibilities for complex IT projects in an environment with a high degree of uncertainty. Keywords: agile, Scrum, public sector, HaMIS JEL Codes: M15 1. Introduction Changes in the world today increase the expectations of taxpayers in relation to the public sector. Their growing public expectations, technological progress and the development of digitization have put pressure on increasing government effectiveness. More and more customers are looking for better services through the Internet. They are looking for faster and more effective methods of project implementation and procurement. Public administration is one of the largest (if not the largest) clients in each country in terms of the quantity and value of information projects. (Dałkowski, 2000, p. 1). The leading country (according to the United Nations Public Administration Network) is the United States, which spend an average of about 100 billion USD on projects. One of the potential directions for research is the ICT industry because of its interdisciplinary nature resulting from the desire for automation and digitization in particular areas of human activity, leading to continuous measurement of a wide spectrum of problems. (Konieczny, 2014, p. 369). The implementation of public projects using traditional methods has repeatedly focused on accurate documentation, forgetting about constant technical progress at the same time. Their many failures force them to look for improvements and new ways of implementing projects that will improve the effectiveness of government operations and meet the needs of the people. Due to some barriers, other ways of awarding public contracts are sought in order to gain more freedom in the surrounding reality. An example of how to ensure greater efficiency is agile methodology, commonly used in business. Same principles that work in business will work in government making them faster, more flexible, and more responsive (in short, more agile) in achieving better outcomes for their citizens (Agile government 2016). The unique nature and absence of a clear action plan prevent it from being used for public projects. The ability to use the agile methodology for realized public IT projects is controversial. Increasingly, large projects use it achieve big successes. Researchers are increasingly examining IT projects for the public sector. The purpose of this article is to identify the key factors that have contributed to the success of the HaMIS IT project. This action was considered important for the implementation of future projects. Identifying the problems encountered and key decisions will improve the implementation of other public sector projects across the world. This article is based on literature and reports from HaMIS project. 2. Agile methodology in IT Projects Information technology managers are looking for modern, alternative project management methods and guidance on how to achieve the greatest results in greater uncertainty. J. Highsmith states that (2004): if your goal is to deliver a product that meets a known and unchanging specification, then try a repeatable process. However, if your goal is to deliver a valuable product to a customer within some targeted boundaries, when change and deadlines are significant factors, then reliable Agile processes work better. We know when we should use agile methodology but what constitutes its basis? In 2001, a group of software developers published the Manifesto for Agile Software Development to define the values of the Agile movement (Bird, Bird, 2016). New methodology has become an alternative to the traditional waterfall approach. Agile is a time boxed, iterative approach to software delivery that builds software incrementally from the start of the project, instead of trying to deliver it all at once near the end. It works by breaking projects down into little bits of user functionality called user stories, prioritizing them, and then continuously delivering them in short two week cycles called iterations (www.agilenutshell.com). Agile method builds four universal rules, generalized demands being overvaluation of existing components of the project (agilemanifesto.org): - individuals and interactions over processes and tools, - working software over comprehensive documentation, - customer collaboration over contract negotiation, - responding to change over following a plan. The use of rules in a project is not an aim, but only a means to achieve it. Their wider analysis was contained in the book by K. Kaczor (2014, pp. 40-47) on the basis of which these 12 principles can be presented in six categories. The whole activity is directed towards the customer. His satisfaction is an important priority accompanying the project. The software provided systematically - every few weeks, gives the customer a sense of physical progress. His instructions, requests and corrections are taken into consideration which compound the final satisfaction. The key determinant of success is the project team. Agile Project Management focuses on selecting the right skills for project team members and molding them into productive teams (Highsmith, 2004, p. 8). It is known that the best architectures, requirements, and designs are the result of workers organizing by themselves. The creation of favorable conditions for work and the opportunity to develop have a significant impact on the quality of the supplied software. Self-organizing team has a sense of creating something important, as a result there is a 100% involvement into the implemented contract. Thanks to daily cooperation identifying the defective factors is simpler, and their exclusion is beneficial for increasing productivity. Daily meetings not only give a clear picture of the situation "done, in progress, to do", but also become a place for exchange of problems and obstacles encountered in the implementation of the project. You can only be better if you learn from mistakes. And then failing is something that prompts you to move ahead (Zhu, 2016). The experience of people working in a team has a vital role at the stage of initial discussions with a client and planning tasks. The real scope of the planned responsibilities becomes the key of success on the road to introduce the software running on time because we know that. In fact, in an agile project, technical excellence is measured by both capacity to deliver customer value today and create an adaptable product for tomorrow (Highsmith, 2004, p. 8). With the demands outlined above there emerges Team orientation to implementation of the project expected by the client. Cooperation of this type results in achieving the desired purpose and at the same time makes the method effective. QSM Associates research shows that projects agile method produced a 37% faster than other methodologies. projects (The Agile Impact Report, 2008). Moreover, only 9% of the projects were carried out in accordance with Agile fails, and waterfall methodologies are up to 30% (The Chaos Manifesto, 2013). 3. Scrum framework The word scrum is taken from rugby and indicates a method of team play that allows you to take possession of the ball and lead it further along the field, and for this you need coherence, unity of intent and a clear understanding of the goal (Sutherland, 2014). The scrum is not considered a type of method or process, but the determinant of a specific framework and guidelines that complement Agile Manifesto. According to the J. Sutherland (2014) Agile Manifest it declared the following values: people over processes; products that actually work over documenting what that product is supposed to do; collaborating with customers over negotiating with them; and responding to change over following a plan. Scrum is the framework built to put those values into practice. There is no methodology. Scrum is a framework for project management that emphasizes teamwork, accountability and iterative progress toward a well-defined goal. The framework begins with a simple premise: Start with what can be seen or known. After that, track the progress and tweak as necessary. The three pillars of Scrum are transparency, inspection and adaptation (searchsoftwarequality.techtarget.com). A key principle of Scrum is its recognition that during product development, the customers can change their minds about what they want and need, often called requirements volatility (Henry, Henry, 1993). In the everyday life of the project the design team is made up of 3 to 9 members. It includes individuals involved in the project i.e. programmers, testers, analysts. A very important person in the project is the Scrum Master, the person in charge of running the process, asks each team member three questions (Sutherland, 2014): 1. What did you do yesterday to help the team finish the Sprint? 2. What will you do today to help the team finish the Sprint? 3. What obstacles are getting in the team’s way? Clearly defined activities relate to each stage of the production, which has been illustrated in figure 1. Fig. 1. Scrum project life cycle Source: own elaboration. Beginning the phase of the process is the Product Backlog, which comprises an ordered list of requirements that a Scrum Team maintains for a product (Martinelli, Milosevic, 2016, p. 304). So the list containing all the steps that should be performed under the project. The customer is considered a priority value and has an impact on the decisions made. Backing product must bring real change, favorable to customers. Initial findings allow the introduction of adjustments and changes in the Thracian implementation. Particular attention is given to operations whose realization time is scheduled for the next sprint. A Sprint (or iteration) is the basic unit of development in Scrum. The Sprint is a time boxed effort; that is, it is restricted to a specific duration (Gandji, Hartman, 2015). The duration is fixed in advance for each Sprint and is normally between one week and one month, with two weeks being the most common (Schwaber, 2004). The Scrum Product Owner is responsible for the correctness of the Product Backlog. A client is required to actively participate in the implementation process in order to improve communication with the team, making key decisions, providing feedback (Konieczny, 2014). The next step is Sprint Planning. The Goal of this session is to define a realistic Sprint Backlog containing all items that could be fully implemented until the end of the Sprint. Therefore, sprint backlog is understood as a list of tasks to be performed in a specific sprint. It is important to the team that chooses the size and scope of the tasks for the next four weeks, pledging thereby to execute them. Turning to the software development the team performs its tasks in the course of one month. A private employee participates every day in the Daily Scrum. The duty of each member is giving a report of what they managed to do the day before and what goals have been set today. It is also important to remember and mention about all the encountered obstacles. Sprint is finished with Sprint Review. In this part the Product Owner is acquainted with the final product. During the Retrospective there is a discussion about successes, failures and future plans to improve the product obtained. If the purpose of Product Owner is a software update, the whole process starts from the beginning. Agile methods require an absolute knowledge of the rules and the full involvement of anyone who might have an impact on the success of the product. In return, they allow you to get the most satisfactory results. 4. Barriers and constraints the HaMIS project Located on the North Sea The Sea Port of Rotterdam from the XIV is the centre of maritime worldwide transport. The Port of Rotterdam Authority has a turnover of approximately €600 million and a staff of 1,100 employees with widely varying commercial, nautical, and infrastructure-related responsibilities. The foremost customer for the feature teams is the Harbour Master division. This business unit ensures the smooth, clean, and secure handling of shipping traffic (annually, approximately 33,000 ocean-going and 110,000 inland vessels) (Grigić, 2014). The success resulted in implementation of a new system in 2009 The system HaMIS. Harbour Master Information Management System has become the answer to the outdated, introduced in 1995 Pontis System. The technical barriers of Pontis prevented the further development of business processes, attracting new customers and efficient monitoring of ships. The introduction of the new system was necessary although it was associated with high risk. Changes could not adversely affect the work of the port and the fear of losing public trust as well as citizens’ money was an additional hurdle. The aim of the project was to introduce a new information system that will provide administration, management and inspection of vessels visiting Rotterdam at any time. The resulting plans, budget, expectations of suppliers and integrators of software made investors realize the demanding requirements and the accompanying risks. There was too much uncertainty about the project done with the use of waterfall method. The complexity of the project, unspecified objectives and implementation of the uncertain environment prompted investors to use Scrum. 5. The Product Owner Formally, the order has been placed by the Sea Port of Rotterdam. In defense of the interests two project managers were recruited. The first official acted as the project manager HaMIS. The other was responsible for external communications and coordination of the projects partly dependent on other companies or departments. Both of them came directly from business, and have always been dedicated full-time to HaMIS. The product owners were supported by a number of domain experts who would gather and provide information to product owners and teams (Grigić, 2014). The scope of their responsibilities associated with the determination of the project included: planning activities, making the most important decisions, responding to questions. The distribution of tasks between two people received a detailed development of each element of the project. Due to the public nature of the project, the analysis has been subjected to every potential user input system and its expectations. Systematically shared elements of the new system were subjected to the public. Based on the feedback they made adjustments and amendments. 6. HaMIS team and working conditions Understanding the nature and the scope of the operation scrum method was laborious. All the relevant issues of the project were discussed in the presence of all participants in the project. V. Grigić (2014), a project participant, published the following comment about project teams: We do have a number of very experienced craftsmen, but we also have many developers who only learned to write proper software in the past four years. The HaMIS team is a mix of Port of Rotterdam employees and contractors, with contractors making up about three-quarters of the workers. The contractors are a combination of freelancers and employees from several service integrators. It was interesting to observe that contractors, after four years and in some cases for much longer, felt more connected to HaMIS than their official employer. We can see that the confrontation of people with varying degrees of experience led to the exchange of information and the development of individual units. Project teams consisted of 3 to 7 people. The Management of the project did not interfere in the selection of new members of the teams. Confidence from the owner favored self-organizing teams. A 15-minute meeting (stand up) every morning became very common. It was an oral report of the achievements and obstacles encountered on the previous day. Each team had one Scrum Master, whose gesture was to raise awareness of essence and principles of the scrum in the various activities. The people who have influence on the finished software include: - Product Owner (two people) - Project & Program management (three people) - Domain Experts / Analysts (three people) - Scrum Master, developers, tasters, Geo (three people) - Scrum Master, Developers, testers, DBA (three people) - Scrum Master, developers / testers, UX (seven people) - Scrum Master, developers, testers, DBA (five people) - Infrastructure specialist (one person) Employing people with various professional qualifications and creating favorable working conditions led to better experience of individual employees. It finally brought more effective work. It is recognized that a good relations between team members is the key. Phone calls and video conferences using Skype overcame the barrier of space. Each success was celebrated. 7. Life cycle of HaMIS HaMIS is not an updating of existing software, but a completely new product created from scratch. The first elements were created with the use of waterfall method. The method involved restrictions which have changed the way of implementation of the software. The used life cycle of the project included product backing. Specific requirements of a customer and potential users became the basis of specific expectations of the implemented system. Plans included a range of activities for the next three months. Selection of acceptable agents were contained in the Sprint Planning. Their disposal between the various task groups formed Sprint Backlog. The Specifically developed range of activities of project teams concerned 4 weeks. A 15-minute daily report on the previous day (Daily Scrum) gave the actual picture of completed tasks. After the end of a one-month action plan, each team presented the final product to the Product Owners in Sprint Review. The meetings lasted an average of 1h. Thanks to the analysis of the previous month in Sprint Retrospective the team shared the obstacles which they came across taking into consideration suggested updates. 8. Features of HaMIS project The Analysis of Project HaMIS raises suspicion concerning the use of agile project to completion of the public project. The purpose of information contained in Table 1 is to compare and identify features combining the method of management in the discussed project with the scrum method. <table> <thead> <tr> <th>Scrum components</th> <th>Components of the HaMIS project</th> </tr> </thead> <tbody> <tr> <td>People involved in the project: The Product Owner, Scrum Master, Testers, Analysts, Programmer etc.</td> <td>Product Owner (2 people) Project &amp; Program management (3 people) Domain Experts / Analysts (3 people) Scrum Master, developers, tasters, Geo (3 people) Scrum Master, Developers, testers, DBA (3 people) Scrum Master, developers / testers, UX (7 people) Scrum Master, developers, testers, DBA (5 people) Infrastructure specialist (1 person)</td> </tr> <tr> <td>Recognition of customers’ needs as a priority.</td> <td>Product Owner was present at every stage of the project in order to improve communication with the team, make key decisions, give feedback.</td> </tr> <tr> <td>Working software delivered to a customer regularly every 3-4 weeks.</td> <td>Working software delivered after each Scrum within 4 weeks.</td> </tr> <tr> <td>The project team consists of 3 to 9 people.</td> <td>Individual task teams ranged from 3 to 7 people</td> </tr> <tr> <td>The product was created</td> <td>The right conditions for...</td> </tr> </tbody> </table> Success factors of agile programming - example of HaMIS <table> <thead> <tr> <th>by fully engaged people who were provided with the appropriate working conditions.</th> <th>individual and group work were provided. Phone calls and video conferences through Skype helped to avoid misunderstandings. They celebrated every positively ended scrum.</th> </tr> </thead> <tbody> <tr> <td>Development opportunities for individuals participating in the project.</td> <td>People with a lot of experience were able to demonstrate it. Responding to questions they educated inexperienced workers.</td> </tr> <tr> <td>Product Owners’ trust in employees.</td> <td>Management did not interfere in the selection of new employees by individual project teams.</td> </tr> <tr> <td>Team meetings last for 10 - 15 min. The previous day is analysed as &quot;done, in progress, to do&quot;.</td> <td>Daily meetings lasted for 15 minutes. The members exchanged their experience in the field of the problems encountered and the successes of the previous day.</td> </tr> </tbody> </table> Source: own elaboration. Presented in the table above components of the project HaMIS imply the use of the method as a dominant scrum. The reason for the start of the project was to replace the system Points with the new system, HaMIS, within two years. The main target has been achieved. The use of agile programming has allowed for the implementation of the new opportunities that were previously considered impossible. Without a doubt, the elements indicated in Table 1 had a decisive influence on the successful completion of the project, and thus its effectiveness. More than this, the attention was focused on the needs of specific visitors. Interviews, tests and observations of users during their work proved to be helpful. Not less important was the involvement of the project team members. 9. Summary Implementation of Agile methods is neither easy nor quick. It requires a thorough analysis of the current state of the organization and constructing the most optimal processes and their implementation. To exploit the benefits of Agile methodologies as fully as possible, it is essential to open yourself to the cultural and mental change in the organization (Stocki, Prokopowicz, Żmuda, 2008, p. 376). As shown in the example discussed, agile is possible to use in the project public after appropriate adaptation. Evidence of this effectively implemented method shows benefits of the system HaMIS. Its success consists of many factors. It is considered that the main element is a proper selection of duties and trainings in the methodology of scrum for teams. Giving the roles and responsibilities is clearly defined. A valuable ally to the project HaMIS was time, which mobilized to work at every stage of the project. The pressure of time increased effectiveness of the team and focused team’s attention on what's important. Updates appearing every 4 weeks gave the image of physical progress. Another motivator was adequate working conditions, development opportunities and mutual trust. However, the key element in the project proved to be a customer orientation. Specific purpose, testing and constant conversation with the customer allowed us to create a system with more opportunities than expected in the beginning. Without a doubt, the project HaMIS broke the barrier of the use of agile method in the public sector and has become an example worth following. Despite the huge success, many countries still have concerns about using agile in public sector. Using the method of waterfall in IT projects not only does not produce the desired results but more often fails. Bad management of public money has a negative impact on relations with citizens. The public sector needs improvement so it is important to promote and seek effective agile factors in order to use it in the public sector. References Czynniki sukcesu zwinnego zarządzania projektami – przykład HaMIS Karolina Piwowarczyk Uniwersytet Ekonomiczny w Krakowie Streszczenie: W artykule poruszono kwestię wdrożenia systemu informatycznego w sektorze publicznym przy użyciu zwinnego zarządzania. Artykuł ten ma na celu identyfikację czynników niezbędnych do skutecznego wdrażania projektów publicznych z wykorzystaniem Scrum. Ponadto koncentruje się również na identyfikowaniu czynników wpływających na tendencję do stosowania metod zwinnych. Przegląd literatury wykazał, że na skuteczność projektów Scrum wpływa między innymi czas, koordynacja zespołu i rezygnacja z nadmiernie dokumentacji. Przeprowadzona analiza pozwoliła na sformułowanie wniosków, że zwinność umożliwiła osiągnięcie większych korzyści, a zwiększenie skuteczności tych metodyk w sektorze publicznym wymaga stworzenia lepszych rozwiązań prawnych ułatwiających realizację złożonych projektów IT w środowisku o wysokim stopniu niepewności. Słowa kluczowe: agile, Scrum, sektor publiczny, HaMIS. Kody JEL: M15
{"Source-Url": "https://journalmmp.com/index.php/jmmp/article/download/55/57", "len_cl100k_base": 5218, "olmocr-version": "0.1.53", "pdf-total-pages": 8, "total-fallback-pages": 0, "total-input-tokens": 22584, "total-output-tokens": 6286, "length": "2e12", "weborganizer": {"__label__adult": 0.00029015541076660156, "__label__art_design": 0.0003044605255126953, "__label__crime_law": 0.0004045963287353515, "__label__education_jobs": 0.0031642913818359375, "__label__entertainment": 4.142522811889648e-05, "__label__fashion_beauty": 0.00013256072998046875, "__label__finance_business": 0.002620697021484375, "__label__food_dining": 0.0003294944763183594, "__label__games": 0.0004243850708007813, "__label__hardware": 0.0003535747528076172, "__label__health": 0.0004241466522216797, "__label__history": 0.0002191066741943359, "__label__home_hobbies": 8.988380432128906e-05, "__label__industrial": 0.00048828125, "__label__literature": 0.0001844167709350586, "__label__politics": 0.0002722740173339844, "__label__religion": 0.0002799034118652344, "__label__science_tech": 0.00432586669921875, "__label__social_life": 0.00010025501251220704, "__label__software": 0.00937652587890625, "__label__software_dev": 0.97509765625, "__label__sports_fitness": 0.0003142356872558594, "__label__transportation": 0.0004413127899169922, "__label__travel": 0.00019407272338867188}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 27835, 0.01934]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 27835, 0.20794]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 27835, 0.92178]], "google_gemma-3-12b-it_contains_pii": [[0, 3454, false], [3454, 8012, null], [8012, 11913, null], [11913, 16241, null], [16241, 20568, null], [20568, 24888, null], [24888, 26795, null], [26795, 27835, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3454, true], [3454, 8012, null], [8012, 11913, null], [11913, 16241, null], [16241, 20568, null], [20568, 24888, null], [24888, 26795, null], [26795, 27835, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 27835, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 27835, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 27835, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 27835, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 27835, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 27835, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 27835, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 27835, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 27835, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 27835, null]], "pdf_page_numbers": [[0, 3454, 1], [3454, 8012, 2], [8012, 11913, 3], [11913, 16241, 4], [16241, 20568, 5], [20568, 24888, 6], [24888, 26795, 7], [26795, 27835, 8]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 27835, 0.12037]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
6eeb56ba239db09d5bbc8e6191a654bbbf0605d6
Compiler Flow for Processors/Systems Prof. Dr.-Ing. Jeronimo Castrillon Chair for Compiler Construction TU Dresden – Cfaed MPSoC Winter School Tunis, Tunisia Nov. 2014 Acknowledgements - Cfaed content: from the Cfaed colleagues – visit www.cfaed.tu-dresden.de - Basic content: references given when appropriate - Research content: most of it carried out in Aachen at the Institute for Communication Technologies and Embedded Systems (ICE): Prof. Leupers, Weihua Sheng, Maximilian Odendahl, Miguel Aguilar 1. Introduction - What is a compiler? - Why do we care? What is a compiler - Compiler translates an input source code to a target code - Typical: target code closer to machine code (e.g., C → assembly) - Must recognize illegal code and generate correct code - Must agree with lower layers (e.g., storage, linker and runtime) History of compilers - **< 1950** Programming in assembly - **1950s** First machine-independent languages (skepticism) – A-0 Language To compile: “put things together” – Not really what it is today - **1959** Complete compiler – J. Backus @ IBM for Fortran (in assembly) Complexity: 15 man-year projects History of compilers (2) - **1960s** Theoretical work for code analysis - **1970** Bootstrapping becomes mainstream (C-compiler written in C) First ever: LISP in 1962 - **1970** Tools to create parts of the compiler (lex & yacc) - **1980s/90s** Code generator generators - **> 2000** Optimizations (mostly backend) - **Today** SIMD, vectorization, continuous compilation, new optimization goals, parallelizing compilers, domain-specific languages, skeletons, auto-tuning, … Compiler goals - First and foremost: **Correctness** - Correct translation while preserving semantics - Incorrect code must be discarded - Optimization goals - Typ.: Performance and code size - New: Energy/power consumption, robustness - Optimality? – Undecidable, often NP complete (especially in the Backend) - Off-line processing - Tolerable turn-around times – time complexity in $O(n) - O(n^2)$ - Some domains are more patient (embedded) Compilers for (heterogeneous) multi/many-cores - Single-processors - Clean interface through the compiler - The past - Multi-processors - Manual Process - The present/future - Deal with mapping, scheduling, synchronization - Different OSes - Different APIs - Compile vs. runtime - Programming Languages - (?) - Programming languages - Architectures & μ-arch This lecture Introduction to classical compilers Insight into MPSoC compilation (followed by hands-on) 2. Classical compilers - How does a compiler work? - Learn/refresh compiler phases - Learn/refresh theoretical background 3-phase compiler - **IR**: Intermediate representation - **Frontend**: Legal code ➔ IR - (Typ.) Target-independent - **Middle-end**: IR ➔ Optimized IR - (Typ.) Target-independent - **Backend**: IR ➔ Target code - Target-dependent Adapted from: A. Appel: Modern Compiler Implementation in C. Structure of a compiler: Front-end + Middle-end - **Lexical analysis**: Maps a character stream into words (tokens) - **Syntax (parser)**: - Recognizes “sentences of tokens” according to a grammar - Produces a representation of the application: **Syntax Tree** (ST) - **Semantic analysis**: Adds information and checks – types, declarations, … - **IR-generation**: Abstract representation of the program, amenable for code generation (backend) – A (abstract) syntax tree is a form of IR - **IR-optimization**: Simplification & improvements (e.g., remove redundancies) Structure of a compiler: Backend - Code selection: Decide which instructions should implement the IR - Register allocation: Decide in which register to place variables - Scheduling: Decide when to execute the instructions (e.g., ordering in assembly program) & ensure conformance with interfaces and constraints Lexical analysis – Example while (y < z) { int x = a + b; y += x; } Lexical analysis – The how - Use **regular expressions** to represent language elements (**tokens**) - Identifiers, integer/real constants, keywords (for, do, while, …) - **Examples** - Binary numbers: (1 | 0)* - Identifiers: [a-zA-Z][a-zA-Z0-9]* - **Principle of operation** - Describe all tokens with **regexp** - Create **finite state automaton** (FSA) for each regexp - Run all FSAs in parallel while reading the input source code Operation example Error-catch rule There are tools that automate the process \texttt{regexp} \rightarrow \texttt{automata}, example: \texttt{lex/flex} Annotate accepting space with the original NFA while (y < z) { int x = a + b; y += x; } Syntax analysis – The how - Structure of programming languages cannot be captured by regexp - Instead: Context Free Grammars (sloppy: a set of rules to produce programs) - Example ``` (1) E → E + T (2) E → T (3) T → T x F (4) T → F (5) F → id ``` This sequence of rules produced the program: `id + id x id` Syntax analysis: Parsing - We are interested in the opposite task - Parsing: Given a grammar and a program, find the syntax tree There are also tools to generate a parser automatically (yacc/bison, ANTLR) \[\begin{align*} (1) & \quad E \rightarrow E + T \\ (2) & \quad E \rightarrow T \\ (3) & \quad T \rightarrow T \times F \\ (4) & \quad T \rightarrow F \\ (5) & \quad F \rightarrow id \end{align*}\] while (y < z) { int x = a + b; y += x; } Semantic: int < int \(\rightarrow\) produces a bool ST: Syntax Tree (= parse tree) foo(int a, int b, int c, int d) { ... } bar() { int f[3], g[0], h, i, j, k; char *p; foo(h, i, "ab", j, k); k = f[i] + j; h = g[17]; printf("<%s,%s>\n", p, q); p = 10; } Why semantic analysis? To generate code, the compiler must understand meaning - Wrong number of arguments and type - Wrong dimension for f - Accessing g[17], but declared g[0] - q unknown - p is “char*” Adapted from: Keith D. Cooper, Ken Kennedy & Linda Torczon Semantic analysis – The how - Different approaches - Formal: Attribute grammars - Programmatic: Visitor pattern on the syntax tree (used by LLVM) - Symbol table: Data structure that stores object names and their attributes - Populated by walking the syntax tree - At any point of the tree - The compiler knows which variables, of which type, are available - Possible to check for correctness IR generation & optimization – Example while \((y < z)\) { int \(x = a + b\); \(y += x;\) } Loop: \(x = a + b\) \(y = x + y\) \(_t1 = y < z\) if \(_t1\) goto Loop Abstract representation of the program, closer to the target IR generation & optimization – The how - Walk the syntax tree to generate different implementations - The syntax tree is itself a form of IR - Use simple “code generation” - Optimize afterwards Abstract Syntax Tree (AST) Example: LLVM Framework ```c int main() { int a, b, c; a = 2; b = 3; c = 5; c += (a*b) >> a; c += foo(a); return 0; } ``` A lot of room for optimization! ```llvm define i32 @main() #0 { %1 = alloca i32, align 4 %a = alloca i32, align 4 %b = alloca i32, align 4 %c = alloca i32, align 4 store i32 0, i32* %1 store i32 2, i32* %a, align 4 store i32 3, i32* %b, align 4 store i32 5, i32* %c, align 4 %2 = load i32* %a, align 4 %3 = load i32* %b, align 4 %4 = mul nsw i32 %2, %3 %5 = load i32* %a, align 4 %6 = ashr i32 %4, %5 %7 = load i32* %c, align 4 %8 = add nsw i32 %7, %6 store i32 %8, i32* %c, align 4 %9 = load i32* %a, align 4 %10 = call i32 @foo(i32 %9) %11 = load i32* %c, align 4 %12 = add nsw i32 %11, %10 store i32 %12, i32* %c, align 4 ret i32 0 } ``` Graph representations: control flow graph - Control flow graph: Represent the branching structure of programs 1: a = 5; 2: c = 1; 3: L1: if (a > c) goto L2; 4: c = c + c; 5: goto L1; 6: L2: a = c – a; 7: c = 0; Basic-blocks: sequence of statements w/o branching in between 1: a = 5 2: c = 1 3: L1: if (a > c) goto L2; 4: c = c + c; 5: goto L1; 6: L2: a = c – a; 7: c = 0; The compiler has to know where the data is coming from for optimizations. 1: \( a = 5 \) 2: \( c = 1 \) 3: \( \text{L1: if } (a > c) \text{ goto L2;} \) 4: \( c = c + c; \) 5: \( \text{goto L1;} \) 6: \( \text{L2: } a = c - a; \) 7: \( c = 0; \) Data-flow information: Who could have defined \( c \)? (among other questions) Limits to analysis: Pointers if (\( a > *pX \)) Backend – Example while (y < z) { int x = a + b; y += x; } \[ x = a + b \] \[ \text{Loop: } y = x + y \] \[ _t1 = y < z \] \[ \text{if } _t1 \text{ goto Loop} \] \[ \text{ADD R1, R2, R3} \] \[ \text{ADD R4, R1, R4} \] \[ \text{SLT R6, R4, R5} \] \[ \text{BEQ R6, loop} \] Code selection – The how Principle: pattern matching in some form of IR (e.g., ASTs) \[ x = a - ((b \times c) + d) \] Based on a cost-model of the ISA LDR R1, $b MOV R1, R2 LDR R1, $c MAC R1, R1, R2, $d SUB R1, $a, R1 STR R1, $x © J. Castrillon. MPSoC Winter School. Tunisia Nov. 2014 Register allocation – The how - Reduce the amount of spill code (e.g., storing variables in the stack) - Find out life-ranges of variables (with a form of data flow analysis) - Apply graph coloring Register allocation – graph coloring These variables cannot be at this point in same register Neither these Neither these © J. Castrillon. MPSoC Winter School. Tunisia Nov. 2014 Register allocation – graph coloring (2) Connected nodes cannot be in the same register \[ \begin{align*} \{a, b, c, d\} \\ \{b, c, e\} \\ \{b, e, f\} \\ \{a, b, c, d\} \end{align*} \] Scheduling – The how - Find an order of instructions that minimizes the execution time - Has to respect data dependencies (a form of data analysis) Scheduling – dependency graph (inside basic block) \[ \begin{align*} t_0 &= t_1 + t_2 \\ t_1 &= t_0 + t_1 \\ t_3 &= t_2 + t_4 \\ t_0 &= t_1 + t_2 \\ t_5 &= t_3 + t_4 \\ t_6 &= t_2 + t_7 \\ \end{align*} \] Adapted from: http://web.stanford.edu/class/archive/cs/cs143/cs143.1128/ Schedules on a RISC processor: option 1 \[ \begin{align*} t_3 &= t_2 + t_4 \\ t_5 &= t_3 + t_4 \\ t_0 &= t_1 + t_2 \\ t_1 &= t_0 + t_1 \\ t_0 &= t_1 + t_0 \\ t_6 &= t_2 + t_7 \\ \end{align*} \] Schedules on a RISC processor: option 2 \[ \begin{align*} t_3 &= t_2 + t_4 \\ t_5 &= t_3 + t_4 \\ t_0 &= t_1 + t_2 \\ t_1 &= t_0 + t_1 \\ t_6 &= t_2 + t_7 \\ t_0 &= t_1 + t_0 \end{align*} \] <table> <thead> <tr> <th>Option 2</th> <th>1</th> <th>2</th> <th>3</th> <th>4</th> <th>5</th> <th>6</th> <th>7</th> <th>8</th> <th>9</th> <th>10</th> <th>11</th> <th>12</th> <th>13</th> <th>14</th> <th>15</th> <th>16</th> </tr> </thead> <tbody> <tr> <td>t0 = t1 + t2</td> <td>IF</td> <td>ID</td> <td>EX</td> <td>MM</td> <td>WB</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>t3 = t2 + t4</td> <td>IF</td> <td>ID</td> <td>EX</td> <td>MM</td> <td>WB</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>t6 = t2 + t7</td> <td>IF</td> <td>ID</td> <td>EX</td> <td>MM</td> <td>WB</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>t1 = t0 + t1</td> <td>IF</td> <td>ID</td> <td>EX</td> <td>MM</td> <td>WB</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>t5 = t3 + t4</td> <td>IF</td> <td>ID</td> <td>EX</td> <td>MM</td> <td>WB</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>t0 = t1 + t0</td> <td>IF</td> <td>ID</td> <td>EX</td> <td>MM</td> <td>WB</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> Saved cycles © J. Castrillon. MPSoC Winter School. Tunisia Nov. 2014 3. Insight multi-core compilers - Parallelizing sequential codes - Parallel dataflow models Recall: challenges in multi-core compilation - Programming languages - Architectures & μ-arch - Single-processors: The past - Multi-processors: The present/future - Programming Languages (?) - Manual Process - Architectures & μ-arch Uni-processor vs Multi-processor Uni-processor Sequential C Program ARM C Compiler Debugging - Simulator - (==Hardware) MPSoc Sequential C Program Task Partitioning Mapping/Scheduling Code Generation - Debugging - Virtual Platform and/or Hardware - Low Visibility - Parallel Debugging Multi-core compilers - Deal with similar problems than classical compilers - Parse and understand high-level parallel language constructs - Search for parallelism, but at a higher level of abstraction (higher than ILP) - Requires a model of the target architecture, but at coarser level - Allocation and scheduling of data to memories and tasks to processors - Code generation via source-to-source compilation On parallel programming models - There are many, really many: With different impacts on compilers - Sequential programming models: C/C++, Matlab, … - Parallel programming models - Shared memory: pthreads, OpenMP, Intel TBB, Cilk, … - Distributed memory: MPI, Charm++, … - In this presentation - Extracting coarse-grained parallelism from C code - Parallel dataflow models 3. Insight multi-core compilers - Parallelizing sequential codes - Parallel dataflow models Principle of operation - Similar compiler flow, but more challenges - More aggressive data flow analysis - More aggressive program transformations - Different granularity (basic-blocks?, functions?) - Focus on coarse-grained parallelism patterns - Whole program analysis Data-flow analysis - **Dynamic** data flow analysis via execution traces - More exact: Find exact portions of memory being read/written - Not sound: Cannot completely rely on dynamic information int main(void) { float x = 0.0; float y = 0.0; float z = 0.0; float a = 9.2; for (int i = 0; i < MAIN_LOAD_PLP; i++) { x = calculate_pi(); y = doSomeWork(x / 2); y = y + a; z = z + doSomeMoreWork(y / 4); } printf("z=%f\n", z); return 0; } On granularity - Granularity for analysis - Depends on the target platform - Requires whole-program information: Costs of functions called - Need to take communication into account - Is not given by traditional compiler boundaries: basic-blocks or functions → Use graph clustering algorithms Data edges: annotated with actual amount of information transported Course-grained parallelism patterns - Search for known parallelism patterns - Task-level parallelism - Data-level parallelism - Pipeline-level parallelism - Others: Reduction, commutative operations, ... Task Level Parallelism (TLP) Data Level Parallelism (DLP) Pipeline Level Parallelism (PLP) Judging parallelism patterns - TLP examples - DLP and PLP Need parallel performance estimation int main(void) { float x = 0.0; float y = 0.0; float z = 0.0; float a = 9.2; for (int i = 0; i < MAIN_LOAD_PLP; i++) { x = calculate_pi(); y = doSomeWork(x / 2); y = y + 3; z = z + doSomeMoreWork(y / 4); } printf("z=%f\n", z); return 0; } Whole program analysis - Global: Discard irrelevant partitions & Fix parameters (e.g., pipe stages) - Metrics: Efficiency & speedup \[ \eta = \frac{t_{seq}}{t_{par} \cdot n_{PE}} \] \[ x_{speedup} = \frac{t_{seq}}{t_{par}} \] Call graph Entire flow & code generation Source code Frontend Middle-end Backend Target code Control & data-flow graphs with profiling information Optimal configuration found by global analysis Architecture Model Parallel implementation (e.g., OpenMP, pthreads, MPI, …) Platform model: includes APIs for parallel execution Lessons learned - Automatic parallelism extraction is hard - Semi-automatic approach - It pays off for some applications depending on coding style - Focus on small patterns and do a good job for them - Application-specific knowledge is key - Partitioning data-structures is a must - High-level performance estimation is important (and difficult) - Important practical problem but not the solutions for many-cores 3. Insight multi-core compilers - Parallelizing sequential codes - Parallel dataflow models Process networks and dataflow programming - Kahn Process Networks (KPN) & other flavors of dataflow models - A node (process) represents computation - An edge (channel) represents communication - Output: Valid mapping (comply to constraints) - Process and channel mapping - Buffer sizing: Memory allocated for communication Static models: Synchronous Dataflow (SDF) - Fully specified rates, allow more compiler analysis - Compute **topology matrix**, and solve system of equations - Solution: **repetition vector** serve to unroll the graph $\[1 \ 3 \ 2\]$ - Perform mapping and scheduling on the resulting **directed acyclic graph** (DAG) Dynamic models: KPNs - Channel accesses not visible at the graph - Need to look inside the processes - Solutions: Use dynamic scheduling - Methods: Employ simulations, genetic algorithms or devise heuristics typedef struct { int i; double d; } my_struct_t; __PNchannel my_struct_t C; __PNchannel int A = {1, 2, 3}; /* Initialization */ __PNchannel short C[2], D[2], F[2], G[2]; __PNkpn AudioAmp __PNin(short A[2]) __PNout(short B[2]) __PNparam(short boost){ while (1) __PNin(A) __PNout(B) { for (int i = 0; i < 2; i++) B[i] = A[i]*boost; } __PNprocess Amp1 = AudioAmp __PNin(C) __PNout(F) __PNparam(3); __PNprocess Amp2 = AudioAmp __PNin(D) __PNout(G) __PNparam(10); Trace-based heuristics - Process tracing: Understand process interactions - Mapping - Mapping & scheduling: Analyze traces and propose mapping - Trace Replay Module (TRM): Evaluate mapping (parallel performance estimation) - Iterate: Improve mapping (if required) Process tracing Channel accesses depend on the internal code Performance estimation/simulation/measurement: A topic in itself ```c for (; i < x; i++) { write(&c2); f1(...); read(&c1); f2(...); read(&c1); }``` Event traces can be represented as large dependence graphs. Trace-based algorithms (2) - Sample trace graph - Possible to reason about - Channel sizes and memory allocation - Mapping and scheduling onto heterogeneous processors \[ \text{size(chan. 2) = 2, size(chan. 1,3) = 1} \] Example algorithm: Group-based mapping (GBM) 1) Initialize: All to all 2) Select element: Trace graph critical path 3) Reduce group 4) Assess & propagate 5) Quasi-homogeneous Heuristics for real-time applications - Common approach: iteratively add resources to the mapping algorithm - Allocate more memory to communication channels - Add more processors (intelligently) Code generation Mapping configuration Application model Code synthesis Platform model (HW/SW) PNargs_ifft_r.ID = 6U; PNargs_ifft_r.PNchannel_freq_coef = filtered_coef_right; PNargs_ifft_r.PNnum_freq_coef = 0U; PNargs_ifft_r.PNchannel_time_coef = sink_right; PNargs_ifft_r.channel = 1; sink_left = IPCllmrf_open(3, 1, 1); sink_right = IPCllmrf_open(7, 1, 1); PNargs_sink.ID = 7U; PNargs_sink.PNchannel_in_left = sink_left; PNargs_sink.PNnum_in_left = 0U; PNargs_sink.PNchannel_in_right = sink_right; PNargs_sink.PNnum_in_right = 0U; taskParams.arg0 = (xdc_UArg)&PNargs_src; taskParams.priority = 1; ... Sample results from mapping exploration [MJPEG decoder diagram] Iterative Mapping Real-time algorithm Real-time constraint Makespan (Gcycles) MJPEG Trials Config.: 3 PEs Config.: 5 PEs © J. Castrillon. MPSoC Winter School. Tunisia Nov. 2014 KPN Mapping: Lessons learned - Explicit parallelism makes it easier - Expressiveness requires intelligent trace analysis - Performance estimation/measurement/simulation/prediction is important - Code generation for heterogeneous MPSoCs bring great productivity improvements - Research directions - HW acceleration in the input language and programming methodology - Mixing implicit parallelism to scale to many-cores - Adaptability: Modifications to the topology & mapping configuration - Energy-aware @ coarse-level 4. Summary In this presentation - Basics topics on compilers - Efforts to hide complexity of programming heterogeneous multi and many-cores - With C code - From KPN extensions to C code - Outlook - Raise abstraction further: More implicit parallelism - **But** give more information to compiler: Domain Specific Languages, for portable performance - Right balance: Compile vs. run-time - New goals: Energy efficiency & resilience Thanks for the attention! Questions? References
{"Source-Url": "https://cfaed.tu-dresden.de/files/user/jcastrillon/publications/141127_castrillon_compilers.pdf", "len_cl100k_base": 6259, "olmocr-version": "0.1.49", "pdf-total-pages": 71, "total-fallback-pages": 0, "total-input-tokens": 109954, "total-output-tokens": 9302, "length": "2e12", "weborganizer": {"__label__adult": 0.00043892860412597656, "__label__art_design": 0.0003829002380371094, "__label__crime_law": 0.00032401084899902344, "__label__education_jobs": 0.0013437271118164062, "__label__entertainment": 6.300210952758789e-05, "__label__fashion_beauty": 0.0001888275146484375, "__label__finance_business": 0.00018131732940673828, "__label__food_dining": 0.0004732608795166016, "__label__games": 0.0007290840148925781, "__label__hardware": 0.0034942626953125, "__label__health": 0.0006113052368164062, "__label__history": 0.0002739429473876953, "__label__home_hobbies": 0.0001373291015625, "__label__industrial": 0.0008349418640136719, "__label__literature": 0.0001920461654663086, "__label__politics": 0.00030350685119628906, "__label__religion": 0.0007910728454589844, "__label__science_tech": 0.027862548828125, "__label__social_life": 8.189678192138672e-05, "__label__software": 0.003690719604492187, "__label__software_dev": 0.9560546875, "__label__sports_fitness": 0.0005092620849609375, "__label__transportation": 0.000950336456298828, "__label__travel": 0.0002551078796386719}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 21827, 0.03057]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 21827, 0.64933]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 21827, 0.69027]], "google_gemma-3-12b-it_contains_pii": [[0, 170, false], [170, 508, null], [508, 565, null], [565, 835, null], [835, 1144, null], [1144, 1627, null], [1627, 2087, null], [2087, 2469, null], [2469, 2574, null], [2574, 2697, null], [2697, 2996, null], [2996, 3569, null], [3569, 3882, null], [3882, 3959, null], [3959, 4408, null], [4408, 4444, null], [4444, 4608, null], [4608, 4657, null], [4657, 4967, null], [4967, 5373, null], [5373, 5523, null], [5523, 5974, null], [5974, 6384, null], [6384, 6619, null], [6619, 6848, null], [6848, 7722, null], [7722, 8113, null], [8113, 8492, null], [8492, 8775, null], [8775, 9065, null], [9065, 9264, null], [9264, 9446, null], [9446, 9633, null], [9633, 9782, null], [9782, 10086, null], [10086, 10281, null], [10281, 10997, null], [10997, 11090, null], [11090, 11333, null], [11333, 11680, null], [11680, 12101, null], [12101, 12483, null], [12483, 12576, null], [12576, 12858, null], [12858, 13058, null], [13058, 13367, null], [13367, 13738, null], [13738, 14045, null], [14045, 14142, null], [14142, 14451, null], [14451, 14692, null], [14692, 15014, null], [15014, 15434, null], [15434, 15527, null], [15527, 15860, null], [15860, 16177, null], [16177, 16389, null], [16389, 16851, null], [16851, 17122, null], [17122, 17354, null], [17354, 17414, null], [17414, 17641, null], [17641, 17817, null], [17817, 18017, null], [18017, 18625, null], [18625, 18874, null], [18874, 19401, null], [19401, 19412, null], [19412, 19844, null], [19844, 19881, null], [19881, 21827, null]], "google_gemma-3-12b-it_is_public_document": [[0, 170, true], [170, 508, null], [508, 565, null], [565, 835, null], [835, 1144, null], [1144, 1627, null], [1627, 2087, null], [2087, 2469, null], [2469, 2574, null], [2574, 2697, null], [2697, 2996, null], [2996, 3569, null], [3569, 3882, null], [3882, 3959, null], [3959, 4408, null], [4408, 4444, null], [4444, 4608, null], [4608, 4657, null], [4657, 4967, null], [4967, 5373, null], [5373, 5523, null], [5523, 5974, null], [5974, 6384, null], [6384, 6619, null], [6619, 6848, null], [6848, 7722, null], [7722, 8113, null], [8113, 8492, null], [8492, 8775, null], [8775, 9065, null], [9065, 9264, null], [9264, 9446, null], [9446, 9633, null], [9633, 9782, null], [9782, 10086, null], [10086, 10281, null], [10281, 10997, null], [10997, 11090, null], [11090, 11333, null], [11333, 11680, null], [11680, 12101, null], [12101, 12483, null], [12483, 12576, null], [12576, 12858, null], [12858, 13058, null], [13058, 13367, null], [13367, 13738, null], [13738, 14045, null], [14045, 14142, null], [14142, 14451, null], [14451, 14692, null], [14692, 15014, null], [15014, 15434, null], [15434, 15527, null], [15527, 15860, null], [15860, 16177, null], [16177, 16389, null], [16389, 16851, null], [16851, 17122, null], [17122, 17354, null], [17354, 17414, null], [17414, 17641, null], [17641, 17817, null], [17817, 18017, null], [18017, 18625, null], [18625, 18874, null], [18874, 19401, null], [19401, 19412, null], [19412, 19844, null], [19844, 19881, null], [19881, 21827, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 21827, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 21827, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 21827, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 21827, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 21827, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 21827, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 21827, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 21827, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 21827, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 21827, null]], "pdf_page_numbers": [[0, 170, 1], [170, 508, 2], [508, 565, 3], [565, 835, 4], [835, 1144, 5], [1144, 1627, 6], [1627, 2087, 7], [2087, 2469, 8], [2469, 2574, 9], [2574, 2697, 10], [2697, 2996, 11], [2996, 3569, 12], [3569, 3882, 13], [3882, 3959, 14], [3959, 4408, 15], [4408, 4444, 16], [4444, 4608, 17], [4608, 4657, 18], [4657, 4967, 19], [4967, 5373, 20], [5373, 5523, 21], [5523, 5974, 22], [5974, 6384, 23], [6384, 6619, 24], [6619, 6848, 25], [6848, 7722, 26], [7722, 8113, 27], [8113, 8492, 28], [8492, 8775, 29], [8775, 9065, 30], [9065, 9264, 31], [9264, 9446, 32], [9446, 9633, 33], [9633, 9782, 34], [9782, 10086, 35], [10086, 10281, 36], [10281, 10997, 37], [10997, 11090, 38], [11090, 11333, 39], [11333, 11680, 40], [11680, 12101, 41], [12101, 12483, 42], [12483, 12576, 43], [12576, 12858, 44], [12858, 13058, 45], [13058, 13367, 46], [13367, 13738, 47], [13738, 14045, 48], [14045, 14142, 49], [14142, 14451, 50], [14451, 14692, 51], [14692, 15014, 52], [15014, 15434, 53], [15434, 15527, 54], [15527, 15860, 55], [15860, 16177, 56], [16177, 16389, 57], [16389, 16851, 58], [16851, 17122, 59], [17122, 17354, 60], [17354, 17414, 61], [17414, 17641, 62], [17641, 17817, 63], [17817, 18017, 64], [18017, 18625, 65], [18625, 18874, 66], [18874, 19401, 67], [19401, 19412, 68], [19412, 19844, 69], [19844, 19881, 70], [19881, 21827, 71]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 21827, 0.01307]]}
olmocr_science_pdfs
2024-11-24
2024-11-24
94dcfa04687b61a01422a5354e81ca1f37797849
CSC384: Lecture 4 - Last time - done with DCL (except for the fact that we’ll use it!) - Today - quick summary of uses of DCL (from last time) - Intro to search; generic search procedure; BrFS, DFS, path extraction, cycle and mult.path checking - Readings: - Today: Ch.4.1 – 4.4, 4.6 - Next week: Ch.4.5/4.6 A Planning Problem - A planning problem: we want robot to decide what to do; how to act to achieve our goals A Planning Problem - How to change the world to suit our needs - Critical issue: we need to reason about how the world will be after doing a few actions, not just what it is like now GOAL: Craig has coffee CURRENTLY: robot in mailroom, has no coffee, coffee not made, Craig in office, etc. TO DO: goto lounge, make coffee,... Planning - So far, we’ve seen DCL used to reason about *static environments* (what the world *is like*) - what is correct treatment for symptom X? - is this region water or land? - Want to use DCL to reason about *dynamic environments* - A,B,C are true: will they still be true after doing X? - A,B,C are true: what do I need to do to make D true? - The heart of decision making! - complexities: uncertainty (where is craig? navigate stairs?); *many actions to choose from (what is right sequence?)*; exogenous events (battery loses charge) Graph Search - We’ll abstract away complexities of planning - focus on finding the right sequence of actions only - going to ignore the fact that at any point in time many things are true and false - Treat planning as the search for a path from one state (of the world) to a desired goal state - Informally: We have a set of states, and a set of moves/actions that take us from one state to another. Given an initial state (current) and target state (goal), find a sequence of moves that gets me from initial state to goal - or shortest sequence, or cheapest sequence, or … Graph Search is Very General - This viewpoint applies to a wide variety of tasks - **RoboCof** – find plan that gives Craig coffee; route across floor plan; etc. [states? moves? objective?] - **Games** – 8-puzzle; backgammon; chess; Doom; [complications: other players making moves] - Scheduling, logistics, planning, most optimization problems - **Medical diagnosis** - **Scene interpretation** – find a consistent labeling - **Finding a derivation** in DCL/Prolog [what are states? moves? goal?] - **Finding a good travel package** [states? moves?] - Almost every problem in AI can be viewed this way! Graph-based Search Formalization - A directed graph: set of nodes $N$, set of directed edges $E \subseteq N \times N$ (these are ordered pairs) - nodes correspond to states we can move among - If $\langle n_1, n_2 \rangle \in E$, then $n_2$ is a neighbor of $n_1$ - written $n_1 \rightarrow n_2$ (relation is not symmetric) - edges correspond to possible moves we can make - A node labeling is a function $L_n : N \rightarrow N\text{labels}$ - denote properties of states (e.g., a value) - An edge labeling is a function $L_e : E \rightarrow E\text{labels}$ - denote properties of edges (e.g., a move cost) An Very Simple Search Graph Nodes (states) are locations robot can move among Edges are routes among these locations Edge labels denote costs (e.g., expected travel time) Paths and Cycles - A **path** in graph $G = (N,E)$ is a sequence of nodes $\langle n_1, n_2, \ldots, n_k \rangle$ s.t. each $\langle n_i, n_{i+1} \rangle \in E$ - $n_1 \to n_2 \to \ldots \to n_k$ is a path from $n_1$ to $n_k$ - A **cycle** is a path $\langle n_1, n_2, \ldots, n_k \rangle$ with $n_1 = n_k$ (k > 1) - A graph $G$ is acyclic if no path in $G$ is a cycle - A path is acyclic if no subpath is a cycle Graph Search Problems - **A graph search problem**: given graph \((N,E)\), a start node \(s \in N\), and a set of goal nodes \(G \subseteq N\), find a path \(P\) from \(s\) to some \(g \in G\) satisfying property \(X\). - **Possible properties \(X\):** - \(X = \text{“null”}\): Any path to any node in \(G\) will do - *Find me any path to the office* - \(X = \text{“P is the best path to goal G”}\): this means we have some optimization criterion we need to satisfy - possible criteria: shortest (# edges); least cost; etc. - *Find me shortest/fastest path to office* - \(X = \text{“P has quality } \geq q\text{”} (\text{a satisficing problem}) - *Find me a path that gets me to the office by 10AM* A Couple Notes - If arcs are labeled with actions, we often want to return the sequence of actions, not just the path. - Most interesting search problems involve *implicit search graphs*: - e.g., consider chess: nobody constructs a graph of all $10^{30}$ board positions explicitly. - e.g., Prolog: answer clauses generated as derived. - when solving search problem, we generate neighbors as we need them. - define states, neighborhood relation… or define moves and how to generate neighboring state. Generic Search Procedure - Many graph search techniques share the following common structure - let the **frontier** refer to set of nodes we already know how to reach from the start node \( s \) 1. Let \( F = \{s\} \); (initial frontier is start node) 2. Loop until frontier is empty (a) Choose some node \( n \) on frontier; remove \( n \) from \( F \) (b) If \( n \in G \) then stop; report success (c) Otherwise add each neighbor of \( n \) to \( F \) A Generic DCL Implementation search( F ) :- select(Node, F, RemF), is_goal(Node). search( F ) :- select(Node, F, RemF), nbs(Node, NbList), add_to_frontier(RemF, NbList, NewF), search( NewF ). 1. nbs(Node, NbList) defines the search graph - for each node, we assert its list of nbs in KB - if implicit search graph, nbs will generate NBList 2. is_goal(N) defines the set of goal nodes - for each goal node, we assert this in KB Generic Search Procedure - Assume frontier represented as a list of nodes - \( \text{search}(F) \) returns yes there is some path to \( G \) from \( F \) - so call with start node \( s \) on frontier: \( \text{search}( \{ s \} ) \) - \( \text{select}(N,F,\text{RemF}) \): true if selecting node \( N \) from frontier \( F \) leaves remaining frontier \( \text{RemF} \) - \( \text{add_to_frontier}(\text{RemF},\text{NbList},\text{NewF}) \): true if adding nodes in \( \text{NbList} \) to \( \text{RemF} \) results in \( \text{NewF} \) One Instantiation of Search Proc. search( F ) :- select(Node, F, RemF), is_goal(Node). search( F ) :- select(Node, F, RemF), nbs(Node, NbList), add_to_frontier(RemF, NbList, NewF), search( NewF ). select(Node, [Node|RemF], RemF). add_tf (RemF, NbList, NewF) :- append(NbList, RemF, NewF). --- **Simple implementation** - you can only select the first node on the frontier - you add neighbors of selected node to the beginning of the frontier (just append them to front) A Modified Example Graph: - nb(off, [mr, h]). - nb(h, []). - nb(mr, [lng]). - nb(lng, []). - nb(lab, [lng]). Goal Node: - isgoal(h). Start Node: - office search([off]). - select off, RF = [] - not a goal, NF = [mr, h] search([mr, h]). - select mr, RF = [h] - not a goal, NF = [lng, h] search([lng]). - select off, RF = [h] - not a goal, NF = [h] search([h]). - select off, RF = [] - is a goal, NF = [mr, h] Return yes! Search Tree for Modified Example No neighbors! Numbering reflects order in which nodes are examined (isgoal?) What if we added an edge from Ing to lab? Depth-First Search - The specific instantiation we’ve seen is simply **depth-first search** (which you’ve seen previously, no doubt) - in the search tree, we work deep into the tree until we reach a dead-end, then we “backtrack” - In generic search algorithm, this is achieved by: - always selecting first node on the frontier - always inserting the new neighbors at head of frontier - Note: all “bookkeeping” required for backtracking is taken care of by organization of the frontier Defn of Search Tree - Given a search graph, start node $s$ - The *search tree rooted at $s$* is a tree such that: - root node is $s$ - each node has all its neighbors for children - So at level $k$ of the tree are all states that you can reach in exactly $k$ moves (where root = 0) - each path in search graph (including cyclic paths) is a path through search tree - nodes in graph can appear *many* times in tree - Frontier moves “down” the tree Manhattan Bike Courier (Acyclic) The MBC Rep’n (No Costs) \[ \begin{align*} \text{mo: } & \text{Main Office} \\ \text{al: } & \text{Alley} \\ \text{eif: } & \text{Ellis Island Ferry} \\ \text{ls: } & \text{Loeb Securities} \\ \text{slb: } & \text{Shearson-Lehmann Bros.} \\ \text{rp: } & \text{Rector Park} \\ \text{ch: } & \text{City Hall} \\ \text{fs: } & \text{Fulton Street} \\ \text{ws: } & \text{Wall Street} \\ \text{sec: } & \text{Securities Exch. Comm.} \\ \text{bp: } & \text{Battery Park} \\ \text{ase: } & \text{Amer. Stock Exch.} \\ \text{trp: } & \text{T.Rowe Price} \\ \text{bb: } & \text{Brooklyn Bridge} \\ \text{ac: } & \text{Anderson Consulting} \\ \text{p27: } & \text{Pier 27} \\ \text{nyse: } & \text{NY Stock Exch.} \end{align*} \] \[ \begin{align*} \text{nb(mo, [al, ls, ws, ch]).} & \quad \text{nb(slb, [])}. \\ \text{nb(sec, [ase, bp, nyse]).} & \quad \text{nb(fs, [])}. \\ \text{nb(ws, [fs, sec, nyse, ac]).} & \quad \text{nb(eif, [ls]).} \\ \text{nb(ac, [trp, nyse, p27]).} & \quad \text{nb(al, [eif]).} \\ \text{nb(ase, [slb, rp]).} & \quad \text{nb(ls, [sec]).} \\ \text{nb(ch, [fs, ac, trp]).} & \quad \text{nb(rp, [])}. \\ \text{nb(trp, [bb]).} & \quad \text{nb(p27, [])}. \\ \text{nb(bb, []).} & \quad \text{nb(bp, [])}. \\ \text{nb(nyse, [bp]).} & \end{align*} \] Search Tree: MBC Acyclic; Start *mo* DepthFirst Search: Start \textit{mo}; Goal \textit{bp} Example Summary - **DFS expands** eight nodes in this example - it examines eight nodes and tests if they are the goal (if they are not, it add neighbors to frontier) - **DFS does not find the shortest path to bp** - the order in which it is required to examine nodes doesn’t allow it to find the shortest path Path Extraction search(F) :- select(Node, F, RemF), is_goal(Node). search(F) :- select(Node, F, RemF), nbs(Node, NbList), add_to_frontier(RemF, NbList, NewF), search(NewF). - Generic search procedure behaves as follows: - assert \textit{isgoal}(bp) ; ask \textit{?search}([mo]). - algorithm says yes. - but what path does courier take?? - says yes if there is a path, but doesn’t tell us what it is - We need a \textit{path extraction mechanism} - simplest thing to do is store paths on frontier - when you select a node from frontier, you also have a specific path to that node attached - \textit{search}(F,Path) : true if Path is solution to search Implementing Path Extraction Assume a path is represented as a list of nodes in reverse order: so the path \( \text{mo} \rightarrow \text{al} \rightarrow \text{eif} \) is represented as the list: \([\text{eif}, \text{al}, \text{mo}]\) \[ \text{search( F, [Node | RestP] ) :-} \quad \text{select( [Node | RestP], F, RemF),} \quad \text{is_goal(Node).} \] \[ \text{search( F, Path ) :-} \quad \text{select( [Node | RestP], F, RemF ),} \quad \text{nbs(Node, NbList),} \quad \text{extendpath(NbList, [Node | RestP], NewPaths ),} \quad \text{add_to_frontier(RemF, NewPaths, NewF),} \quad \text{search( NewF, Path ).} \] Notes on Path Extraction - We call search from start node \( mo \) using \texttt{search}([ [mo], Path ]). - initial frontier consists of a length one \textit{path} (not node) - Only new predicate needed is \textit{extendpath} - basic idea: given a path \([n_3, n_2, n_1]\) and neighbors of \( n_3 \) specified by \texttt{nbs}(n_3, [n_4, n_5, n_6]); it produces 3 new paths organized in a list: \[ [ [n_4, n_3, n_2, n_1], [n_5, n_3, n_2, n_1], [n_6, n_3, n_2, n_1] ] \] DFS with Path Extraction \[ \text{search( F, [Node \mid RestP] ) :-} \] \[ \text{select([Node \mid RestP], F, RemF),} \] \[ is\_goal(Node). \] \[ \text{search( F, Path ) :-} \] \[ \text{select([Node \mid RestP], F, RemF),} \] \[ nbs(Node, NbList), \] \[ extendpath(NbList, [Node \mid RestP], NewPaths), \] \[ add\_to\_frontier(RemF, NewPaths, NewF), \] \[ search( NewF, Path ). \] \[ \text{select(Path, [Path\midRestPaths], RestPaths).} \] \[ \text{add\_tf (RemF, Paths, NewF) :-} \] \[ append(Paths, RemF, NewF). \] Search Tree: MBC Acyclic; Start \textit{mo} Trace of DFS (with paths: mo to fs) Frontier evolution: 1. [mo] 2. [al,mo] [ls,mo] [ws,mo] [ch,mo] (= A) 5. [sec,ls,eif,al,mo] ..A.. 6. [ase,sec,...,mo] [bp,sec,...,mo] [nyse,sec,...,mo] ..A.. (= B) 7. [slb,ase,...,mo] [rp,ase,...,mo] ..B.. ..A.. 8. [rp,ase,...,mo] ..B.. ..A.. 9. [bp,sec,...,mo] [nyse,sec,...,mo] ..A.. 10. [nyse,sec,...,mo] ..A.. 12. [ls,mo] [ws,mo] [ch,mo] 13. [sec,ls,mo] [ws,mo] [ch,mo] 14-19. Exactly like expansion of [sec,ls,wtc,al,mo] in Steps 6-11 20. [ws,mo] [ch,mo] 21. [fs,ws,mo] [sec,ws,mo] [nyse,ws,mo] [ac,ws,mo] [ch,mo] GOAL = fs is found Total Search steps: 21 nodes expanded Paths Explored by DFS in Example Properties of DFS: Time How long can DFS take? (a) **Finite graph, no cycles:** - Could explore each branch of search tree (until goal found or search fails). - If branching factor bounded by $b$, depth bounded by $n$, then we explore $O(b^n)$ full paths (length $n$) - note: $n \leq N$ (number of nodes in $G$) (b) Finite graph with cycles: - may not terminate unless we perform cycle checking (later) - Does it ever make sense to explore a cyclic path? (c) If we’re **lucky** with the node ordering: - may find soln in $n^*$ steps ($n^*$ is length of shortest path to goal) Properties of DFS: Space - How many paths on frontier at any one time? - If current path length $m$ (i.e., current node selected), then there are $bm$ paths on frontier - If longest path is length $n$, then never more than $bn$ paths - $b$ paths have length 1, $b$ length 2, etc. up to $b$ paths of length $n$ - Total space $b + 2b + 3b + \ldots nb$ which is $O(n^2b)$ space - Is quadratic space required? - No: many paths have common substructure - Consider how to store frontier in linear space $O(nb)$: use a tree! Properties of DFS: Solution Quality - Will DFS find the shortest (min # arcs) solution? - In general, no. - It can if you are lucky. - In Manhattan (acyclic) problem, with start mo and goal ls, it returns soln: \( \text{mo} \rightarrow \text{al} \rightarrow \text{eif} \rightarrow \text{ls} \), even though shorter solution \( \text{mo} \rightarrow \text{ls} \) exists. - So how can we find shortest path? Breadth-First Search - One way to ensure shortest solution is found (wrt # of arcs) is to explore paths in order of length - **Breadth-first search (BFS)** does exactly this - It is implemented by selecting nodes/paths from the front of the frontier (like DFS), but inserting new neighbors/paths at the *end of the frontier* ```prolog select(Path, [Path|RestPaths], RestPaths). add_tf (RemF, Paths, NewF) :- append( RemF, Paths, NewF). ``` *differs from DFS only in order of arguments to append* Frontier Growth in BFS e tc. Trace of BFS (with paths: mo to fs) Frontier evolution: 1. **Length 0 Paths** [mo] 2. **Length 1 Paths (inserted after 1 len1 path)** inserted at end of frontier in order shown [al, mo] [ls, mo] [ws, mo] [ch, mo] 3. **Length 2 Paths (inserted after 4 len1 paths)** inserted at end of frontier in order shown [eif, al, mo] [sec, ls, mo] [fs, ws, mo] [fs, ch, mo] [sec, ws, mo] [ac, ch, mo] [nyse, ws, mo] [trp, ch, mo] [ac, ws, mo] 4. **Length 3 Paths (inserted after 9 len2 paths)** inserted at end of frontier in order shown [ls, eif, al, mo] [ase, sec, ls, mo] (plus 14 more paths not added to frontier) [bp, sec, ls, mo] [nyse, sec, ls, mo] On Third Step (3rd Path in the Length 2 Frontier), the goal FS will be found. Total Search steps: 1+4+3 = 8 8 nodes expanded Paths Explored by BFS in Example Properties of BFS - All paths of length $k$ occur on frontier after all length $k-1$ paths - No length $k$ path is added to frontier until we have expanded all length $k-1$ paths - This last property ensures that we are guaranteed to find shortest path (if sol’n exists) - If we find a length $k$ sol’n, since we’ve looked at all shorter paths, no shorter sol’n exists Properties of BFS: Time - How long can BFS take? (a) **Finite graph, no cycles:** - If branching factor bounded by \( b \), and the shortest sol’n has length \( n^* \), then we’ll explore \( O(b^{n^*}) \) paths (length \( n \)) - Note: presence of cycles has no effect if a solution is present - If no solution, will explore all paths: \( O(b|N|) \) (b) **Finite graph with cycles:** - If sol’n: same as above - If no sol’n: may not terminate unless we perform cycle checking or multiple path checking Properties of BFS: Space - How many paths on frontier at any one time? - If current path length $m$, then there are between $b^{m-1}$ and $b^m$ paths on frontier - If shortest path has length $n^*$, then guaranteed to have frontier of size $O(b^{n^*})$ - Luck with node ordering plays no role: BFS is systematic - Space cost is the price you pay for optimality Cycle Checking (see text for more) - Cycles can hurt DFS: can prevent termination - **Cycle checking** in DFS: requires a simple test - when you select a path from frontier and extend it with its neighbors, we only add a new path to the frontier if the neighbor is not already on the path - Test requires linear time in length of path - some tricks can be used to reduce this - Cannot affect existence of soln, rule out best soln \[ n_1 \rightarrow n_2 \rightarrow n_3 \] - \( n_4 \) \( \checkmark \) \([n_4, n_3, n_2, n_1]\) - \( n_2 \) \( \times \) \([n_2, n_3, n_2, n_1]\) - \( n_5 \) \( \checkmark \) \([n_5, n_3, n_2, n_1]\) Multiple Paths to Same Node - In Manhattan example, with start = mo: - at depth 2, we have path $P_1 = [ls, mo]$ - at depth 4, we have path $P_2 = [ls, eif, al, mo]$ - Why add $P_2$ to the frontier? - If there is a path from $ls$ to goal, then extension of $P_1$ to the goal is shorter than the extension of $P_2$ (each extension of $P_2$ added to frontier is just wasted) - If there is no path from $ls$ to goal, not adding $P_2$ to frontier cannot hurt Multiple Path Checking in BFS - Cycle checking can be applied to BFS too - saves some time (don’t explore cyclic path) - ensures termination in cyclic graphs with no solution - **Multiple path checking** is more general - Every time a (path to a) node is considered for addition to frontier, check list of *visited* nodes (those that have already been expanded). - If node is on list, do not add it to the frontier. - If node is not on list, add it to frontier and visited list. - In BFS, need an extra argument: *VisitedList* - MPC subsumes cycle checking Notes on MPC • In BFS, we need an extra argument, \textit{VisitedList}, to maintain the list of visited nodes • what would you initialize \textit{VisitedList} with on first call? • \textbf{MPC subsumes} cycle checking • a cycle is just one type of “multiple path” to same node • Why doesn’t MPC make sense for DFS? • Exercise: Sketch out revised clauses defining: • DFS with cycle checking • BFS with MPC
{"Source-Url": "http://www.dgp.toronto.edu:80/~ppacheco/course/384/Lectures/Lecture4.pdf", "len_cl100k_base": 6059, "olmocr-version": "0.1.50", "pdf-total-pages": 45, "total-fallback-pages": 0, "total-input-tokens": 76552, "total-output-tokens": 8047, "length": "2e12", "weborganizer": {"__label__adult": 0.0004651546478271485, "__label__art_design": 0.00079345703125, "__label__crime_law": 0.0007476806640625, "__label__education_jobs": 0.0197601318359375, "__label__entertainment": 0.00020301342010498047, "__label__fashion_beauty": 0.00029158592224121094, "__label__finance_business": 0.0004706382751464844, "__label__food_dining": 0.0005955696105957031, "__label__games": 0.00261688232421875, "__label__hardware": 0.00124359130859375, "__label__health": 0.0006976127624511719, "__label__history": 0.0007691383361816406, "__label__home_hobbies": 0.00041365623474121094, "__label__industrial": 0.00113677978515625, "__label__literature": 0.0009312629699707032, "__label__politics": 0.0005011558532714844, "__label__religion": 0.000698089599609375, "__label__science_tech": 0.1241455078125, "__label__social_life": 0.0003533363342285156, "__label__software": 0.0149383544921875, "__label__software_dev": 0.8251953125, "__label__sports_fitness": 0.00081634521484375, "__label__transportation": 0.0016736984252929688, "__label__travel": 0.0004055500030517578}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 19563, 0.00958]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 19563, 0.58635]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 19563, 0.80735]], "google_gemma-3-12b-it_contains_pii": [[0, 321, false], [321, 431, null], [431, 759, null], [759, 1311, null], [1311, 1894, null], [1894, 2533, null], [2533, 3151, null], [3151, 3325, null], [3325, 3747, null], [3747, 4470, null], [4470, 4980, null], [4980, 5448, null], [5448, 5924, null], [5924, 6465, null], [6465, 6973, null], [6973, 7400, null], [7400, 7555, null], [7555, 8047, null], [8047, 8503, null], [8503, 8536, null], [8536, 9803, null], [9803, 9840, null], [9840, 9895, null], [9895, 10220, null], [10220, 10909, null], [10909, 11527, null], [11527, 12013, null], [12013, 12534, null], [12534, 12578, null], [12578, 13279, null], [13279, 13312, null], [13312, 13892, null], [13892, 14424, null], [14424, 14838, null], [14838, 15341, null], [15341, 15371, null], [15371, 16187, null], [16187, 16220, null], [16220, 16592, null], [16592, 17108, null], [17108, 17477, null], [17477, 18114, null], [18114, 18579, null], [18579, 19147, null], [19147, 19563, null]], "google_gemma-3-12b-it_is_public_document": [[0, 321, true], [321, 431, null], [431, 759, null], [759, 1311, null], [1311, 1894, null], [1894, 2533, null], [2533, 3151, null], [3151, 3325, null], [3325, 3747, null], [3747, 4470, null], [4470, 4980, null], [4980, 5448, null], [5448, 5924, null], [5924, 6465, null], [6465, 6973, null], [6973, 7400, null], [7400, 7555, null], [7555, 8047, null], [8047, 8503, null], [8503, 8536, null], [8536, 9803, null], [9803, 9840, null], [9840, 9895, null], [9895, 10220, null], [10220, 10909, null], [10909, 11527, null], [11527, 12013, null], [12013, 12534, null], [12534, 12578, null], [12578, 13279, null], [13279, 13312, null], [13312, 13892, null], [13892, 14424, null], [14424, 14838, null], [14838, 15341, null], [15341, 15371, null], [15371, 16187, null], [16187, 16220, null], [16220, 16592, null], [16592, 17108, null], [17108, 17477, null], [17477, 18114, null], [18114, 18579, null], [18579, 19147, null], [19147, 19563, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 19563, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 19563, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 19563, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 19563, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 19563, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 19563, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 19563, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 19563, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 19563, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 19563, null]], "pdf_page_numbers": [[0, 321, 1], [321, 431, 2], [431, 759, 3], [759, 1311, 4], [1311, 1894, 5], [1894, 2533, 6], [2533, 3151, 7], [3151, 3325, 8], [3325, 3747, 9], [3747, 4470, 10], [4470, 4980, 11], [4980, 5448, 12], [5448, 5924, 13], [5924, 6465, 14], [6465, 6973, 15], [6973, 7400, 16], [7400, 7555, 17], [7555, 8047, 18], [8047, 8503, 19], [8503, 8536, 20], [8536, 9803, 21], [9803, 9840, 22], [9840, 9895, 23], [9895, 10220, 24], [10220, 10909, 25], [10909, 11527, 26], [11527, 12013, 27], [12013, 12534, 28], [12534, 12578, 29], [12578, 13279, 30], [13279, 13312, 31], [13312, 13892, 32], [13892, 14424, 33], [14424, 14838, 34], [14838, 15341, 35], [15341, 15371, 36], [15371, 16187, 37], [16187, 16220, 38], [16220, 16592, 39], [16592, 17108, 40], [17108, 17477, 41], [17477, 18114, 42], [18114, 18579, 43], [18579, 19147, 44], [19147, 19563, 45]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 19563, 0.0]]}
olmocr_science_pdfs
2024-11-28
2024-11-28
1ceb627f9493e4adc4183ff39074190818e4cfe7
Problem 1: Miscellaneous Short Problems (25 pts) A. (8 pts) A key idea in this course is the difference between abstraction and implementation. Consider two abstractions we’ve studied: ISPC’s foreach and Cilk’s spawn construct. Briefly describe how these two abstractions have similar semantics. (Hint: what do the constructs declare about the associated loop iterations? Be precise!). Then briefly describe how their implementations are quite different (Hint: consider their mapping to modern CPUs). As a reminder, we give you two syntax examples below: ISPC foreach: ```c void f(int i, float* x, float* y) { x[i] = y[i] } ``` ```c foreach (i = 0 ... 100) { x[i] = y[i]; } ``` Cilk: ```c void f(int i, float* x, float* y) { x[i] = y[i] } ``` ```c for (int i=0; i<100; i++) { cilk_spawn f(i, x, y); } ``` B. (7 pts) You have a simple message passing program that uses **blocking sends** to communicate with remote processor P1. Pseudocode is below. ```c int my_buffer[32]; // initialize contents of my_buffer with msg 1 here .. // send second message to P2 send(P1, 32, my_buffer); // write contents of msg 2 into my_buffer here .. // send second message to P2 send(P1, 32, my_buffer); ``` Your friend remembers the conversation about deadlock when using blocking sends from class, and changes to code so that asynchronous sends are used instead of blocking sends are used. The program immediately starts giving incorrect results. Why? (A full credit answer will briefly describe how to modify the code so that it is both correct and maintains asynchronous communication of both messages.) C. (10 pts) In class we described the usefulness of making roofline graphs, which plots the instruction throughput of a machine (gigaops/sec) as a function of a program’s arithmetic intensity (ops performed per byte transferred from memory). Consider the roofline plot below. Please plot the roofline curve for a machine featuring a 1 GHz dual-core processor. Each core can execute one 4-wide SIMD instruction per clock. This processor is connected to a memory system providing 4 GB/sec of bandwidth. **Hint: what is the peak throughput of this processor? What are its bandwidth requirements when running a piece of code with a specified arithmetic intensity?** Plot the expected throughput of the processor when running code at each arithmetic intensity on the X axis, and draw a line between the points. Problem 2: Data-Parallel Thinking (35 pts) Assume you are given a library that can execute a bulk launch of $N$ independent invocations of an application-provided function using the following CUDA-like syntax: ``` my_function<<<N>>>(arg1, arg2, arg3...); ``` For example the following code would output: (id is a built-in id for the current function invocation) ``` void foo(int* x) { printf("Instance %d : %d\n", id, x[id]); } int A[] = {10,20,30} foo<<<3>>>(A); "Instance 0 : 10" "Instance 1 : 20" "Instance 2 : 30" ``` The library also provides the data-parallel function `exclusive_scan` (using the + operator) that works as discussed in class. ``` exclusive_scan(N, in, out); ``` Example usage: ``` N = 6 in = \{1, 2, 3, 4, 5, 6\} ===================================== out = \{0, 1, 3, 6, 10, 15\} ``` In this problem, we'd like you to design a data-parallel implementation of `largest_segment_size()`, which, given an array of flags that denotes a partitioning of an array into segments, computes the size of the longest segment in the array. ``` int largest_segment_size(int N, int* flags); ``` The function takes as input an array of $N$ flags (flags) (with 1’s denoting the start of segments), and returns the size of the largest segment. The first element of flags will always be 1. For example, the following flags array describes five segments of lengths 4, 2, 2, 1, and 1. ``` N = 10 flags = \{1, 0, 0, 0, 1, 0, 1, 0, 1, 1\} ===================================== result: = 4 ``` Questions on next page... A. (20 pts) The first step in your implementation should be to compute the size of each segment. Please use the provided library functions (bulk launch of a function of your choice + exclusive_scan) to implement the function segment_sizes() below. // Example output of segment_sizes(N, flags, num_segs, sizes): // N = 8 // flags = {1, 0, 1, 0, 0, 0, 1, 0} // num_segs = 3 // sizes = {2, 4, 2} // You may wish to define functions used in bulk launches here // You can allocate any required intermediate arrays in this function // You may assume that 'seg_sizes' is pre-allocated to hold N elements, // which is enough storage for the worse case where the flags array // is all 1's. void segment_sizes(int N, int* flags, int* num_segs, int* seg_sizes) { } B. (15 pts) Now implement `largest_segment_size()` using `segment_sizes()` as a subroutine. **NOTE:** this problem can be answered even without a valid answer to Part A. Your implementation may assume that the number of segments described by `flags` is always a power of two. A full credit implementation will maximize parallelism and minimize work when computing the maximum segment size from an array of segment sizes. *Hint: we are looking for solutions with \( \lg(\text{num}_\text{segs}) \) span.* // you may want to implement helper functions here that are called via bulk launch ```c int largest_segment_size(int N, int* flags) { int num_segs; int seg_sizes[N]; segment_sizes(N, flags, &num_segs, seg_sizes); } ``` Problem 3: Implementing CS149 Spark (40 pts) In this problem we want you to implement a very simple version of Spark, called CS149Spark, that supports only a few operators. You will implement CS149Spark as a simple C++ library consisting of a base class RDD as well as subclasses for all CS149Spark transforms. ```cpp class RDD { public: virtual bool hasMoreElements() = 0; // all RDDs must implement this virtual string next() = 0; // all RDDs must implement this int count() { // returns number of elements in the RDD int count = 0; while (hasMoreElements()) { string el = next(); count++; } return count; } vector<string> collect() { // returns STL vector representing RDD vector<string> data; while (hasMoreElements()) { data.append(next()); } return data; } }; class RDDFromTextFile : public RDD { ifstream inputFile; // regular C++ file IO object public: RDDFromTextFile(string filename) { inputFile.open(filename); // prepares file for reading } bool hasMoreElements() { return !inputFile.eof(); // .eof() returns true if no more data to read } string next() { return inputFile.readLine(); // reads next line from file } }; For example, given the two definitions above, a simple program that counts the lines in a text file can be written as such. ``` A. (10 pts) Now consider adding a l33tify RDD transform to CS149Spark, which returns a new RDD where all instances of the character 'e' in string elements of the source RDD are converted to the character '3'. For example, the following code sequence creates an RDD (r1) whose elements are lines from a text file. The RDD r2 contains a l33tified version of these strings. This data is collected into a regular C++ vector at the end of the program using the call to collect(). ```cpp RDDFromTextFile r1("myfile.txt"); // creates an RDD where each element is a string // corresponding to a line from the text file RDDL33tify r2(r1); // l33tify all elements for r1 vector<string> lines = r2.collect(); // lines from the file, but in l33t form ``` Implement the functions hasMoreElements() and next() for the l33tify RDD transformation below. A full credit solution will use minimal memory footprint and never recompute (compute more than once) any elements of any RDD. ``` class RDDL33tify : public RDD { RDD parent; RDDL33tify(RDD parentRDD) { parent = parentRDD; } bool hasMoreElements() { } string next() { } }; ``` B. (10 pts) Now consider a transformation \texttt{FilterLongWords} that filters out all elements of the input RDD that are strings of greater than 32 characters. Again, we want you to implement \texttt{hasMoreElements()} and \texttt{next()}. You may declare any member variables you wish and assume \texttt{.length()} exists on strings. Careful: \texttt{hasMoreElements()} is trickier now! Again a full credit solution will use minimal memory footprint and never recompute any elements of any RDD. A sample program using the \texttt{FilterLongWords} RDD transformation is below: ```cpp RDDFromTextFile r1("myfile.txt’’); // creates an RDD where each element is a string corresponding to a line from the text file RDDL33tify r2(r1); // converts elements to l33t form RDDFilterLongWords r3(r2); // removes strings that are greater than 32 characters print("RDD r3 has length %d\n", r3.count()); ``` ```cpp class RDDFilterLongWords : public RDD { RDD parent; public: RDDFilterLongWords(RDD parentRDD) { parent = parentRDD; } bool hasMoreElements() { // implementation } string next() { // implementation } }; ``` C. (10 pts) Finally, implement a `groupByFirstWord` transformation which is like Spark’s `groupByKey`, but instead (1) it uses the first word of the input string as a key, and (2) instead of building a list of all elements with the same key, concatenates all strings with the same key into a long string. For example, `groupByFirstWord` on the RDD ['hello world”, ”hello cs149”, ”good luck”, ”parallelism is fun”, ”good afternoon”] would produce the RDD ['hello world hello cs149”, ”good luck good afternoon”, ”parallelism is fun”]. Your implementation can be rough pseudocode, and may assume the existence of a dictionary data structure (mapping strings to strings) to actually perform the grouping, an iterator over the dictionaries keys, and useful string functions like: `.first()` to get the first word of a string, and `.append(string)` to append one string to another. Rough pseudocode is fine, but your solution should make it clear how you are tracking the next element to return in `next()`. A full credit solution will use minimal memory footprint and never recompute any elements of any RDD. ```cpp class RDDGroupByFirstWord : public RDD { RDD parent; Dictionary<string, string> dict; // assume dict[“hello’’] returns the string // associated with key “hello’’ public: RDDGroupByFirstWord(RDD parentRDD) { parent = parentRDD; } bool hasMoreElements() { // Your implementation here } string next() { // Your implementation here } }; ``` D. (5 pts) Describe why the RDD transformations `L33tify`, `FilterLongWords`, and RDD construction from a file, as well as the action `count()` can all execute efficiently on very large files (consider TB-sized files) on a machine with a small amount of memory (1 GB of RAM). E. (5 pts) Describe why the transformation `GroupByFirstWord` differs from the other transformations in terms of how much memory footprint it requires to implement. The following problems are PRACTICE PROBLEMS and will not be graded. Practice Problem 1: Bringing Locality Back Justin Timberlake and Kanye West hear that Spark is all the rage and decide they are going to code up their own implementation to compete against that of the Apache project. Justin’s first test runs the following Spark program, which creates four RDDs. The program takes Justin’s lengthy (1 TB!) list of dancing tips and finds all misspelled words. ```scala var lines = spark.textFile("hdfs://mydancetips.txt"); // 1 TB file var lower = lines.map(x => x.toLowerCase()); // convert lines to lower case var words = lower.flatMap(x => x.split(" ")); // convert RDD of lines to RDD of individual words var misspelled = words.filter(x => !x.isInDictionary()); // filter to find misspellings print misspelled.count(); // print number of misspelled words ``` A. Understanding that the Spark RDD abstraction affords many possible implementations, Justin decides to keep things simple and implements his Spark runtime such that each RDD is implemented by a fully allocated array. This array is stored either in memory or on disk depending on the size of the RDD and available RAM. **The array is allocated and populated at the time the RDD is created — as a result of executing the appropriate operator (map, flatmap, filter, etc.) on the input RDD.** Justin runs his program on a cluster with 10 computers, each of which has 100 GB of memory. The program gets correct results, but Justin is devastated because the program runs incredibly slow. He calls his friend Taylor Swift, ready to give up on the venture. Encouragingly, Taylor says, “shake it off Justin”, just run your code on 40 computers. Justin does this and observes a speedup much greater than 4\times his original performance. Why is this the case? B. With things looking good, Kanye runs off to write a new single “All of the Nodes” to use in the marketing for their product. At that moment, Taylor calls back, and says “Actually, Justin, I think you can schedule the computations much more efficiently and get very good performance with less memory and far fewer nodes.” Describe how you would change how Justin schedules his Spark computations to improve memory efficiency and performance. C. After hacking all night, the next day, Justin, Kanye, and Taylor run the optimized program on 10 nodes. The program runs for 1 hour, and then right before `misspelled.count()` returns, node 6 crashes. Kanye is irate! He runs onto the machine room floor, pushing Taylor aside and says, “Taylor, I have a single to release, and I don’t have time to deal with rerunning your programs from scratch. Geez, I already made you famous.” Taylor gives Kayne a stink eye and says, “Don’t worry, it will be complete in just a few minutes.” Approximately how long will it take after the crash for the program to complete? You should assume the `.count()` operation is essentially free. But please clearly state any assumptions about how the computation is scheduled in justifying your answer. Practice Problem 2: Implementing a Barrier In class we talked about the `barrier()` synchronization primitive. No thread proceeds past a barrier until all threads in the system have reached the barrier. (In other words, the call to `barrier()` will not return to the caller until its known that all threads have called `barrier()`). Consider implementing a barrier in the context of a message passing program that is only allowed to communicate via blocking sends and receives. Using only the helper functions defined below, implement a barrier. Your solution should make no assumptions about the number of threads in the system. **Keep in mind that all threads in a message passing program execute in their own address space—there are no shared variables.** ```c // send msg with id msgId and contents msgValue to thread dstThread void blockingSend(int dstThread, int msgId, int value); // recv message from srcThread. Upon return, msgId and msgValue are populated void blockingRecv(int srcThread, int* msgId, int* msgValue); // returns the id of the calling thread int getThreadId(); // returns the number of threads in the program int getNumThreads(); ``` Practice Problem 3: Data Parallel Graphs Consider a representation for a directed graph much like the one we used your programming assignment. A graph of N vertices is represented by an array of per-vertex values and an array of incoming_edges which lists the vertex id of all incoming edges, and incoming_starts, which denotes the start and end position of vertex i’s incoming edge (in the array incoming_edges). In other words, the j’th incoming edge to vertex i is given by: incoming_edges[incoming_starts[i] + j]. C code for this definition is here. Followed by an example to refresh your memory: ```c struct Graph { int N; float* values[N]; // per vertex values int* incoming_edges[NUM_EDGES]; int* incoming_starts[N+1]; // this is a length N+1 array, the last element // is always equal to the total number of edges }; ``` Example, the graph defined below: ```c N = 4; incoming_edges = {1, 2, 0, 3, 3, 0, 1, 2}; // 8 edges incoming_starts = {0, 1, 4, 6, 8}; ``` Has edges: (0,1) (1,2), (1,0), (1,3) (2,3), (2,0) (3,1), (3,2) (Question continues on next page...) Assume you are given a library of data parallel functions on arrays. We’ve provided pseudocode below so it is clear what operations these functions perform. However, please make no assumption about their actual implementation. (they could be parallelized, etc.) We are using $T$ as a generic type in the code below, assume it can be floats or ints. ```c void init(int n, T val, T* out) { // initialize all array elements to val for (int i=0; i<n; i++) out[i] = val; } void gather(int n, T* in, int* index, T* out) { // gather from in into out for (int i=0; i<n; i++) out[i] = in[index[i]]; } void scatter(int n, T* in, int* index, T* out) { // scatter from in to out out[index[i]] = in[i]; } void subtract(int n, T* in1, T* in2, T* out) { // elementwise subtract in2 from in1 for (int i=0; i<n; i++) out[i] = in1[i] - in2[i]; } void compare(int n, T* in, T val, int* out) { // compare elements of in to value for (int i=0; i<n; i++) out[i] = (in[i] > val) ? 1 : 0; } void shift_left(int n, T* in, T* out) { // note: in is of size n, out of size n-1 for (int i=0; i<n-1; i++) out[i] = in[i+1]; } void segmented_prefixsum(int n, T* in, int* segments, T* out) { // This is an inclusive segmented scan involving an add operator, but it // is performed per segment. 'segments' has the value 1 at the start // of all segments // Example: // if: in = {1,2,3,4,5,6,7,8}, and segments = {1,0,0,1,0,1,0,0} // then out = {1,3,6, 4,9, 6,13,21} } ``` (Question continues on next page...) A. Given the library functions on the previous page, implement an algorithm that computes an array \texttt{big\_change\_mask}, where \texttt{big\_change\_mask[i]}=1 only if vertex \texttt{i}'s value (\texttt{g.values[i]}) is \texttt{THRESHOLD} units greater than \textbf{the sum the values of the vertices that have edges pointing to it} (and 0 otherwise.) Be precise with your pseudocode, but we will not be picky about potential edge cases for the last vertex. ```c Graph g; // assume graph is initialized. // Number of vertices is N, number of edges is NUM_EDGES // your solution should write 0's and 1's to this array // you may allocate any temporal arrays as necessary int* big_change_mask = alloc(int, N); // // Hint: build segments array // int* ones = alloc(int, N); int* segments = alloc(int, NUM_EDGES); init(N, 1, ones); // // Hint: gather vertices and perform per-vertex sums // ``` B. (THIS QUESTION CAN BE ANSWERED INDEPENDENTLY OF A CORRECT SOLUTION TO PART A.) Now consider a version of the library that uses various techniques discussed in class to compress key data structures in the problem, such as the list of incoming edges, and boolean masks. Give one reason why using compressed in-memory data structures might be a bad idea if the code was to be run on a single thread of a large 64-core machine. Give one reason why compressing data structures might be a good idea if the code was run on all 64-cores of the machine.
{"Source-Url": "http://cs149.stanford.edu/fall20content/static/pdfs/written_asst3.pdf", "len_cl100k_base": 4923, "olmocr-version": "0.1.50", "pdf-total-pages": 19, "total-fallback-pages": 0, "total-input-tokens": 30615, "total-output-tokens": 5893, "length": "2e12", "weborganizer": {"__label__adult": 0.00043320655822753906, "__label__art_design": 0.0002689361572265625, "__label__crime_law": 0.0003790855407714844, "__label__education_jobs": 0.0018339157104492188, "__label__entertainment": 7.009506225585938e-05, "__label__fashion_beauty": 0.0001480579376220703, "__label__finance_business": 0.00013530254364013672, "__label__food_dining": 0.0005269050598144531, "__label__games": 0.0007333755493164062, "__label__hardware": 0.0016469955444335938, "__label__health": 0.00043654441833496094, "__label__history": 0.000240325927734375, "__label__home_hobbies": 0.0001323223114013672, "__label__industrial": 0.00049591064453125, "__label__literature": 0.0002658367156982422, "__label__politics": 0.0002627372741699219, "__label__religion": 0.0005540847778320312, "__label__science_tech": 0.00777435302734375, "__label__social_life": 0.0001302957534790039, "__label__software": 0.0029659271240234375, "__label__software_dev": 0.97900390625, "__label__sports_fitness": 0.0003609657287597656, "__label__transportation": 0.0007839202880859375, "__label__travel": 0.00022220611572265625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 19617, 0.02511]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 19617, 0.64895]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 19617, 0.80461]], "google_gemma-3-12b-it_contains_pii": [[0, 828, false], [828, 1619, null], [1619, 2426, null], [2426, 3974, null], [3974, 4732, null], [4732, 5468, null], [5468, 6912, null], [6912, 8037, null], [8037, 9210, null], [9210, 10765, null], [10765, 11207, null], [11207, 11276, null], [11276, 13027, null], [13027, 14255, null], [14255, 15419, null], [15419, 16562, null], [16562, 18133, null], [18133, 19070, null], [19070, 19617, null]], "google_gemma-3-12b-it_is_public_document": [[0, 828, true], [828, 1619, null], [1619, 2426, null], [2426, 3974, null], [3974, 4732, null], [4732, 5468, null], [5468, 6912, null], [6912, 8037, null], [8037, 9210, null], [9210, 10765, null], [10765, 11207, null], [11207, 11276, null], [11276, 13027, null], [13027, 14255, null], [14255, 15419, null], [15419, 16562, null], [16562, 18133, null], [18133, 19070, null], [19070, 19617, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 19617, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 19617, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 19617, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 19617, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 19617, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 19617, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 19617, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 19617, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, true], [5000, 19617, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 19617, null]], "pdf_page_numbers": [[0, 828, 1], [828, 1619, 2], [1619, 2426, 3], [2426, 3974, 4], [3974, 4732, 5], [4732, 5468, 6], [5468, 6912, 7], [6912, 8037, 8], [8037, 9210, 9], [9210, 10765, 10], [10765, 11207, 11], [11207, 11276, 12], [11276, 13027, 13], [13027, 14255, 14], [14255, 15419, 15], [15419, 16562, 16], [16562, 18133, 17], [18133, 19070, 18], [19070, 19617, 19]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 19617, 0.0]]}
olmocr_science_pdfs
2024-12-03
2024-12-03
6687a557aded4ed34dfd031c3a0fcb7ece7e23b9
A Correspondence between GNN pseudocode and the polynomial span In Figure 2 we further elaborate on the diagrams given in Figure 1 to explicitly relate the various steps of how processing data with a GNN might proceed with the individual arrows (i, p, o) of the polynomial span. To do this, we colour-code parts of a plausible GNN pseudocode, to match the colours of arrows in a polynomial span diagram. Additionally, in Figure 3 we follow this construction to explicitly provide the pseudocodes for the proposed $V^2$ and $V^3$-GNN models (as proposed in Diagram 7 and Diagram 10, respectively). B The bag and list monads Before we conclude, we turn back to the theory behind our polynomial spans, to more precisely determine the restrictions on our abstract latent space $R$. We found this investigation useful to include in the main paper, as it yields a strong connection to one of the most actively used concepts in theoretical computer science and functional programming. Recall that the realisation of our pushforward operations required the existence of two aggregators: $\otimes$ (to fold lists) and $\bigoplus$ (to reduce bags). Previously, we mentioned only in passing how they can be recovered—now, we proceed to define $\bigoplus$ axiomatically. Given a set $S$, we define $\text{bag}(S) := \{ p : S \to N \mid \# \{ p(r) \neq 0 \} < \infty \}$, the natural-valued functions of finite support on $S$. This has a clear correspondence to multisets over $S$: $p$ sends each element of $S$ to the amount of times it appears in the multiset. We can write its elements formally as $\sum_{s \in S} n_s s$, where all but finitely many of the $n_s$ are nonzero. Given a function $f : S \to T$ between sets, we can define a function $\text{bag}(f) : \text{bag}(S) \to \text{bag}(T)$, as follows: $\text{bag}(f)(\sum_{s \in S} n_s s) := \sum_{s \in S} n_s f(s)$, which we can write as $\sum_{t \in T} m_t t$, where $m_t = \sum_{f(s) = t} n_s$. For each $S$, we can also define two special functions. The first is $\text{unit} : S \to \text{bag}(S)$, sending each element to its indicator function (i.e. an element $x \in S$ to the multiset $\{x\}$). The second is $\text{join} : \text{bag}(\text{bag}(S)) \to \text{bag}(S)$, which interprets a nested sum as a single sum. These facts tell us that $\text{bag}$ is a monad, a special kind of self-transformation of the category of sets. Monads are very general tools for computation, used heavily in functional programming languages (e.g. Haskell) to model the semantics of wrapped or enriched types. Monads provide a clean way for abstracting control flow, as well as gracefully handling functions with side effects [33]. It is well-known that the algebras for the monad $\text{bag}$ are the commutative monoids, sets equipped with a commutative and associative binary operation and a unit element. Require: Node features $X \in \mathbb{R}^{n \times k}$ Message function $\psi: \mathbb{R}^k \times \mathbb{R}^k \to \mathbb{R}^m$, Update function $\phi: \mathbb{R}^m \to \mathbb{R}^m$ Ensure: Latent features $H \in \mathbb{R}^{n \times m}$ (nodes), $M \in \mathbb{R}^{n \times n \times m}$ (edges) $\text{Arg}_\text{end} \leftarrow \text{tile}[X, 0, n]$; // $\text{Arg}_\text{end} \in \mathbb{R}^{n \times n \times k}$ $\text{Arg}_\text{trans} \leftarrow \text{tile}[X, 1, n]$; // $\text{Arg}_\text{trans} \in \mathbb{R}^{n \times n \times k}$ for $(u, v) \in V \times V$ do $\text{msg}_{uv} \leftarrow \psi(\text{arg}_\text{end}, \text{arg}_\text{trans})$; // $\text{Msg} \in \mathbb{R}^{n \times n \times m}$ end for for $u \in V$ do $h_u \leftarrow \phi(\bigoplus_{v \in V} \text{msg}_{uv})$; end for $M \leftarrow \text{Msg}$ // $\text{Msg}$ is sent to two places $(H, M)$; output morphism $o$ is not a function! Figure 3: Correspondence between the arrows in the polynomial span, and the pseudocode for implementing the GNNs represented by Diagram 7 (above) and Diagram 10 (below). Edge and graph features are ignored for simplicity. The code sections are colour-coded to correspond to arrows in the polynomial span. Note the difference to Figure 2; we now also need to output edge features (on $V^2$). Concretely, a commutative monoid structure on a set $R$ is equivalent to defining an aggregator function $\bigoplus: \text{bag}(R) \to R$ compatible with the unit and monad composition. Here, compatibility implies it should correctly handle sums of singletons and sums of sums, in the sense that the following two diagrams commute; that is, they yield the same result regardless of which path is taken: ``` \[ \begin{array}{c} R \xrightarrow{\text{id}} \text{bag}(R) \\ \bigoplus \downarrow \quad \bigoplus \downarrow \\ \text{bag}(R) \xrightarrow{\text{join}} R \end{array} \] \[ \begin{array}{c} \text{bag}(\text{bag}(R)) \xrightarrow{\text{join}} \text{bag}(\bigoplus) \xrightarrow{\bigoplus} \text{bag}(R) \end{array} \] ``` The first diagram explains that the outcome of aggregating a singleton multiset (i.e. the one produced by applying unit) with $\bigoplus$ is equivalent to the original value placed in the singleton. The second diagram indicates that the $\bigoplus$ operator yields the same results over a nested multiset, regardless of whether we choose to directly apply it twice (once on each level of nesting), or first perform the join function to collapse the nested multiset, then aggregate the collapsed multiset with $\bigoplus$. 15 So the structure of a commutative monoid on \( R \) is exactly what we need to complete our definition of the message pushforward \( o_B \). The story for the argument pushforward, \( p_B \), is remarkably similar. Define \( \text{list}(S) := \{(s_1, \ldots, s_n) \mid n \in \mathbb{N}, s_i \in S\} \), the set of all ordered lists of elements of \( S \), including the empty list. Equivalently, \( \text{list}(S) = \coprod_{n \geq 0} S^n \). We can also extend \( \text{list} \) to a functor: \[ \text{list}(f)(s_1, \ldots, s_n) := (f(s_1), \ldots, f(s_n)). \] \( \text{list} \) is also a monad, with \( \text{unit} : S \to \text{list}(S) \) sending each \( x \in S \) to the singleton list \( (x) \), and \( \text{join} : \text{list}(\text{list}(S)) \to \text{list}(S) \) sending a list of lists to their concatenation. The algebras for the list monads are \textit{monoids}—not just commutative ones. So \( R \) needs a second monoid structure, possibly noncommutative, to support our definition of the argument pushforward. We detail how this can elegantly be done in our specific case in Appendix C. ### C The monad for semirings We have asked that \( R \) be an algebra for two monads: \( \text{list} \) and \( \text{bag} \). But this is an unnatural condition without some compatibility between the two. It would more useful to find a single monad encapsulating both. In general, the composition of two monads is not a monad. For example, the composite functor \( \text{list} \circ \text{bag} \) does not support a monad structure. However, the other composite \( \text{bag} \circ \text{list} \) is actually a monad in a natural way, due to the existence of a \textit{distributive law}, which is a natural transformation \( \lambda : \text{list} \circ \text{bag} \to \text{bag} \circ \text{list} \) satisfying some axioms, see e.g. [8]. It is easy to describe \( \lambda \). Given any list of bags \( \left( \sum_{i_1} a_{i_1}, \ldots, \sum_{i_n} a_{i_n} \right) \), we have \[ \lambda\left(\sum_{i_1} a_{i_1}, \ldots, \sum_{i_n} a_{i_n}\right) = \sum_{i_1, \ldots, i_n} (a_{i_1}, \ldots, a_{i_n}). \] This is exactly how multiplication of sums works in a semiring. For example, if \( p \) think of a polynomial \[ \text{polynomial functor starts with a polynomial span:} \] \[ \begin{array}{ccc} X & \xrightarrow{p} & Y \\ \downarrow & & \downarrow \\ W & \xrightarrow{o} & Z \end{array} \] \[\] And it produces a composition of three functors: \[ \begin{array}{ccc} C/X & \xrightarrow{\Pi_p} & C/Y \\ \uparrow i^* & & \downarrow \Sigma_o \\ C/W & \xrightarrow{s_z} & C/Z \end{array} \] Here \(\Sigma_0\) and \(\Pi_p\) are operations called the \textit{dependent sum} and \textit{dependent product} respectively. Note that there is a direct correspondence between the three arrows in each of the diagrams \(^5\) and \(^11\) So it is very tempting to ask whether our integral transform is expressible as a polynomial functor. Can our results be rephrased in those terms? We don’t have a complete answer, but we can connect the two pictures, at least in the case of commutative multiplication, via the monoidal category \(\text{FinPoly}\), whose objects are finite sets, whose morphisms are polynomial diagrams, and whose monoidal product is given by disjoint union \(+\). A result of Tambara says that \(\text{FinPoly}\) is the Lawvere theory for commutative semirings \(^{25}\) \(^{17}\). What this means is that the strong monoidal functors \(F : (\text{FinPoly}, +) \to (\text{Set}, \times)\) are uniquely determined by giving a commutative semiring structure on the set \(F(1)\). In other words, once we have decided on a commutative semiring structure on \(R = [1, R]\), we automatically have \(F(V) = F(\Sigma_V 1) = [1, R]^V = [V, R]\), and the action of \(F\) on morphisms can be checked to coincide with our construction of the integral transform. Likewise, we can interpret finite polynomial functors as the action on the category of categories \(F : (\text{FinPoly}, +) \to (\text{Cat}, \times)\) with \(F(1) = \text{FinSet}\). Note that \([V, \text{FinSet}] = \text{FinSet}^V = \text{FinSet}/V\), as picking one finite set for each element of \(V\) is equivalent to picking a finite set equipped with a function to \(V\). So \(F\) takes a finite set \(V\) to its slice category \(\text{FinSet}/V\), and likewise takes polynomial diagrams to the associated polynomial functor. In fact, \(F\) in this case actually extends to a 2-functor. Since the 2-categorical structure is important for polynomial functors, it may be useful to explore it for integral transforms as well. In any case, we can see that \([V, \mathbb{N}]\), where \(\mathbb{N}\) is the usual natural numbers with addition and multiplication, is just a decategorified version of \(\text{FinSet}/V\), obtained by considering only cardinalities. Indeed, the existence of such a “decategorification” for transforms over spans was an early inspiration for our present work. But what about categorifying other semirings? To replace \(\mathbb{N}\) with an arbitrary semiring \(R\), we would need to find a way to interpret a function \(f : W \to R\) as a classifying morphism for some kind of bundle \(E \to W\) in a suitable category of geometric objects over \(R\). For the min-plus semiring \(R = \mathbb{N}^\infty\), one possibility is to define a category of \(R\)-schemes, which should be certain types of topological spaces equipped with sheaves of \(R\)-modules. We don’t know of a place this theory is fully developed, but the spectrum functor from rings to topological spaces is extended to poset-enriched semirings in \(^{12}\). And this construction is certainly related to tropical schemes, defined in \(^{13}\). For \(R = \mathbb{R}\), we can also consider the more familiar category of manifolds, or more generally the category of locally compact Hausdorff spaces. But do polynomial functors work in categories like this? While polynomial functors were developed in type theory over locally cartesian closed categories—too strong of a condition for interesting topology to occur—\(^{34}\) has shown that polynomial functors can be defined in any category with pullbacks, as long as the “processor” morphism \(p : X \to Y\) satisfies an abstract condition called \textit{exponentiability}. \(i\) and \(o\) can still be arbitrary morphisms. For some intuition, we quote two results on exponentiability. \(^{6}\) shows that the exponentiable morphisms in the category of compact Hausdorff spaces are the local homeomorphisms. And \(^{22}\) shows that a morphism \(R \to S\) of commutative rings gives rise to an exponentiable morphism of affine schemes exactly when \(S\) is dualizable as an \(R\)-module. So exponentiability seems to be strongly linked to covering spaces in classical topology, as well as descent theory in modern algebraic geometry. Expanding on these ideas is far out of scope for the present work, but we hope it gives a glimpse into the possibilities for future development. E Plots of in-distribution performance on CLRS For plots that illustrate in-distribution performance of our proposed $V^3$ model, against the non-polynomial ($V^2$) model, please refer to Figure 4 and Table 4. Our findings largely mirror the ones from out-of-distribution—with $V^3$ either matching the performance of the baseline or significantly outperforming it (e.g. on Insertion Sort and Floyd-Warshall). We do note that sometimes, matched performance by the non-polynomial $V^2$ baseline in-distribution can be misleading, as it significantly loses out to $V^3$ out of distribution (cf. Table 1). This lines up with predictions of prior art: in-distribution, many classes of GNNs can properly fit a target function [37], but in order to extrapolate well, the alignment to the target function needs to be stronger, as otherwise the function learnt by the model may be highly nonlinear, and therefore less robust out-of-distribution [38]. F Test results for the scaled PGN experiments on CLRS To supplement the aggregated results provided in Table 2, here we provide the per-task results of our scaled PGN experiment. Table 3 provides, for each of the 27 CLRS algorithms we investigated here, the test (out-of-distribution) performance of the PGN model [29], with both the $V^2$ and $V^3$ variant. In all cases, the models compute 96-dimensional embeddings; for memory considerations, the $V^2$ pipeline computes 128-dimensional latent vectors, the $V^3$ addition computes 16-dimensional latent vectors, and these are then all linearly projected to 96 dimensions and combined. We particularly highlight in Table 3 the edge-centric algorithms within this set, to emphasise our gains on them. An algorithm is considered edge-centric if it explicitly requires a prediction (either on the algorithm’s output or its intermediate state) over the given graph’s edges. Table 3: Test (out-of-distribution) results of all PGN variants on all 27 algorithms in our scaled up experiments, averaged over 8 seeds. Edge-centric algorithms are highlighted in blue. Note that most of the benefits of our proposed $V^3$ architecture occur over the edge-centric tasks. <table> <thead> <tr> <th>Algorithm</th> <th>$V^2$-PGN</th> <th>$V^3$-PGN</th> </tr> </thead> <tbody> <tr> <td>Activity Selector</td> <td>62.28% ± 1.02</td> <td>63.75% ± 1.03</td> </tr> <tr> <td>Articulation Points</td> <td>11.91% ± 4.46</td> <td>14.72% ± 3.69</td> </tr> <tr> <td>Bellman-Ford</td> <td>80.05% ± 0.87</td> <td>77.60% ± 0.78</td> </tr> <tr> <td>BFS</td> <td>99.97% ± 0.02</td> <td>99.76% ± 0.12</td> </tr> <tr> <td>Binary Search</td> <td>26.20% ± 2.07</td> <td>25.57% ± 1.95</td> </tr> <tr> <td>Bridges</td> <td>26.02% ± 1.68</td> <td>25.48% ± 1.54</td> </tr> <tr> <td>DAG Shortest Paths</td> <td>62.62% ± 0.44</td> <td>62.43% ± 0.82</td> </tr> <tr> <td>DFS</td> <td>8.70% ± 0.73</td> <td>8.16% ± 0.95</td> </tr> <tr> <td>Dijkstra</td> <td>34.60% ± 4.13</td> <td>37.51% ± 4.71</td> </tr> <tr> <td>Find Maximum Subarray</td> <td>48.28% ± 1.46</td> <td>52.58% ± 1.20</td> </tr> <tr> <td>Floyd-Warshall</td> <td>8.01% ± 1.31</td> <td>17.31% ± 0.92</td> </tr> <tr> <td>Graham Scan</td> <td>37.66% ± 1.77</td> <td>42.08% ± 1.57</td> </tr> <tr> <td>Heapsort</td> <td>2.34% ± 0.15</td> <td>4.20% ± 0.24</td> </tr> <tr> <td>Insertion Sort</td> <td>12.14% ± 0.24</td> <td>18.99% ± 0.98</td> </tr> <tr> <td>KMP Matcher</td> <td>2.44% ± 0.11</td> <td>1.59% ± 0.11</td> </tr> <tr> <td>LCS Length</td> <td>52.87% ± 2.35</td> <td>67.24% ± 4.93</td> </tr> <tr> <td>Matrix Chain Order</td> <td>70.94% ± 1.13</td> <td>74.61% ± 0.92</td> </tr> <tr> <td>Minimum</td> <td>58.92% ± 1.82</td> <td>56.54% ± 1.77</td> </tr> <tr> <td>MST-Kruskal</td> <td>43.34% ± 5.26</td> <td>38.42% ± 6.82</td> </tr> <tr> <td>MST-Prim</td> <td>29.05% ± 3.54</td> <td>29.86% ± 3.78</td> </tr> <tr> <td>Naive String Matcher</td> <td>2.06% ± 0.59</td> <td>1.80% ± 0.46</td> </tr> <tr> <td>Quickselect</td> <td>2.22% ± 0.08</td> <td>2.56% ± 0.16</td> </tr> <tr> <td>Quicksort</td> <td>2.45% ± 0.09</td> <td>6.82% ± 1.01</td> </tr> <tr> <td>Segments Intersect</td> <td>61.77% ± 2.15</td> <td>61.24% ± 1.99</td> </tr> <tr> <td>Strongly Connected Components</td> <td>8.98% ± 0.56</td> <td>11.41% ± 2.13</td> </tr> <tr> <td>Task Scheduling</td> <td>84.36% ± 1.30</td> <td>85.18% ± 0.63</td> </tr> <tr> <td>Topological Sort</td> <td>12.80% ± 0.56</td> <td>9.91% ± 1.63</td> </tr> <tr> <td>Overall average</td> <td>35.30%</td> <td>36.94%</td> </tr> </tbody> </table> Table 4: Validation (in-distribution) results of all MPNN-based models on all six algorithms studied, across three random seeds. <table> <thead> <tr> <th>Algorithm</th> <th>$V^2$–large</th> <th>$V^3$–large</th> <th>$V^2$–small</th> <th>$V^3$–small</th> </tr> </thead> <tbody> <tr> <td>Dijkstra</td> <td>92.03% ± 0.46</td> <td>92.70% ± 0.34</td> <td>91.46% ± 0.53</td> <td>91.54% ± 0.49</td> </tr> <tr> <td>Find Maximum Subarray</td> <td>81.98% ± 2.51</td> <td>84.71% ± 0.93</td> <td>81.91% ± 1.99</td> <td>76.29% ± 2.46</td> </tr> <tr> <td>Floyd-Warshall</td> <td>79.51% ± 0.59</td> <td>90.02% ± 0.32</td> <td>78.19% ± 0.67</td> <td>88.99% ± 0.47</td> </tr> <tr> <td>Insertion Sort</td> <td>87.48% ± 1.96</td> <td>87.97% ± 1.86</td> <td>76.12% ± 3.77</td> <td>88.84% ± 1.68</td> </tr> <tr> <td>Matrix Chain Order</td> <td>97.69% ± 0.07</td> <td>97.96% ± 0.06</td> <td>97.59% ± 0.10</td> <td>97.88% ± 0.10</td> </tr> <tr> <td>Optimal BST</td> <td>92.42% ± 0.24</td> <td>91.61% ± 0.28</td> <td>91.80% ± 0.46</td> <td>90.77% ± 0.63</td> </tr> <tr> <td>Overall average</td> <td>88.52%</td> <td>90.83%</td> <td>86.18%</td> <td>89.05%</td> </tr> </tbody> </table> Figure 4: Validation (in-distribution) curves of all models on all six algorithms studied, across three random seeds.
{"Source-Url": "https://proceedings.neurips.cc/paper_files/paper/2022/file/8248b1ded388fcdbbd121bcdfea3068c-Supplemental-Conference.pdf", "len_cl100k_base": 5781, "olmocr-version": "0.1.49", "pdf-total-pages": 7, "total-fallback-pages": 0, "total-input-tokens": 29023, "total-output-tokens": 6081, "length": "2e12", "weborganizer": {"__label__adult": 0.0004222393035888672, "__label__art_design": 0.0003838539123535156, "__label__crime_law": 0.0004532337188720703, "__label__education_jobs": 0.0004897117614746094, "__label__entertainment": 9.03010368347168e-05, "__label__fashion_beauty": 0.0002038478851318359, "__label__finance_business": 0.0002224445343017578, "__label__food_dining": 0.0004968643188476562, "__label__games": 0.0006351470947265625, "__label__hardware": 0.0014019012451171875, "__label__health": 0.0006146430969238281, "__label__history": 0.00031375885009765625, "__label__home_hobbies": 0.00015604496002197266, "__label__industrial": 0.00070953369140625, "__label__literature": 0.00034809112548828125, "__label__politics": 0.0003292560577392578, "__label__religion": 0.0006809234619140625, "__label__science_tech": 0.0745849609375, "__label__social_life": 0.00011479854583740234, "__label__software": 0.007129669189453125, "__label__software_dev": 0.90869140625, "__label__sports_fitness": 0.00038743019104003906, "__label__transportation": 0.0007610321044921875, "__label__travel": 0.00024628639221191406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 18089, 0.05847]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 18089, 0.20353]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 18089, 0.82138]], "google_gemma-3-12b-it_contains_pii": [[0, 2860, false], [2860, 5437, null], [5437, 7854, null], [7854, 12312, null], [12312, 14328, null], [14328, 17972, null], [17972, 18089, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2860, true], [2860, 5437, null], [5437, 7854, null], [7854, 12312, null], [12312, 14328, null], [14328, 17972, null], [17972, 18089, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 18089, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 18089, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 18089, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 18089, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 18089, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 18089, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 18089, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 18089, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 18089, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 18089, null]], "pdf_page_numbers": [[0, 2860, 1], [2860, 5437, 2], [5437, 7854, 3], [7854, 12312, 4], [12312, 14328, 5], [14328, 17972, 6], [17972, 18089, 7]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 18089, 0.27857]]}
olmocr_science_pdfs
2024-11-25
2024-11-25
5aca6ef899bac3a540703784ad001eadad8e1ec6
State of DNS Rebinding Attack & Prevention Techniques and the Singularity of Origin Gérald Doussot & Roger Meyer | DEF CON 27 Contributions New Tool: Singularity - Everything you need for DNS rebinding - **Reliable**: Default settings just work - **Performant**: up to 20x faster (3s vs 60s) - **Built-in payloads**: Jenkins, Rails, AWS Instance Metadata, etc... - **Autopwn**: Networks & services scan, service detection and auto-exploitation Neat Technical Details/Techniques - **Speed**: Multiple DNS answers and cache flooding - **Protection Bypasses**: 3 different bypasses for common DNS rebinding protections - Using DNS trickery - **Hook/Control** - Interactively browse the victim’s internal network - Websocket proxying, no HTTP proxy needed! Agenda ● A Refresher on DNS Rebinding ● DNS Rebinding Attack: Building on reliable foundations ● **The Need for Speed**: DNS rebinding in 3 seconds ● **Protection Bypasses**: 3 different bypasses for common DNS rebinding protections ● **Hook and Control**: Interactively browse the victim’s internal network ● Scanning for Vulnerable Host Services ● **Automation**: Service detection & exploitation and orchestrating all the above Introduction Who Are We - Gérald Doussot and Roger Meyer - Security consultants at nccgroup - San Francisco, CA - Authors of Singularity of Origin, a DNS Rebinding Attack Framework https://github.com/nccgroup/singularity Why Should You Care About DNS Rebinding bind 0.0.0.0 Why Should You Care About DNS Rebinding bind 127.0.0.1 Why Should You Care About DNS Rebinding The call is coming from inside the house — DNS rebinding in EOSIO keosd wallet Why Should You Care About DNS Rebinding Attacking Private Networks from the Internet with DNS Rebinding Brannon Dorsey Follow Jun 19, 2018 · 20 min read TL;DR Following the wrong link could allow remote attackers to control your WiFi router, Google Home, Roku, Sonos speakers, home thermostats and more. Why Should You Care About DNS Rebinding Just another hacking blog Home About Contact How your ethereum can be stolen through DNS rebinding 19 Jan 2018 With the new buzz around exploiting unauthenticated JSON-RPC services on localhost ignited by Tavis Ormandy, the first thing that came to my mind was ethereum clients (Geth, Mist and Parity). Most of the ethereum clients run a JSON-RPC service on port 8545 on localhost, but since it's on localhost, we can't access it directly from user's browser due to SOP. This issue in the electrum wallet exploited the CORS headers to take control over the user's electrum wallet through JSON-RPC on localhost. How to steal any developer's local database Aug 2016 If you’re reading this and you’re a software developer, you’re probably running some services locally. Redis, Memcached, and Elasticsearch are software products that many rely on. What you might not know, is that these locally running services are accessible by any website you visit, making it possible for bad guys to steal the data you have locally! Why Should You Care About DNS Rebinding MWR LABS + Advisories /var/log/messages Publications Tools Careers Minikube RCE & VM Escape The Kubernetes dashboard service on Minikube is vulnerable to DNS rebinding attacks that can lead to remote code execution on the host. <table> <thead> <tr> <th>Product</th> <th>Minikube</th> </tr> </thead> <tbody> <tr> <td>Severity</td> <td>High</td> </tr> <tr> <td>CVE Reference</td> <td>CVE-2018-1062163</td> </tr> <tr> <td>Type</td> <td>Remote Code Execution</td> </tr> </tbody> </table> Why Should You Care About DNS Rebinding Rails Webconsole DNS Rebinding The webconsole gem which ships with the Rails development server allows remote code execution via DNS Rebinding. I reported this issue to Rails on April 20th 2015. However, it may have been reported to them earlier because Homakov also found the issue independently and tweeted about it here: Why Should You Care About DNS Rebinding - Prevalence of apps exposing **HTTP servers on localhost** (e.g. Electron) - **IoT devices** exposing sensitive interfaces on internal networks - **Misconceptions** - DNS rebinding is slow - DNS rebinding can be solved by out-of-the-box DNS filtering products or services A Refresher on DNS Rebinding On the Origin of Web Documents The “Origin” of a resource is a tuple consisting of scheme, host and port. Two documents A and B share the “same-origin” if they have identical scheme, host and port components. On the Origin of Web Documents The “same-origin policy” dictates how two different origins may interact. These interactions between origins are typically permitted: form submissions, links, redirects, content embedding (JavaScript, CSS). Cross-origin reads are typically not allowed e.g. reading the content of an HTML document located on gmail.com from site attacker.com. DNS Rebinding permits to bypass restrictions imposed by the same-origin policy. DNS Rebinding Attack Walkthrough - **Victim (Browser)** - **Target Service 127.0.0.1** - **Attacker DNS & Web Server 35.185.206.165** DNS Rebinding Attack Walkthrough Victim (Browser) -> Target Service 127.0.0.1 Unauthenticated access Intranet | Internet Attacker DNS & Web Server 35.185.206.165 Target Service 127.0.0.1 DNS Rebinding Attack Walkthrough - **Victim (Browser)** - **Target Service 127.0.0.1** - **Unauthenticated access** - **Intranet** - **Internet** - **Blocked** - **Attacker DNS & Web Server 35.185.206.165** DNS Rebinding Attack Walkthrough Victim (Browser) → DNS query `rebind.it` → Attacker DNS & Web Server 35.185.206.165 Target Service 127.0.0.1 DNS Rebinding Attack Walkthrough Victim (Browser) → DNS query `rebind.it` → DNS A record response: `35.185.206.165` → Attacker DNS & Web Server: `35.185.206.165` Target Service: `127.0.0.1` DNS Rebinding Attack Walkthrough - Victim (Browser) queries "rebind.it". - Attacker DNS & Web Server respond with "35.185.206.165". - Victim (Browser) queries "rebind.it" again. - DNS cache expires; Victim (Browser) queries "rebind.it" again. - Attacker DNS & Web Server respond with "35.185.206.165". - Target Service (127.0.0.1) is accessed by the Victim (Browser). DNS Rebinding Attack Walkthrough Victim (Browser) -> DNS query `rebind.it` DNS A record response: `35.185.206.165` DNS cache expires; DNS query `rebind.it` DNS A record response: `127.0.0.1` Target Service `127.0.0.1` -> Attacker DNS & Web Server `35.185.206.165` DNS Rebinding Attack Walkthrough Victim (Browser) GET/POST request to 127.0.0.1 Target Service 127.0.0.1 DNS query `rebind.it` DNS A record response: 35.185.206.165 DNS cache expires; DNS query `rebind.it` DNS A record response: 127.0.0.1 Attacker DNS & Web Server 35.185.206.165 Target Service 127.0.0.1 GET/POST request to 127.0.0.1 Learning More About the Basics of DNS Rebinding - [2007] Stanford University - Protecting Browsers from DNS Rebinding Attacks (https://crypto.stanford.edu/dns/) iOS Demo: DNS rebinding in 5 s (cache flooding) DNS Rebinding Attack: Building on Reliable Foundations You Visit a Completely Innocuous Looking Website Adventures in Equestrianism THOROUGHBRED HORSE RACING | STEEPLECHASING | AMERICAN QUARTER HORSE | ENDURANCE RIDING | RIDE AND TIE Planning Your Next Horse Riding Holidays Nunc facilisis elit ex, at tristique erat commodo id. Aliquam vel magna velit. Duis convallis quis ipsum id viverra. Duis magna nulla, hendrerit nec nisi quis, ornare varius metus. Ut nunc nunc, tristique at scelerisque non, consectetur non mi. Proin sapien dolor, commodo at arcu id, porttitor congue nulla. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vivamus pellentesque eleifend arcu, sit amet porta erat pulvinar vitae. Quisque laoreet blandit A Singularity of Origin Production | 2019 Malicious JavaScript Code Downloaded. Sending First DNS Query… What’s in a Query? Example DNS query from a browser to Singularity DNS server: `s-35.185.206.165-127.0.0.1-3504134790-fs-e.d.rebind.it` - **(s)**tart - **35.185.206.165**: Attacker Host IP Address - **127.0.0.1**: Target Service IP Address or Name - **3504134790**: Session ID - **fs**: DNS Rebinding Strategy - “first then second” IP address. - **(e)**nd - **d.rebind.it**: Attack Host Domain Removing HTTP Performance Enhancing Techniques That Impede DNS Rebinding HTTP Caching - We want the browser to get fresh copies of resources. ```go func (d *DefaultHeadersHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1 w.Header().Set("Pragma", "no-cache") // HTTP 1.0 w.Header().Set("Expires", "0") // Proxies w.Header().Set("X-DNS-Prefetch-Control", "off") // Chrome } ``` Keep-Alive - We don’t want the browser to stick to the attacker’s server. ``` // drop browser connections after delivering // so they dont keep socket alive and facilitate rebinding. httpServer.SetKeepAlivesEnabled(false) ``` TTL Values # 1st query $ dig +noall +answer s-35.185.206.165-127.0.0.1-123-fs-e.d.rebind.it S-35.185.206.165-127.0.0.1-123-fs-e.d.rebind.it.0 IN A 35.185.206.165 # 2nd query $ dig +noall +answer s-35.185.206.165-127.0.0.1-123-fs-e.d.rebind.it S-35.185.206.165-127.0.0.1-123-fs-e.d.rebind.it.0 IN A 127.0.0.1 Why not 1 second? We hoped 0 second would break stuff[1]. It did not so far, as far as we know, it is a legitimate value[2]. How Do We Know We’ve Successfully Rebounded? Two ways to differentiate the attacker server from the target service: ```sh $ curl -v http://s-35.185.206.165-127.0.0.1-3504134792-fs-e.d.rebind.it:8080/ HTTP/1.1 200 OK X-Singularity-Of-Origin: t # Custom HTTP Header <!--thisismytesttoken--><!doctype html><title>(...) # Index Token ``` Randomness and Catering for Potential Interference IPS/IDS/other interference via spurious DNS queries - **Challenge**: the environment IPS/IDS may make their own queries to the attacker domains in addition to the target, resulting in incorrect DNS/out of sequence DNS answers for the target. - **Solution**: Use the random DNS rebinding strategy. - Slower technique in general (but you could get lucky!). The Need for Speed: DNS Rebinding in 3 Seconds Implementation Details Matter! DNS Rebinding speed varies based on a number of factors: - **OS implementation**: Windows or Unix-like (Linux, macOS) - **Browser vendor**: IE/Edge, Firefox, Chrome/Chromium Edge, Safari - **Target specification**: local, remote - **External factors**: Spurious DNS queries e.g. presence of IPS/IDS DNS rebinding may take 40+ min or ~3s on Edge depending on the strategy! We can automatically fingerprint to optimize for speed in some conditions. More on this later! Multiple Answers Rebinding Strategy with Targets 127.0.0.1 / 0.0.0.0 The time-varying (Singularity’s “first then second”) DNS rebinding technique is \( \sim 60 \) seconds on all browsers except IE/Edge. Multiple answers (respond with attacker and target addresses, then block attacker with ephemeral firewall rule) is near instantaneous. 127.0.0.1 works on Windows only. We got it to work on Unix-y machines (Linux, macOS) with “0.0.0.0”. \[ \longrightarrow \] Solid and fast DNS rebinding against all “localhost” services. Multiple Answers Rebinding Strategy Illustrated Target Browser Target Service 127.0.0.1 t: 2s - HTTP request 3 DNS query rebind.it DNS A record response: 1. 35.185.206.165 2. 127.0.0.1 t: 0s - HTTP request 1 t: 1s - HTTP request 2 Blocked! DNS Cache Flooding Multiple Answers works well for the loopback (0.0.0.0 or 127.x.x.x) interface - inconsistent results for other target specifications. On Google Chrome or Safari/iOS platforms, when flooding the DNS cache with 1K+ queries for which we receive valid answers, we observe DNS rebinding time with the time varying attack technique (first then second) of 5 to 40 seconds, a substantial progress over the average of ~60 seconds. Flooding the cache is performed in a web worker. button is only available when the server is started with the "dangerouslyAllowDynamicHTTPServers" command line argument. **Attack** Simple Fetch Get **Payload** **Start Attack** Toggle Advanced Options Rebinding Strategy **First then second** Read the next step if changing from the default value to ensure that the attack will succeed. Interval How long to wait between attempts in seconds. Flood DNS Cache Attempt hijacking the browser DNS cache. Successfully tested on Chrome. Index Token The attack uses this string to recognize whether it is accessing the attacker or target test. It must be placed in the index page of the attacker server. WS/Proxy Port TCP port on which Singularity listens to handle WebSockets and proxy operations. Please wait for DNS cache entries to expire. Simple Fetch Get target: 127.0.0.1:8080, session: 861969865, strategy: fs. DNS rebind successfully! # Speed Measured / Target Definition <table> <thead> <tr> <th>Browser</th> <th>OS</th> <th>Strategy</th> <th>Time to Exploit</th> <th>Fetch Interval</th> <th>Target Spec</th> </tr> </thead> <tbody> <tr> <td>🌐🌐🌐</td> <td>Windows 10</td> <td>MA</td> <td>3 seconds</td> <td>1 second</td> <td>127.0.0.1</td> </tr> <tr> <td>🌐🌐🌐</td> <td>Ubuntu</td> <td>MA</td> <td>3 seconds</td> <td>1 second</td> <td>0.0.0.0</td> </tr> <tr> <td>🌐🌐🌐</td> <td>macOS</td> <td>MA</td> <td>3 seconds</td> <td>1 second</td> <td>0.0.0.0</td> </tr> <tr> <td>🌐🌐🌐</td> <td>macOS, Ubuntu, Windows</td> <td>FS+Cache Flooding</td> <td>15-40 seconds</td> <td>1 second</td> <td>Any</td> </tr> <tr> <td>🌐🌐🌐</td> <td>iOS</td> <td>FS+Cache Flooding</td> <td>5 seconds</td> <td>1 second</td> <td>Any</td> </tr> </tbody> </table> Protection Bypasses DNS Rebinding Protection Bypasses - Singularity can bypass all known DNS rebinding protections: - Unbound - Dnsmasq - pfSense - OpenWRT - OpenDNS (Cisco Umbrella) - Common recommendations and default configurations do not provide complete protection Common DNS Protections Approaches: ● Block RFC 1918 IP addresses ○ 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 ● Block localhost (127.0.0.0/8) ● Block local (internal) networks ● Block 0.0.0.0/8 Tools: ● Dnsmasq & Unbound widely used ○ pfSense, OpenWRT, home routers (e.g. FRITZ!Box, ASUS) ● Public DNS services ○ OpenDNS: “Block internal IP addresses”: Blocks RFC 1918 IP addresses Dnsmasq - **--stop-dns-rebind**: Reject private IP ranges - **--rebind-localhost-ok**: Exempt 127.0.0.0/8 from rebinding checks - This blocks RFC1918 addresses, 0.0.0.0/8, and 127.0.0.0/8 - **localhost** is not blocked --- --- --- **Unbound** - **private-address**: Configure specific internal IP address range to be blocked - This blocks RFC1918 IP addresses - Does **not block** 0.0.0.0, 127.0.0.1, and localhost https://nlnetlabs.nl/documentation/unbound/unbound.conf/ DNS Rebinding Protection Bypass #1: 0.0.0.0 - Wikipedia: “0.0.0.0 is a non-routable meta-address used to designate an invalid, unknown or non-applicable target” - **Fact**: 0.0.0.0 works well on Linux and macOS to access the localhost - This **bypasses** protections that block DNS responses of 127.0.0.1 - Singularity returns a DNS A record: ```bash $ dig s-1.2.3.4-0.0.0.0-474794-fs-e.d.rebind.it ;; QUESTION SECTION: s-1.2.3.4-0.0.0.0-474794-fs-e.d.rebind.it. IN A ;; ANSWER SECTION: s-1.2.3.4-0.0.0.0-474794-fs-e.d.rebind.it. 0 IN A 0.0.0.0 ``` DNS Rebinding Protection Bypass #2: CNAME - What if all internal IP addresses are blocked? - Canonical Name records (CNAME) map one domain name to another - We return a CNAME DNS record instead of an internal IP address - e.g. wiki.nccgroup.com or jenkins.internal.corp.com - This bypasses protections that block DNS responses of private IP addresses - The local, internal DNS server will then resolve the CNAME ```bash $ dig s-1.2.3.4-wiki.nccgroup.com-123-fs-e.d.rebind.it ;; QUESTION SECTION: ;s-1.2.3.4-wiki.nccgroup.com-123-fs-e.d.rebind.it. IN A ;; ANSWER SECTION: s-1.2.3.4-wiki.nccgroup.com-123-fs-e.d.rebind.it. 9 IN CNAME wiki.nccgroup.com. ``` DNS Rebinding Protection Bypass #2a: localhost - localhost is a hostname that means this computer - We return a CNAME (Canonical Name) DNS record of “localhost.” - This **bypasses** protections that block DNS responses of 127.0.0.1 ``` $ dig s-1.2.3.4-localhost-123-fs-e.d.rebind.it ;; QUESTION SECTION: s-1.2.3.4-localhost-123-fs-e.d.rebind.it. IN A ;; ANSWER SECTION: s-1.2.3.4-localhost-123-fs-e.d.rebind.it. 0 IN CNAME localhost. ``` Hook and Control: interactively browse the victim's internal network after DNS rebinding Experimenting with Proxying without an HTTP Proxy HTTP tools such as BeEF (Browser Exploitation Framework - https://beefproject.com/) and FireDrill (https://www.usenix.org/conference/woot13/workshop-program/presentation/dai) can use a hooked browser via XSS or DNS rebinding as a gateway to otherwise unreachable networks such as home or corporate environments. We know that BeEF requires to configure the attacker browser or operating system to use the BeEF HTTP proxy e.g. “http://beef.attaker.com:3120/”. We do not know how FireDrill does it since its code is unfortunately not available. We implemented browsing of services via a hooked browser in Singularity, without requiring the attacker setting up its browser to use an HTTP proxy for fun. Proxy Architecture Attacker Browser → Singularity → Hooked Target Browser → Target Service - Websocket: connect and wait for instructions - HTTP: connect and select hooked target browser Proxy Architecture Attacker Browser -> Singularity -> Hooked Target Browser -> Target Service GET /home HTTP/1.1 Websocket: op="fetch", args "/home" HTTP: fetch("home",{...}) ...and back Proxying without an HTTP Proxy - Customized Golang’s RoundTripper [https://golang.org/pkg/net/http/#RoundTripper](https://golang.org/pkg/net/http/#RoundTripper) - Using WS plain text protocol to package `fetch()` requests and responses - Inflated size of data in transit: \( \text{len} \approx \frac{4}{3} \text{ of len(message)} \) using base64 encoding. **Attacker Browser - Any user agent:** Web browser, `curl`, HTTP inspecting proxy, SQLMap, etc. Dealing with Split Brains: Syncing the state between the attacker and target’s browsers The initial assumption was that we did not have to care about cookies. Our first test case was Duplicati, a backup application which was vulnerable to DNS rebinding attack and has a web interface listening on localhost. ```javascript this.get_import_url = function(passphrase) { var rurl = this.apiUrl + '/backups/import?x-xsrf-token=' + encodeURIComponent($cookies.get('xsrf-token')) if ((passphrase || '').trim().length > 0) rurl += '&passphrase=' + encodeURIComponent(passphrase); if (this.proxy_url != null) return this.proxy_url + '?x-proxy-path=' + encodeURIComponent(rurl); return rurl; }; ``` Oops. Dealing with Split Brains: Syncing the state between the attacker and target’s browsers Cookies may be used as CSRF tokens or other purposes. For non HttpOnly cookies: - Read them from target browser => transmit to the Singularity server - Singularity sets them on the attacker browser for the target domain (the DNS domain constructed by Singularity). For HttpOnly cookies: - We don’t care - they can’t be read by JS so they cannot be used by JS. - The target browser handles (receives and transmits) them for us. Dealing with Split Brains: Syncing the state between the attacker and target’s browsers To be able to read cookies from a response to a `fetch()` request, **you must pass the option** `{credentials: ‘include’}` **to the fetch() request.** If the application requires HTTP authorization (**WWW-Authenticate**), then we must forego completely about passing cookies, **unless we know the credentials in advance** and pass them without being challenged for authentication. Why? Let’s test in the next slides Dealing with Split Brains: Syncing the state between the attacker and target’s browsers `fetch ('http://127.0.0.1', {credentials: 'include'})` → Authentication dialog box popup in victim’s browser → Victim 🤔 Dealing with Split Brains: Syncing the state between the attacker and target’s browsers fetch ('http://127.0.0.1', {credentials: omit}) → No authentication dialog box → Victim 😌 Demo 2: Hook & Control Index Token: thisismytesttoken WS/Proxy Port: 3129 Please wait for DNS cache entries to expire. Hook and Control target: 0.0.0.0:8080, session: 536786693, strategy: ma, DNS rebinding successful! Scanning for Vulnerable Hosts Services Old World and Cool Hacks (Embedding Images, Measuring Requests Response Time) Many astute attempts to replicate nmap behavior without the power of raw sockets. Often unreliable / do too much for our purposes e.g. we don’t care about whether a SSH port is open or not. Does it speak HTTP? We are interested in DNS rebinding and DNS rebinding deals with the HTTP protocol only (so far). Leveraging Modern APIs and Focusing on What Matters (**fetch**, **abort**, HTTP only) ```javascript function scan(targetdata, duration) { let sendDate = new Date().getTime(); var controller = new AbortController();//NO IE support var signal = controller.signal; timeout(duration, fetch('http://${targetdata.address}:${targetdata.port}/', { mode: 'no-cors', credentials: 'omit', signal })), controller) ``` Leveraging Modern APIs and Focusing on What Matters (fetch, abort, http only) Solution: - Wrap in a web worker - distribute scan targets across 4 web workers - `fetch()` resource headers with timeout (300 ms) - Don’t bother with resp. body - Timeout drives how fast scans can go - how long we hang, waiting for a response - When an unhandled protocol (e.g. SSH) or when a port is firewalled (No TCP RST packet) - **Fast** for: open HTTP ports, closed ports - **Slower** for: firewalled ports, slow HTTP services & possibly specific protocols - Pro-tip: - Use a lower timeout when scanning LAN and/or fast HTTP services. - Use higher timeouts when scanning different networks e.g. across VPN. Leveraging Modern APIs and Focusing on What Matters (fetch, abort, http only) Other bits and pieces: - Use the classical WebRTC IP address leak when available to obtain the IP address of the machine and derive a subnet (Chrome, Firefox). - `fetch ('http://127.0.0.1', {credentials: omit})` → No authentication dialog box → Victim 😞. Didn’t we cover this before? 🤔 - Considering performing a second scan pass for potentially slower services (Singularity implementation TODO list). Automation: Service Detection & Exploitation and Orchestrating all the Above Auto Detection and Exploitation of All Things Accessible by the Target Web Browsers ● “Autoattack.html” automation and orchestration sample file ● Customizable ● Permits to leverage all features of Singularity ○ Specific exploitation payload or auto-selection of payload to deliver based on detected service ○ Targets selection + optional detection ○ Ports selection + optional port scanning ○ Default DNS strategy selection + optional detection of best strategy to use in specific cases ○ Various options such as flooding DNS cache, visibly hiding activity etc. ● Future work: more auto-optimization so you don’t have to read the extensive wiki (https://github.com/nccgroup/singularity/wiki). 😂 Choosing the Right Targets 0.0.0.0, "localhost", CNAMES, Weak Host Model - Mix and match different specifications of same target for reliability, security controls bypass and speed ("0.0.0.0", "localhost", "127.0.0.1"). - Find and use the external IP address to exploit routers / Wifi APs’ internal network facing administration interface (weak end system model - https://www.defcon.org/images/defcon-18/dc-18-presentations/Heffner/DEFCON-18-Heffner-Routers-WP.pdf) - Do some homework using OSINT - try to determine the local corporate domains, use a dictionary of service names and specify them as CNAMES e.g. jenkins.internal.corp.com. This is likely to pay off. Service Detection Singularity comes with a number of attack payloads targeting services such as Chrome DevTools Remote Debugger, Amazon AWS instance metadata, Ruby on Rails etc. We recently augmented a number of its payloads with a service detection routine. ```javascript async function isService(headers, cookie, body) { return headers.get("X-Jenkins") !== null; } ``` Selecting the “automatic” payload will instruct Singularity to detect the service and deliver the appropriate attack! Concluding Remarks: There is Only One HTTP Origin How To Protect From DNS Rebinding: Use DNS blacklists Use DNSSec? Use this DNS service provider Use this router/appliance/IPS! How To Protect From DNS Rebinding: Common Wisdom is Not Enough Use DNS blacklists Use DNSSec Use this DNS service provider Use this router/appliance/IP ...Do you understand all the subtleties of DNS rebinding? And no, DNSSec does not help at all! How To Really Protect From DNS Rebinding Always use authentication. Validate the Host header of HTTP requests for correct values e.g. 127.0.0.1 (whitelisting). Demo 3: Automation 1. Portscan 2. Rebind in 3s 3. Auto-detect services 4. Exploit Thank You - Get Singularity of Origin at [https://github.com/nccgroup/singularity](https://github.com/nccgroup/singularity) - DNS server to rebind DNS names to IP addresses - HTTP server to serve HTML pages and JavaScript code to targets and to manage the attacks - Sample attack payloads: Chrome DevTools, Jenkins, & many more - Supports DNS CNAME to evade DNS filtering solutions - A simple, fast and efficient HTTP port scanner to identify vulnerable services - Attack automation: completely automate the scanning and exploitation - Hook & control to exploit victim browser as HTTP proxy to access internal network resources - Contact us: - gerald.doussot@nccgroup.com - roger.meyer@nccgroup.com
{"Source-Url": "https://media.defcon.org/DEF%20CON%2027/DEF%20CON%2027%20presentations/DEFCON-27-Gerald-Doussot-Roger-Meyer-State-of-DNS-Rebinding-Attack-and-Prevention-Techniques-and-the-Singularity-of-Origin.pdf", "len_cl100k_base": 7004, "olmocr-version": "0.1.53", "pdf-total-pages": 76, "total-fallback-pages": 0, "total-input-tokens": 81561, "total-output-tokens": 10655, "length": "2e12", "weborganizer": {"__label__adult": 0.00124359130859375, "__label__art_design": 0.0010967254638671875, "__label__crime_law": 0.023284912109375, "__label__education_jobs": 0.0018510818481445312, "__label__entertainment": 0.0005822181701660156, "__label__fashion_beauty": 0.0004878044128417969, "__label__finance_business": 0.0008649826049804688, "__label__food_dining": 0.0005192756652832031, "__label__games": 0.00429534912109375, "__label__hardware": 0.006008148193359375, "__label__health": 0.0010251998901367188, "__label__history": 0.0008912086486816406, "__label__home_hobbies": 0.00029850006103515625, "__label__industrial": 0.0012731552124023438, "__label__literature": 0.0009403228759765624, "__label__politics": 0.0007944107055664062, "__label__religion": 0.0009684562683105468, "__label__science_tech": 0.275390625, "__label__social_life": 0.0003323554992675781, "__label__software": 0.22216796875, "__label__software_dev": 0.4541015625, "__label__sports_fitness": 0.000576019287109375, "__label__transportation": 0.0006604194641113281, "__label__travel": 0.0003402233123779297}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 27950, 0.04374]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 27950, 0.28073]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 27950, 0.7572]], "google_gemma-3-12b-it_contains_pii": [[0, 128, false], [128, 763, null], [763, 1195, null], [1195, 1208, null], [1208, 1418, null], [1418, 1472, null], [1472, 1528, null], [1528, 1648, null], [1648, 1956, null], [1956, 2615, null], [2615, 3023, null], [3023, 3466, null], [3466, 3832, null], [3832, 4150, null], [4150, 4179, null], [4179, 4529, null], [4529, 4986, null], [4986, 5121, null], [5121, 5313, null], [5313, 5521, null], [5521, 5665, null], [5665, 5857, null], [5857, 6226, null], [6226, 6492, null], [6492, 6837, null], [6837, 7677, null], [7677, 7725, null], [7725, 7780, null], [7780, 9460, null], [9460, 9524, null], [9524, 9921, null], [9921, 10637, null], [10637, 11194, null], [11194, 11532, null], [11532, 11940, null], [11940, 11987, null], [11987, 12489, null], [12489, 13017, null], [13017, 13265, null], [13265, 13758, null], [13758, 14663, null], [14663, 15375, null], [15375, 15395, null], [15395, 15657, null], [15657, 16048, null], [16048, 16283, null], [16283, 16526, null], [16526, 17077, null], [17077, 17736, null], [17736, 18177, null], [18177, 18266, null], [18266, 19018, null], [19018, 19207, null], [19207, 19399, null], [19399, 19853, null], [19853, 20567, null], [20567, 21085, null], [21085, 21592, null], [21592, 21803, null], [21803, 21984, null], [21984, 22205, null], [22205, 22244, null], [22244, 22632, null], [22632, 23084, null], [23084, 23786, null], [23786, 24268, null], [24268, 24345, null], [24345, 25053, null], [25053, 25719, null], [25719, 26216, null], [26216, 26266, null], [26266, 26397, null], [26397, 26646, null], [26646, 27048, null], [27048, 27131, null], [27131, 27950, null]], "google_gemma-3-12b-it_is_public_document": [[0, 128, true], [128, 763, null], [763, 1195, null], [1195, 1208, null], [1208, 1418, null], [1418, 1472, null], [1472, 1528, null], [1528, 1648, null], [1648, 1956, null], [1956, 2615, null], [2615, 3023, null], [3023, 3466, null], [3466, 3832, null], [3832, 4150, null], [4150, 4179, null], [4179, 4529, null], [4529, 4986, null], [4986, 5121, null], [5121, 5313, null], [5313, 5521, null], [5521, 5665, null], [5665, 5857, null], [5857, 6226, null], [6226, 6492, null], [6492, 6837, null], [6837, 7677, null], [7677, 7725, null], [7725, 7780, null], [7780, 9460, null], [9460, 9524, null], [9524, 9921, null], [9921, 10637, null], [10637, 11194, null], [11194, 11532, null], [11532, 11940, null], [11940, 11987, null], [11987, 12489, null], [12489, 13017, null], [13017, 13265, null], [13265, 13758, null], [13758, 14663, null], [14663, 15375, null], [15375, 15395, null], [15395, 15657, null], [15657, 16048, null], [16048, 16283, null], [16283, 16526, null], [16526, 17077, null], [17077, 17736, null], [17736, 18177, null], [18177, 18266, null], [18266, 19018, null], [19018, 19207, null], [19207, 19399, null], [19399, 19853, null], [19853, 20567, null], [20567, 21085, null], [21085, 21592, null], [21592, 21803, null], [21803, 21984, null], [21984, 22205, null], [22205, 22244, null], [22244, 22632, null], [22632, 23084, null], [23084, 23786, null], [23786, 24268, null], [24268, 24345, null], [24345, 25053, null], [25053, 25719, null], [25719, 26216, null], [26216, 26266, null], [26266, 26397, null], [26397, 26646, null], [26646, 27048, null], [27048, 27131, null], [27131, 27950, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 27950, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 27950, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 27950, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 27950, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 27950, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 27950, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 27950, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 27950, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 27950, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 27950, null]], "pdf_page_numbers": [[0, 128, 1], [128, 763, 2], [763, 1195, 3], [1195, 1208, 4], [1208, 1418, 5], [1418, 1472, 6], [1472, 1528, 7], [1528, 1648, 8], [1648, 1956, 9], [1956, 2615, 10], [2615, 3023, 11], [3023, 3466, 12], [3466, 3832, 13], [3832, 4150, 14], [4150, 4179, 15], [4179, 4529, 16], [4529, 4986, 17], [4986, 5121, 18], [5121, 5313, 19], [5313, 5521, 20], [5521, 5665, 21], [5665, 5857, 22], [5857, 6226, 23], [6226, 6492, 24], [6492, 6837, 25], [6837, 7677, 26], [7677, 7725, 27], [7725, 7780, 28], [7780, 9460, 29], [9460, 9524, 30], [9524, 9921, 31], [9921, 10637, 32], [10637, 11194, 33], [11194, 11532, 34], [11532, 11940, 35], [11940, 11987, 36], [11987, 12489, 37], [12489, 13017, 38], [13017, 13265, 39], [13265, 13758, 40], [13758, 14663, 41], [14663, 15375, 42], [15375, 15395, 43], [15395, 15657, 44], [15657, 16048, 45], [16048, 16283, 46], [16283, 16526, 47], [16526, 17077, 48], [17077, 17736, 49], [17736, 18177, 50], [18177, 18266, 51], [18266, 19018, 52], [19018, 19207, 53], [19207, 19399, 54], [19399, 19853, 55], [19853, 20567, 56], [20567, 21085, 57], [21085, 21592, 58], [21592, 21803, 59], [21803, 21984, 60], [21984, 22205, 61], [22205, 22244, 62], [22244, 22632, 63], [22632, 23084, 64], [23084, 23786, 65], [23786, 24268, 66], [24268, 24345, 67], [24345, 25053, 68], [25053, 25719, 69], [25719, 26216, 70], [26216, 26266, 71], [26266, 26397, 72], [26397, 26646, 73], [26646, 27048, 74], [27048, 27131, 75], [27131, 27950, 76]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 27950, 0.02516]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
3eb063b41ad4bf039f991395db63c9ced4721153
Runtime Checking of MPI Applications with MARMOT Bettina Krammer\textsuperscript{a}, Matthias S. Müller\textsuperscript{b} and Michael M. Resch\textsuperscript{a} \textsuperscript{a}High Performance Computing Center Stuttgart (HLRS) Allmandring 30, D-70550 Stuttgart, Germany {\textcolor{black}{krammer, resch}@hlrs.de} \textsuperscript{b}Centre for Information Services and High Performance Computing (ZIH) D-01062 Dresden, Germany matthias.mueller@tu-dresden.de The Message Passing Interface (MPI) is widely used to write parallel programs using message passing, but it does not guarantee portability between different MPI implementations. When an application runs without any problems on one platform but crashes or gives wrong results on another platform, developers tend to blame the compiler/architecture/MPI implementation. In many cases the problem is a subtle programming error in the application undetected on the platforms used previously. Finding this bug can be a very strenuous and difficult task. This paper presents MARMOT, an automated tool designed to check the correctness of MPI applications during runtime. Examples of such violations are the introduction of irreproducibility, deadlocks, incorrect management of resources such as communicators, groups, datatypes etc. or the use of non-portable constructs. 1. How to Find Bugs in Parallel Programms Parallel programs can not only be inflicted with all the bugs known from serial programming (multiplied by the number of processes) but also by bugs resulting from the interaction of several parallel processes. Reproducibility is often not given. Finding these bugs in a complex parallel application is quite a painful task. Fortunately there are powerful tools for the different aspects of debugging, e.g. tools for memory checking or for correctness checking. Apart from the classical way of debugging – \texttt{printf} statements – the different solutions are roughly grouped into four different approaches: classical debuggers, special MPI libraries and other tools that may perform a runtime or post-mortem analysis. 1. The freely available debugger gdb [16], which is also used with its graphical front-end ddd [17], has currently no support for MPI, but it can be attached to one or several, possibly already running MPI processes. The same can be done with special memory-checking debuggers like valgrind [18,19]. More convenient are parallel debuggers, which are based on serial debuggers like gdb. They provide the usual interactive functionality of debuggers, such as single-stepping, breakpointing, evaluating variables, etc., but additionally allow the user to monitor and act on groups of processes in a single debugging session. Examples are the well-known commercial debuggers Totalview [14] or DDT [13]. These debuggers can also be used for a post-mortem analysis of core files. 2. The second approach is to provide a special debug version of the MPI library (e.g. mpich or NEC-MPI). This version is not only used to catch internal errors in the MPI library, but also to detect some incorrect usage of MPI by the user, e.g. a type mismatch of sending and receiving messages or mismatched collective operations [4–6]. Another possibility is to develop tools dedicated to finding problems within MPI applications at runtime. At present, three different message-checking tools are under more or less active development: MPI-CHECK [8], Umpire [3] and MARMOT [9,10]. MPI-CHECK is currently restricted to Fortran code and performs argument type checking or finds problems like deadlocks [8]. Like MARMOT, Umpire [3] uses the profiling interface. The fourth approach is to perform a post-mortem analysis by collecting all information on MPI calls in a trace file. After program execution, this trace file is analysed by a separate tool or compared with the results from previous runs [7]. An example of this is the Intel Message Checker (IMC) [20]. This approach is also used by many tools with respect to performance analysis, and indeed, in some cases it can be very enlightening to “abuse” a performance tool for debugging. As no tool is an all-in-one device suitable for every purpose, a combination of different tools will probably aid the developers most. While a memory-checking debugger may be able to diagnose that an application crashes due to an uninitialized variable, it will definitely not help you much in finding incorrect usage of the MPI interface as MARMOT does. Regardless, not every error can be caught by tools. 2. Architecture of MARMOT MARMOT uses the so-called profiling interface to intercept MPI calls and analyse them during runtime. It does not require any modification of the application’s source code nor of the MPI library, it is just a library that has to be linked to the application in addition to the underlying MPI implementation. Figure 1 illustrates the design of MARMOT. For all tasks that require a global view, e.g. deadlock detection or the control of the execution flow, MARMOT uses an additional process, the so-called Debug Server. Each client registers at the debug server, which in turn gives its clients the permission for execution in a roundrobin way. In order to ensure that this additional debug process is transparent to the application, we map $\text{MPI}_\text{COMM}_\text{WORLD}$ to a MARMOT communicator containing only the application processes. Since all other communicators are derived from $\text{MPI}_\text{COMM}_\text{WORLD}$ they automatically exclude the debug server process. Everything that can be checked locally, e.g. verification of arguments such as tags, communicators or ranks, is performed by the client. Additionally, the clients and the Debug Server use MPI internally to transfer information. This server/client architecture inflicts a bottleneck, thus affecting the scalability and performance of the tool, especially for communication-intensive applications [12]. 3. Runtime Checking of MPI Applications 3.1. Runtime versus Post-mortem Analysis Compared to human intervention, automatic checking has the potential to scale better. Two different scalability issues are important. First, scalability to many processors, and second, scalability in runtime. We see programs that show illegal or non-portable use of MPI only after an exceptionally long runtime. For instance, an application increases the send/receive tag after each iteration step by 1. After thousands of iterations, the tag finally exceeds the limit of up to 32767 that is guaranteed by the MPI standard. While many MPI implementations grant a much higher range of tags, there are implementations that are strict about that limit, for example versions of LAM-MPI prior to 7.0. Since runtime checking does not require storing a huge amount of persistent information there is no scalability limit regarding runtime. Another advantage of runtime checking, compared to offline analysis, is that the application is still up and running when an error is detected. Thus other tools can be used to further analyse the situation. For example, a debugger can be attached to check the content of variables and understand the status of the application. 3.2. Frequent Problems of Parallel Programming Parallel programming is a complex challenge. It offers enough pitfalls that MPI can imaginably stand for “Maddening Programming Interface”. Among the Top Ten common programming errors are: - **Deadlocks**: MARMOT contains a mechanism to automatically detect deadlocks and notify the user where and why they have occurred. In general, deadlocks are caused by the non-occurrence of something else, for example mismatched send/receive operations or mismatched collective calls. One can distinguish between real deadlocks, which occur inevitably, and potential deadlocks, which may occur only under certain circumstances, e.g. depending on data races or on the implementation, for instance, if a standard send is implemented as a buffered send or not. In this code snippet process 0 and process 1 exchange messages between each other. ```c if (rank == 0) { // send to 1 and receive from 1 MPI_Send(...); MPI_Recv(...); } else if (rank == 1) { // send to 0 and receive from 0 MPI_Send(...); MPI_Recv(...); } ``` If the MPI_Send is implemented in buffered mode, for example for small message sizes, this code will not deadlock, otherwise it will. Currently MARMOT’s deadlock detection is based on a timeout mechanism and therefore finds all real deadlocks. MARMOT’s debug server surveys the time each process is waiting in an MPI call. If this time exceeds a certain user-defined limit on all processes at the same time, the debug process issues a deadlock warning. The user is then able to trace the last few calls on each node. It is also possible that attaching MARMOT (or any other tool) to an application slightly changes the execution flow in such a way that a potential deadlock becomes apparent. - **Data races:** Potential race conditions can be caused by various reasons, e.g. by the use of a receive call with the wildcard MPI_ANY_SOURCE as source argument or the wildcard MPI_ANY_TAG as tag argument, by the use of random numbers, or by the fact that nodes do not behave exactly the same. Some users also rely on collective calls being synchronising, however, the only synchronising collective call is the MPI_BARRIER. Other collective calls can be synchronising or not, depending on their implementation. For example, assume that any of the send calls on the processes 1 and 2 match to any of the receive calls on process 0. ```c if (rank == 0) { MPI_Recv(..., MPI_ANY_SOURCE, MPI_ANY_TAG,...); MPI_Bcast(...); MPI_Recv(..., MPI_ANY_SOURCE, MPI_ANY_TAG,...); } else if (rank == 1) { MPI_Send(...); MPI_Bcast(...); } else if (rank == 2){ MPI_Bcast(...); MPI_Send(...); } ``` If the MPI_Bcast is synchronising process 0 will have to receive the message from process 1 first. If it is not then the message order will not be deterministic: either the message from process 1 or from process 2 can be received first. At present, MARMOT indicates the use of wildcards, but it does not construct dependency graphs to view the different possible executions nor does it use methods like record and replay to identify and track down bugs in parallel programs [7] or to compare different runs. Why does one need a tool to detect this sort of argument as a simple grep command on the source code would give the same result? Actually, a search command does neither show the execution flow nor will it be able to detect this argument if the application takes functions from some other library with hidden MPI calls. - **Mismatches:** Mismatches in arguments of one call can be detected locally and are sometimes even detected by the compiler. Examples are wrong type or number of arguments. Mismatches are also seen in arguments involving more than one call, e.g. in send/receive pairs or in collective calls. Special attention is needed when comparing matched pairs of derived datatypes because it is legal to send, for example two (MPI_INT, MPI_DOUBLE) and to receive one (MPI_INT, MPI_DOUBLE, MPI_INT, MPI_DOUBLE), or to send one (MPI_INT, MPI_DOUBLE) and to receive one (MPI_INT, MPI_DOUBLE, MPI_INT, MPI_DOUBLE) (a so-called partial receive). MPI implementations usually abort an application when there is a datatype mismatch, e.g. send an MPI_INT and receive an MPI_DOUBLE, but no exact diagnosis of the mismatch is given. • **Resource handling:** This is an area in MPI where incorrect usage may result in fatal errors with almost no obvious link to the real cause. Since they are very difficult to find, we place special focus into detecting them. MARMOT is able to keep track of the proper construction, usage and destruction of all MPI resources, such as communicators, groups, datatypes, etc. As these resources are “opaque” objects and therefore implementation-dependent, MARMOT has its own book-keeping of these resources and, thus, duplicates the management done by the underlying MPI library. MARMOT also checks if requests and other arguments (tags, ranks, etc.) are used correctly, e.g. if an active requests is reused. The main functionality is implemented for the C language binding, whereas the functionality for the Fortran language binding is obtained through a wrapper to the C interface. Special attention is paid to the verification of the datatypes because they are one of the major differences between the C and the Fortran language binding. • **Memory and other resource exhaustion:** Non-blocking calls such as `MPI_Isend` etc. can complete without issuing a matching test or wait call. However, the number of available request handles is limited (and implementation defined). Therefore requests should always be freed, as should allocated communicators, datatypes, etc. MARMOT gives a warning when a request is reused, and also when there are active or non-freed requests left at the `MPI_Finalize`. Another issue is reusing memory that is still in use, for example by reading/writing from/into a buffer by an unfinished send/receive operation. MARMOT does currently not perform any checks if a buffer can be reused safely because the transmission of data has completed. This kind of check is a subtle task that requires some insight into an MPI implementation: what is really going on when calling e.g. `MPI_Isend` or `MPI_Irecv`, how does that depend on the message size, etc.? In some cases, MARMOT checks if buffers are overwritten by mistake, e.g. for `MPI_Gatherv` and similar collective calls, it is verified if on the root process data is overridden due to an erroneous array of displacements. • **Portability:** The MPI standard leaves many decisions to the implementors, for example how to implement opaque objects and handles to these objects, if to implement `MPI_Send` as buffered call or not, if to implement collective calls as synchronising calls, if to make the implementation thread-safe or not, etc. Some of these issues can already be detected at compile time when the application is ported to another environment, some can be found at runtime by MARMOT, e.g. using a tag beyond the guaranteed limit. Another example of non-portable constructs can even be found in the MPI-1 standard on pages 79 - 80 (and we have found it exactly like that in a user’s code): ```c /* build datatype describing structure */ ... MPI_Aint disp[3]; int base; /* compute displacements of structure components */ ... base = disp[0]; for (i=0; i<3; i++) disp[i] -= base; MPI_Type_struct(...,disp,...); ``` If you ever try to use the datatype constructed above on a 64-bit-architecture the code will probably crash without any warning, not at the construction step, but later on when the datatype is used, e.g. in a send/receive call. The reason is that MPI_Aint is long and not int there, and thus, some significant bits are lost in the computed array of displacements. MARMOT supports the complete MPI-1.2 standard, although not all possible tests (such as consistency checks) are implemented. It can be used with any standard-conforming MPI implementation and may thus be deployed on any development platform available to the programmer. Although high-quality MPI implementations detect some of these errors themselves, there are many cases where they do not give any warnings. For example, non-portable implementation-specific behaviour is not indicated by the implementation itself, nor are checks performed that would decrease the performance too much, such as consistency checks. What is worse, MPI implementations tolerate quite a few errors without warnings or crashing, by simply giving wrong results. MARMOT is tested on Linux Clusters with IA32/IA64 processors, Cray, Hitachi, IBM Regatta and NEC SX systems, using different compilers (GNU, Intel, PGI, etc.) and different MPI implementations (mpich, LAM/MPI, vendor MPIs, etc.). Functionality and performance tests are performed with test suites, microbenchmarks and real applications [11,12]. 4. More Examples There are many examples of errors that are tolerated by MPI implementations or that only occur on specific platforms, or occur under specific circumstances. For example, in mpich it is possible to use the Fortran datatype MPI_INTEGER in a C program without any problems or warnings because, in this implementation, some Fortran datatypes are defined in the C include file mpi.h. Implementations that are stricter, e.g. LAM/MPI, will not execute that code. When analysing the development version of a medical application that uses a 3D Lattice-Boltzmann method for blood flow calculation, we find another portability problem of that kind. In many places the developers equate MPI_Comm with int. This is a dangerous thing to do because, in mpich, the opaque object MPI_Comm is actually defined as an int and therefore the code works without a problem. However, in LAM/MPI, MPI_Comm is defined as a pointer to a struct and therefore it breaks on any platform where a pointer does not fit into an integer. When we test this application with different input files representing the geometry of the artery we find other problems. In the simplest case, a mere tube with an approximately constant radius, the code runs without any problems. When calculating the blood flow for an artery stenosis, i.e. using a tube with varying radius, the application stalls and MARMOT finds a deadlock caused by process 0, which performs an MPI_Sendrecv whereas all other processes perform an MPI_Bcast. A very simplified skeleton of the source code shows why: ```c main { ... // compute number of iterations depending on the radius if (radius < x) num_iter = y; else num_iter = z; for (i=0; i < num_iter; i++) { // compute blood flow and exchange results // with neighbours using MPI_Sendrecv ``` Every process calculates its own number of iterations depending on the radius, but unfortunately, they do not communicat to agree on a maximum number of iterations. As a result, process 0 tries to perform more iterations having a piece of the artery with a bigger radius than the others, and therefore tries to exchange results with its neighbour using the MPI_Sendrecv whereas the others already have finished their iterations and try to communicate with the MPI_Bcast. This shows how important it is to choose relevant input data sets for an effective runtime checking. It also shows how difficult it is for developers to keep track of all the MPI communication when it is hidden in subroutines. Another input file representing a forked artery reveals yet another programming error. In this case, every process results in different values for the send/receive counts in the collective call MPI_Gather. On some platforms the application runs without a problem, but on some platforms the different values cause a segmentation violation. Strangely enough, on one platform the application runs without a problem, but when attaching a performance analysis tool to it, it crashes. It appears to be the fault of the tool, but in reality there is a bug in the application. Antithetically, it is possible that bugs never occur in the presence of tools (so-called Heisenbugs). 5. Conclusions and Future Work Hitherto, we have presented the MARMOT tool, which analyses the behaviour of an MPI application during runtime and checks for errors frequently made in the use of the MPI API. The functionality of this tool has been tested with real world applications. Although there is still plenty of work to do, we believe that MARMOT is on the right track and will become an indispensable tool in the development of MPI-parallel applications. Future work includes an extension of MARMOT’s functionality according to the users’ needs. To offer a more user-friendly interface, to support frequently used parts of MPI-2 such as parallel file I/O [10] or to support hybrid applications written in OpenMP and MPI. Another goal is to improve the performance and scalability of the tool, especially for communication-intensive applications. Acknowledgments The development of MARMOT was partially supported by the European Union through the IST-2001-32243 project “CrossGrid”. References http://www.streamline-computing.com/software/division_1.shtml [19] Valgrind support for MPICH. http://www.hlrs.de/people/keller/mpi/mpich_valgrind.html Unfortunately, debugging message-passing applications can be difficult. Software complexity, data races, and scheduling dependencies can make programming errors challenging to locate with manual, interactive debugging techniques. This article describes Umpire, a new tool for detecting programming errors at runtime in message passing applications. Umpire monitors the MPI operations of an application by interposing itself between the application and the MPI runtime system using the MPI profiling layer. Umpire then checks the application’s MPI behavior for specific errors. Our initial collection of programming errors includes deadlock detection, mismatched collective operations, and resource exhaustion. Main interface MPI profiling interface according to MPI standard 1.2. Implementation of C language binding of MPI. 18 Medical application on an IA32 cluster with Myrinet 19 Message statistics with native MPI 20 Message statistics with MARMOT 21 Medical application on an IA32 cluster with Myrinet without barrier 22 Barrier with native MPI 23 Barrier with MARMOT 24 Conclusion. MARMOT supports MPI 1.2 for C and Fortran binding.
{"Source-Url": "https://redaron.com/tari.pdf", "len_cl100k_base": 4553, "olmocr-version": "0.1.53", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 19737, "total-output-tokens": 6056, "length": "2e12", "weborganizer": {"__label__adult": 0.0003056526184082031, "__label__art_design": 0.000217437744140625, "__label__crime_law": 0.00033402442932128906, "__label__education_jobs": 0.0003342628479003906, "__label__entertainment": 7.140636444091797e-05, "__label__fashion_beauty": 0.0001386404037475586, "__label__finance_business": 0.00017011165618896484, "__label__food_dining": 0.00032138824462890625, "__label__games": 0.0005116462707519531, "__label__hardware": 0.0016965866088867188, "__label__health": 0.00055694580078125, "__label__history": 0.0002199411392211914, "__label__home_hobbies": 7.975101470947266e-05, "__label__industrial": 0.0004887580871582031, "__label__literature": 0.00018274784088134768, "__label__politics": 0.00023937225341796875, "__label__religion": 0.0004682540893554687, "__label__science_tech": 0.055419921875, "__label__social_life": 8.803606033325195e-05, "__label__software": 0.0142059326171875, "__label__software_dev": 0.9228515625, "__label__sports_fitness": 0.0003459453582763672, "__label__transportation": 0.0004878044128417969, "__label__travel": 0.0001926422119140625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 24819, 0.02382]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 24819, 0.4338]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 24819, 0.86151]], "google_gemma-3-12b-it_contains_pii": [[0, 3213, false], [3213, 5688, null], [5688, 8532, null], [8532, 11512, null], [11512, 14625, null], [14625, 17908, null], [17908, 20719, null], [20719, 23681, null], [23681, 24819, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3213, true], [3213, 5688, null], [5688, 8532, null], [8532, 11512, null], [11512, 14625, null], [14625, 17908, null], [17908, 20719, null], [20719, 23681, null], [23681, 24819, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 24819, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 24819, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 24819, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 24819, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 24819, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 24819, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 24819, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 24819, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 24819, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 24819, null]], "pdf_page_numbers": [[0, 3213, 1], [3213, 5688, 2], [5688, 8532, 3], [8532, 11512, 4], [11512, 14625, 5], [14625, 17908, 6], [17908, 20719, 7], [20719, 23681, 8], [23681, 24819, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 24819, 0.0]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
c124000421233f5488bb753e0042e8ee8ac70c07
Automatic grading of programming exercises in a MOOC using the INGInious platform Guillaume Derval, Anthony Gego, Pierre Reinbold, Benjamin Frantzen and Peter Van Roy, Université catholique de Louvain, Belgium ABSTRACT This paper represents a return of experience about the use and design of an external grader for a computer science MOOC. We introduce INGInious, an automatic grader for both on-site students and students from the edX platform. Then, we explore both the practical and technical approach of its use. We see that providing good feedback is a key element to learning, and that it must be as detailed as possible, but also, because of theoretical limits, transparent. Then we see how a good external grader must be designed, that is, generic, safe and reliable. Introduction When learning computer science, it is important to give actual programming exercises, where students are required to write fully working algorithms. It has been long since the idea of automating corrections of such exercises has been suggested, but faced different limits, theoretical or technical, resulting in full or partial involvement of a human in the correction. In the case of MOOCs, the automation of these corrections is no longer a desire, but also a requirement. The number of students is usually too great to permit handmade corrections. Even with automation, the slightest involvement required from a physical person can become huge and induce great costs. Apart from alternative forms of feedback [Nicol, 2010], the process therefore needs to be fully automated. This paper presents methods and tools that allow automatic grading of code made by students. INGInious [Derval et al., 2014] developed at the Université Catholique de Louvain by Guillaume Derval, Anthony Gégo and Pierre Reinbold, is a tool designed for this goal. INGInious is made to be generic, capable of running virtually any programming language; safe, running students’ algorithms in specific virtual environments confined from the base system; and scalable, capable of dealing with large numbers of submissions. In addition to grading algorithms autonomously, INGInious also provides an interface with the edX platform. INGInious is a free and open-source software (FOSS) distributed under the AGPL license. Its sources are available on GitHub. Creating exercises with INGInious To prepare INGInious for correcting student exercises, two preliminary steps are needed. First, it must be installed, which requires some important step is available in the documentation of INGInious. Second, courses and exercises can be added. INGInious classifies exercises in terms of courses and tasks. A course contains multiple tasks, and a task contains one or more exercises. Each exercise has the form of a directory, containing at least two files. One of them contains various information about the exercise, like its name, a description, and various constraints to be applied when tested (time or memory limits). The second file is the actual script to be run. This script can in turn call various components or subscripts present in the virtual machine (we discuss these virtual machines in the section Secure code execution and environments). This script is intended to check the student’s answer and provide some feedback. The feedback must provide at least two elements, as edX course designers will know, that is, a binary value to state if the exercise is passed or not, and an arbitrary text to provide the user some feedback. This feedback is discussed in the next section. At this point, INGInious is ready to accept student input. When adding an exercise to an edX course, a (small) additional step is required, that is, setting up the exercise in edX (see edX documentation about external graders [edX, 2014]). Providing the user with good feedback Introduction In the context of MOOCs, one must keep in mind that, historically, automated feedback was the only one the students were going to get, at least in large-scale courses. Nowadays, other forms of reviewing have emerged (peer reviewing for instance), but automated feedback can still be wished for, especially in hard science, due to the factual nature of most exercises. If we choose to use it, it is important to help students to find, understand and correct their mistakes themselves, in order to maximize their learning [Nicol, 2010]. A good feedback is therefore a requirement of a good grading process. Giving a result as ‘passed’ or çIDLOHGèLVLQVXIĆFLHQW Cause of errors When writing programs, there are three different kinds of errors. (1) The program is not correct with respect to the programming language, that is, there is a compilation error. (2) The program is syntactically correct but the execution encounters an unexpected operation, that is, there is a runtime error. (3) Finally, it is correct regarding to the programming language, but does not provide the correct answers. One should note that each of these errors does not necessarily mean that the student has a comprehension issue. In our case, a student could very well understand a concept, but fail to apply it to a concrete example because of the particular syntax of the programming language used (in our case, Oz). However, it is quite useless in computer science to understand a concept and not being able to use it, so helping the student to correct the mistake is important. How feedback is provided Computer scientists know that automatic correction is not an easy task, because of theoretical limits: it is actually impossible to check whether the student’s code does the same as a correct one (consequence of Rice’s Theorem, see [Beckman, 1980]). There are different approaches to check for algorithm correctness. Some mathematical theories provide actual tools to prove a program’s correctness (for example, see [Vander Meulen, 2014]). However, these can be quite complicated, and represent much trouble to implement. Moreover, in the context of a Programming Paradigms course, the goal is not for students to ensure program correctness, which is a theoretical field in itself, but rather to understand the concepts exposed. We therefore take the approach of unitary testing. In other words, we run the student’s code with some inputs and check the output. For each test, we then handle the errors. Classification of feedback We can reduce all three kinds of errors to one behavior in the grading process. First of all, before even thinking of interpreting the error, we must accept that it is probably not possible to predict all the possible answers a student could give, and the reasons he gave them. In this regard, it is good practice to be as transparent as possible in the errors detected. It is important to tell the student how his algorithm has been tested, that is, with what input, so that he can test it himself, and reflect about the error. Nevertheless, we would like to provide more precise feedback, at least for the most common errors. Concerning compilation and runtime error messages, they are often generic and sometimes quite meaningless, even though they often happen for the same reasons. It is usually beyond the scope of a compiler to provide advice to correct errors, but a grader can suggest different leads to the students when a particular error is encountered. Also, it is possible to do some static checks to detect most common syntactic and conceptual errors. These errors are often similar in all possible exercises, and will most likely not be reproduced once understood. Other errors can be specific to a particular exercise. Here, static checks can also be performed. But with a bit of practice, it is possible to recognize frequent mistakes made by students, resulting in the same wrong output, or an error. When this error is detected, it is a good idea then to give more information to the student and probable cause of mistakes. Practical experience There are some additional thoughts one should keep mind when designing exercises. First, it is very easy to see the limits of unitary testing: if an algorithm is supposed to compute, say, ‘4+2’, one can design an algorithm that will compute ‘1+5’, ‘3+3’ or simply return 6 directly. Each of these algorithms provides the good answer, but the computation is not correct. Combined with the transparency principle, it is easier for a student to cheat. This is an issue for on-site students of a MOOC. The idea is thus to make it more difficult for the student to cheat rather than giving the good answer. There are different possibilities to achieve that. A good start is to make many different tests. Other ways can be to test subsets of the algorithm (for instance, each function individually), force students to use some pre-defined functions, or pre-defined lines of code, and finally, perform some static check to prevent some specific calls or patterns. More optimistically, though, a student could also write an algorithm that works in some cases but not in others, for instance, he might not even know why his algorithm works or doesn’t work. Our goal here is to provide feedback that will help him understand. Among these test cases, we will therefore test limit cases of the algorithm, that is, cases that can be somewhat singular and require additional steps from the algorithm (for example, trying to sort an empty list). Students often forget about these limit cases, and they often are the reason the algorithm is incorrect: a forgotten limit case can often cause the algorithm to crash. Also can be tested some cases that are to be considered typical regarding the goal of the exercise, to make sure the student really understands its purpose. Once all these tests pass, we can consider that goal achieved, and it will often be enough to consider the exercise correct. Finally, to avoid too many different causes of mistakes, which complicate the design of the grading process, and most likely the understanding of students, it is a good idea to keep exercises small, and focused on one particular aspect. The automation of corrections being as it is, correcting big algorithms gives more opportunity to encounter an unexpected situation, and thus provide wrong feedback, which often irritates students. Small exercises will allow them to test their knowledge in a straightforward manner, and identify their errors quickly. More elaborate exercises can be done at different intervals, and are an opportunity to cross their knowledge and challenge them more, but it is a better practice to do that only when we are sure each concept has been understood individually. Architecture of INGInious INGInious is composed of two parts, called the frontend and the backend. The frontend provides a simple web interface for the students that do not follow the MOOC (at UCL, INGInious is used for other courses that are not on edX), an administration that allows writing tasks directly in the web browser. The frontend also manages the database (using MongoDB) containing submissions and statistics. The plugin system is also managed by the frontend. It can be configured to run the edX plug-in, communicating with the edX platform and allowing to grade code using the simplicity and power of INGInious on edX. The edX plugin is in fact, from the point of view of the edX platform, a passive grader. The configuration of this plugin is very simple and is described in the documentation of INGInious. Other plugins are available, allowing calling the grader externally via JavaScript for example, or providing additional statistics on the submissions. Made as an independent library, easily reusable, the backend creates, manages and deletes containers, running the code made by the students. The backend does not store anything in a database or on the disk. Figure 1 shows a simplified diagram of the INGInious architecture. Once the environments (container images, described in the next section) and the tasks’ scripts have been written by the teacher or its assistants, everything is automatized: the students’ code will Students have two ways to interact with INGInious: the first being the frontend web interface, that needs the creation of an account (at UCL, accounts are provided via an LDAP server); the second is the edX plug-in, which receives anonymous requests from the edX platform. The use of this plug-in is completely invisible for edX students. The course can be followed simultaneously by on-site students, each with its own INGInious account; and by edX students, each with its edX account, whom will post their answer directly at edX. Secure code execution and environments INGInious must execute its code in a safe environment that allows both resource control and safety. Code submitted by students should not be trusted in any way. The separation between the host machine and the safe environment is traditionally handled by the usage of virtual machines (Pythia [Le Clément de Saint-Marcq & Combéfis, 2012], the predecessor of INGInious, used User Mode Linux, a kind of virtual machine), that in fact separate the untrusted processes via a hypervisor. This hypervisor manages the resources available to the virtual machines. This approach certainly has advantages (nearly complete separation of the processes), but also has some drawbacks, in particular creating new environments is hard and there is a huge overhead due to the presence of a second operating system. INGInious uses another approach, based on Docker [Docker, Inc., n.d.-b], a relatively recent technology that provides containers. Containers are safe and closed environments, but run inside the host kernel. This resource separation is in fact provided by two features of Linux, kernel namespaces and cgroups. Containers are therefore very lightweight: they do not start and manage another operating system, as, for the host OS, containers are simply constrained processes. Like virtual machines, containers can be run with a specified amount of memory, be associated with specific CPUs, and mount shared folder from the host. Moreover, Docker provides a simple way, called Dockerfiles [Docker, Inc., n.d.-b], to create new container images (or environments). With a very simple syntax, anyone that uses a Linux command line tool can quickly create a new environment. Code listing 1 below is the complete content of the Programming Paradigms course. It is somewhat simple: it inherits from the default INGInious container image, and installs Mozart 2 (which provides the Oz language, used for the course). ``` # Inherits from the default container FROM # ingi/INGInious-c-default ADD mozart2-2.0.0-alpha.0+build.4105.5c- -06ced-x86_64-linux.rpm /mozart.rpm # Install dependencies of Mozart 2 and Mozart 2 RUN yum -y install emacs tcl tk RUN rpm -ivh /mozart.rpm RUN rm /mozart.rpm ``` Code listing 1. Dockerfile for ingi/inginious-c-oz Docker uses a union file system to store the container images. The container images are viewed as layers, and each command in a Dockerfile (from inheritance to RUN commands) creates a new layer. This allows to drastically reduce space used to store the different environments, as only the difference between the custom container images and the default one is stored. INGInious launches a container each time a submission is made, from the appropriate container image. Containers are then very short-lived (they live the duration of the grading). Container images are most of the time shared between multiple tasks or even between multiple courses. For the purpose of the MOOC, only two container images were used, ingi/inginious-c-oz (that provides Mozart 2), and ingi/inginious-c-pythia1compat (that provides a compatibility layer for Pythia). Other container images are available, allowing using different languages: C++, Java 7/8, Scala, Python 2/3 are also provided with the sources of INGInious. Creating new containers to add new languages is very simple as shown earlier. This way to use containers means that there are as many running containers as running tasks. With the union file system, the disk is not used by more than a few kilobytes at each container start. There is also a very low memory footprint. The kernel scheduler then handles the repartition of the CPU resources between the different running processes. INGInious adds some constraints, such as timeouts, to the container to ensure that they correctly end. Processes that exceed the time allowed to them or that use too much memory are killed, sending an appropriate message to the student. Scaling of the machine At INGInious, we use a single machine running all the components of INGInious. We have currently four courses that use INGInious: the Programming Paradigms MOOC, Computer Science I, Artificial Intelligence and Advanced algorithms for optimization (Deville, 2014). Programming Paradigms has a broad audience compared to the other courses: in the Fall 2014 edition more than four thousand students enrolled in the second part of the course. The other courses count between thirty and four hundred students. Exercises of the courses Programming Paradigms and Computer Science I asks students to write very small algorithms that are never long to complete, and do not involve a lot of computing. The two other courses run exercises that may take more than five minutes of computation to complete. The machine hosting INGInious was scaled to handle these two types of loads: a large audience running lightweight exercises and a small audience running computation-intensive exercises. We used a virtual machine with 6 (virtual) CPUs and 12 GB of memory. The figure 2 represents the load averages between December 28th, 2014 and January 12th, 2015, which are the days when the final exam of the MOOC occurred. All the other courses were already finished. During this period, around 600 students made 5976 requests to INGInious, with an average running time of 5.17 seconds. The maximum number of concurrent requests was three. From the point of view of the MOOC, the machine is clearly over-scaled, with the load averages often below one (less than six times the maximum sustainable load), and with memory usage always under 30%. A small dual-core virtual machine with 6 GB of memory is sufficient to handle the MOOC load. INGInious thus does not need to run on a costly cloud. The machine we use is well scaled for the usage of INGInious made at UCL, as the two more computationally intensive courses sometimes put it at its limit. Usage peaked twice during the Fall 2014 semester, at the deadlines of the course advanced algorithms for optimization, with a load average of 6 for some hours. The management of the peaks is still a work in progress in INGInious, as heuristics for queue management have to be developed. Conclusion Automation of correction is still a great challenge nowadays, and the stakes are high in the context of MOOCs. In the future, with the increase of use of ICTs, more and more students are likely to follow courses online, both in a formal, legal, or informal manner. Followed by actual students seeking for a certificate with a legal value, automatic correction is a key element of checking their competences. But more than just a corrector, an automatic grader has... also to be seen as a feedback provider, which can analyze student's understanding and guide them in their learning. Different tools make it easier today to design such grader, with different functional requirements in mind (genericity, safety, reliability). INGInious is one of these graders, and provides both easy-to-use features (for students and instructors) and these requirements. The use of INGInious is very easy, whether for automation of correction, but also by executing about any task based on a student input. More than its use in the context of MOOCs, many prospects therefore rise, that might change the vision of online learning itself. The use of such tools will indeed change the way instructors are able to design their courses, and provide a very personalized learning despite the distance and virtualization, and the prospects in this regard are most likely to be as great and exciting as the future. References
{"Source-Url": "https://alfresco.uclouvain.be/alfresco/service/guest/streamDownload/0e245c65-3ca3-43fb-ac4b-f76d6fab143b/DervalVanRoy-EMOOCs2015.pdf?guest=true", "len_cl100k_base": 4201, "olmocr-version": "0.1.50", "pdf-total-pages": 6, "total-fallback-pages": 0, "total-input-tokens": 17013, "total-output-tokens": 4995, "length": "2e12", "weborganizer": {"__label__adult": 0.0005054473876953125, "__label__art_design": 0.0005869865417480469, "__label__crime_law": 0.0005526542663574219, "__label__education_jobs": 0.06024169921875, "__label__entertainment": 0.00012552738189697266, "__label__fashion_beauty": 0.00026535987854003906, "__label__finance_business": 0.00047850608825683594, "__label__food_dining": 0.000797271728515625, "__label__games": 0.000873565673828125, "__label__hardware": 0.0010232925415039062, "__label__health": 0.0006656646728515625, "__label__history": 0.00036978721618652344, "__label__home_hobbies": 0.00020229816436767575, "__label__industrial": 0.0006089210510253906, "__label__literature": 0.0005898475646972656, "__label__politics": 0.0004377365112304687, "__label__religion": 0.00099945068359375, "__label__science_tech": 0.01067352294921875, "__label__social_life": 0.0003294944763183594, "__label__software": 0.0190277099609375, "__label__software_dev": 0.89892578125, "__label__sports_fitness": 0.00044798851013183594, "__label__transportation": 0.0008320808410644531, "__label__travel": 0.0003879070281982422}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 21793, 0.01723]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 21793, 0.77294]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 21793, 0.93011]], "google_gemma-3-12b-it_contains_pii": [[0, 3667, false], [3667, 8279, null], [8279, 12068, null], [12068, 16109, null], [16109, 19265, null], [19265, 21793, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3667, true], [3667, 8279, null], [8279, 12068, null], [12068, 16109, null], [16109, 19265, null], [19265, 21793, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 21793, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 21793, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 21793, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 21793, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 21793, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 21793, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 21793, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 21793, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 21793, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 21793, null]], "pdf_page_numbers": [[0, 3667, 1], [3667, 8279, 2], [8279, 12068, 3], [12068, 16109, 4], [16109, 19265, 5], [19265, 21793, 6]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 21793, 0.0]]}
olmocr_science_pdfs
2024-11-27
2024-11-27
1e066f617f0a54ae9472d6c1e5bca2f37904a809
Unlocking the Hidden Logic of Process Improvement: Peer Reviews The success of many of the most useful procedures recommended by the higher maturity levels of the Capability Maturity Model® (CMM®) and the CMM IntegrationSM (CMMI®) depends on understanding the silent links connecting them to practices associated with Level 2. Certain activities that can seem peripheral to Level 2 goals during an assessment, in fact, prepare organizational foundations for what will become fundamental improvements. In trying to get through Level 2 as quickly as possible and neglecting the global logic of the CMM and the CMMI, companies sidestep the momentum-builders that can catapult them to world-class status. Perhaps the most significant illustration of this phenomenon concerns the function of peer reviews and the procedures associated with detecting defects early. The success of using peer reviews can vary widely. Many companies start to use peer reviews and then abandon them. These companies introduced formal training, but it did not help — within a year or two, very few if any projects were still actively doing peer reviews. Other companies swear by peer reviews, and boast that “they have saved us millions of dollars.” So why do peer reviews work in some companies and not in others? And what difference does it make? The answers have to do with organizational culture. All of this could be gleaned from reading the Software Engineering Institute’s Capability Maturity Model® (CMM®)/CMM IntegrationSM (CMMI®). But you need to read between the lines, since the CMM and CMMI enumerate necessary tasks but do not always describe the logic that sequences them. Part of this hidden logic involves the fact that moving toward and achieving Level 2 involves a general organizational discipline that recognizes and deals with problems early, accepts independent quality reviews, and promotes discomfort when quality procedures are missing. This cultural change affects far more than the tasks specifically identified in Level 2, and it is essential for getting the most out of, for example, peer reviews. Although some companies seem to be able to assemble this kind of discipline without having all the pieces of Level 2 in place (for example, if they have previously employed other kinds of quality programs such as Crosby), this kind of discipline amounts to having all the practices of Level 2 in place. Level 2 has to do with management discipline. Most Level 1 managers cannot protect their workers because their process is too chaotic. Without such protection, workers do not have the freedom to perform peer reviews effectively. The Inner Logic of the CMM/CMMI: Technical Progress Conditions Cultural Discipline The CMM and CMMI enumerate necessary tasks but do not always describe the logic that sequences them. Both models assume the importance of detecting defects early and then preventing them, yet these goals are not spelled out in the early stages of the maturity scale. At Level 2, all the process areas/key process areas ostensively concern project management activities — risk assessment, creating consistent processes, etc. Technical Culture and Organizational Culture Technical culture in this article is defined as the sum of an organization’s technical practices and methodologies. Changing the technical culture involves instituting better practices, or organizing them in a different sequence. It involves what employees do, not why they do it. Organizational culture deals with the underlying values that motivate individuals as they relate to an organization and its present and future goals. In the words of Harrison Trice and Janice Beyer, cultures consist of: ... shared sets of beliefs, values, and norms that both impel people to action and justify their actions to themselves and others. With the passage of time, [these sets of beliefs] tend to move away from the forefront of people’s attention and become implicit and taken for granted. [1] Why Maturity Levels Cannot Be Skipped Process capability grows in stages. Key processes are only effective after prerequisite processes are stabilized. Engineering processes usually do not improve, for example, before management stabilizes the way it makes decisions. If management changes the work conditions day to day or week to week, the best processes in the world do not have a chance to succeed. Therefore, Level 2 is largely concerned with management decision processes. Further, as management discipline solidifies, so does a more general quality discipline [2]. In technical terms, at Level 2, managers learn to prepare estimates with their team rather than by themselves and methodically track actual estimates against original estimates. These actions constitute an important increase in technical rigor. They also, however, involve changing perspectives as well as changing practices. Managers are empowered by enhanced information to take corrective action early rather than late, and get into the habit of doing so when they need to. When costly problems are found in reviews, and fixed early and easily, teams start to see the benefit of independent and methodical reviewing and begin to feel discomfort when consistent processes are missing. In other words, changes at Level 2 not only alter what people do but also how they think about it, that is, they substantively alter organizational culture. The big picture looks like this: When all members of the project are involved in planning activities, the whole team has to come to a consensus about goals and necessary quality standards in the product and the process. This can be a slow and bruising process, but it can happen in a timely manner with the proper culture and team participation. Reaching a consensus means the entire team buys in. People are less afraid to raise problems because they have survived an open discussion, and because their first prior- ity is to fix things before it is too late. Quality comes before blame. (This is sometimes called *decriminalization.*) A culture in which problems are handled early – without the fear of blame – also accepts independent review without defensiveness. How does all this happen? Where does it lead? **Changing the Technical Culture for Defect Detection** One of the most powerful payoffs of the CMM and the CMMI has to do with the savings made possible by finding and fixing defects before testing (the technique that is used is called peer reviews in both the CMM and CMMI). Peer reviews offer huge savings when done correctly. For example, to find and fix a defect before testing costs only one percent of what it would cost to fix the same defect in operations. That is, to find and fix one defect found early in development might cost $100. To find and fix the same defect during integration and test can cost $1,000 to $2,000. And to find and fix the same defect post-delivery costs an organization anywhere from $10,000 to $20,000. (Fixing critical defects found post-delivery can cost much, much more [3]). Today, software developers expect to find at least three to six post-delivery defects per thousand lines of code [4]. That means a loss in the range of $50,000 to $100,000 in unnecessary costs per thousand lines of code. For a typical system that contains millions of lines of code, the unnecessary costs that can be saved are astronomical. An operational defect, defined as a defect encountered by the product user as a failure, causes the product to malfunction relative to the product specification. (If it does not do what the user wants, it does not work.) Since many projects now consist of anywhere between 250,000 and millions of lines of code (with programs getting more complex every day), the real costs of quality are enormous, and the real benefits of process improvement are equally high – the potential saving of hundreds of millions of dollars of preventable costs. Levels 4 and 5 build naturally on the technical and organizational cultures conditioned by Levels 2 and 3. But peer reviews require not only a management discipline but also a cultural discipline. This kind of developing cultural discipline forms an essential element of the CMM/CMMI program of maturity. **Why Defect Detection Does Not Work Without Level 3 Maturity: Doing Peer Reviews in an Immature Organization** Even when they seem to be doing so, teams without a culture of cooperation do not really look for operational defects. Managers who have not internalized the culture of quality scare staff away from discussing problems by quickly assigning blame. Lacking the technical discipline of planning and monitoring and control procedures, they too often rush to drop quality procedures when schedules are slipping. Their subordinates pick up these signals and act accordingly. Finding too many defects might mean that they will be blamed for not doing their job properly. Rifkin states, > If we fear for our jobs then we are less likely to take the chances that are inherent in performing some new action, making the inevitable mistakes. We would fear that such mistakes would count against us, and we may form a basis for poor performance and then we could lose our jobs. [5] An operational defect, encountered by the product user as a failure, causes the product to malfunction relative to the product specification. Of course, not all defects are equally disabling. Critical defects render a product unusable and require immediate attention. In the case of serious defects, the customer's use is severely restricted. Defects of medium severity involve limitations that are not critical to overall operations. Low severity defects permit users to circumvent the problem and use the product with slight inconvenience. For peer reviews, a determination must be made between major defects and minor defects. Critical and serious defects would be considered major defects, medium severity could be either major or minor depending on the nature of the defect, and low severity defects would fall under the category of minor defects [6]. In a Level 1 organization, finding a few defects (no matter how many more there were or whether the critical ones were caught) is good enough. Finding them will *impress the boss*. If too many are found, the boss will think that “we are not very good at our jobs.” The same attitudes shape the way teams in a Level 1 organization conduct peer reviews. Managers who do not understand the culture of quality scare staff away from discussing problems. They then do not raise them because they are afraid they will be blamed for them – or for slowing down the schedule by raising them. Without real changes in organizational discipline, peer reviews typically result in only one operational defect detected per review. Consider this example. On one project, the project manager of organization X (which was Level 1) mandated that every development team use formal inspections. One team manager was sure he really did not need to do this since his team did not make mistakes (and even if they did, no one would know about them). But since he had to do it anyway, he decided to implement the order in the following way. He told the project manager his team did not have time to be trained. They would have to read the material on their own and would be directed to perform the formal inspections on Saturdays. Needless to say his team inspection defect rate was very low. But since there was no one on the project regularly reviewing the inspection data as it was produced, this team manager was allowed to continue with his practice. When the system went into testing, over 60 percent of the defects found were from this one team's modules. It slowed the entire project schedule down by over three months, and cost the project $200,000. (Remember, the difference between one defect found in inspections versus testing is approximately $100 versus $1,000.) Worse yet, after peer reviews produce disappointing results, companies may get discouraged and adopt a resistance to improvement that places them farther away from improved productivity than they were before. **The Cost of Doing Peer Reviews Without a Mature Organizational Culture** Organizations quickly understand how doing peer reviews can save vast amounts of money. They less frequently see the point of the intermediate activities that really make peer reviews work. Getting to Level 2 can seem to take forever, and instituting Level 2 activities can often seem pointless. In the meantime people wonder why they cannot implement more radical techniques right away. “Why wait for Level 3 to do peer reviews?” they ask. “What’s the use of all the tinkering the CMM/CMMI requires beforehand?” “Why do you need to progress through Maturity Levels?” “Why not just do those things that provide a real payoff?” Alternatively, organizations often try to get away with attaining Level 2 with only a cursory independent quality review in place. Consequently, their organizations do not develop a culture that is aware of the importance of finding problems early. Organizations also sometimes delay putting in place substantive measures to aid tracking critical elements at critical times. (For example, they estimate lines of code before they have done requirements and then collect no actual data.) Hence, their numbers give no early warning during the requirements and design phases, and the organizations delay developing a culture in which identifying issues early is positively reinforced. The result: management remains in crisis management mode rather than in a proactive mode. But teams without a culture of cooperation cannot operate critical defects because they do not really know how to look for them. More precisely, they are not equipped as a culture to look for them. Without the management and cultural discipline conditioned by Level 2 activities, peer reviews produce derisory results. Hewlett Packard, we know, took 10 years to reach a 25 percent adoption level [7] because they did not have a Level 2 cultural discipline in place. The resulting discouragement usually leads to companies bowing to ever-present resistance to continuing process improvement. Once staff turns against peer reviews, they will not attempt them at all, and they hesitate to adopt further improvement measures. Nor do most managers understand enough to explain what has happened. All that anyone sees is wasted effort and unrealized savings. Implications for Senior Managers: Assessments Senior managers as well as mid-level managers need to be aware of the technical and the cultural implications of the CMM/CMMI. They need to understand the value of a process and measurements that gives them real visibility early in the developmental process and allows them to be proactive rather than reactive. Being proactive is the key to quality. Trice and Beyer state that, In order to manage cultures of work organizations successfully, managers must (1) be culturally aware — that is, they must understand and take into account what culture is and how it works; (2) know the cultures they are managing; (3) recognize and use the levers they have available to influence their organizations’ cultures; (4) resolve the ethical dilemmas involved in managing cultures; and (5) be clear about whether they seek to maintain existing cultures, change existing cultures, or establish new ones. If managers understand the nature of culture, they will be better able to recognize the opportunities and constraints it poses for managerial action. [8] In other words, executives are key to the success of implementing change (which is never merely technical change). Without executive vision, positive change is unlikely to occur. Assessments are an effective method for management and practitioners to get expert insight into the organization’s maturity and culture. Senior managers should not put too much stress on the numerical grade of an assessment and should stress instead an assessment’s salutary stimulation. Organizations sometimes try to game an assessment, which sidesteps the self-reflection that leads to real change and hinders the growth of cultural discipline that will generate the major benefits to come. Pretending things are better than they are does not improve things; only laying firm foundations helps. An organization’s emphasis should not be “How badly did we do?” “Are we still at Level 1?,” or “Who is to blame?” Rather it should ask: “What aren’t we doing right and how can we fix it?” Asking these questions is already a big step toward higher maturity. Always, the greatest payoff is in heightened self-consciousness and the self-discipline that goes with it. With self-discipline the big payoffs later on are easy. Without it, they are nearly impossible [9]. Going from Level 1 to Level 2 the right way forces everyone in the organization to be more self-conscious. Middle and project managers begin to understand what to look for, what to ask for, and what the answers mean. Managers have real information and people become less frustrated. Once managers can see the road ahead, their expectations become more realistic, and they seek to maintain existing cultures, or establish new ones. If managers understand the nature of culture, they will be better able to recognize the opportunities and constraints it poses for managerial action. [8] Implications for Senior Executives: The Bottom Line Without the hands-on and technically informed input of executives, the big decisions (not to game an assessment, to take the recommendations that come out of an assessment seriously) do not get implemented. And unless they are implemented, nothing changes. To make this kind of decision with confidence, senior managers need to understand the huge payoff in profit margin when defects are caught or prevented before testing, and how these payoffs are tied to a changed organizational culture. Unless they personally understand the way a culture of cooperation and discipline evolves through the levels of process improvement, their organization will inevitably take all the easy ways out. Being world class brings enormous <table> <thead> <tr> <th>Name of Level 5 Assessed Company</th> <th>Quality Improvement</th> <th>Productivity/ Profit Improvement</th> <th>Predictability Improvement</th> <th>Customer Satisfaction</th> </tr> </thead> <tbody> <tr> <td>Telcordia Technologies</td> <td>35-40 percent higher than in 1997 and profit margin substantially higher.</td> <td>Projects took two years.</td> <td>No information available.</td> <td>No information available.</td> </tr> <tr> <td>Motorola India</td> <td>Improved by 16 percent moving from Level 3 to Level 5.</td> <td>On-time schedule adherence has improved from 75 percent in 1993 to 95 percent in 1997.</td> <td>No information available.</td> <td>No information available.</td> </tr> <tr> <td>BAESYSTEMS, CNI Division</td> <td>Defects halved over two years.</td> <td>External Customer Satisfaction improved 9 percent in the past year.</td> <td>No information available.</td> <td>No information available.</td> </tr> </tbody> </table> Table 1: Results From Companies That Have Changed Their Culture rewards. The charts in Table 1 illustrate four Level 5 organizations and their reported benefits. It should be noted that these organizations are in different businesses, have different product lines, and in general have different business concerns. Yet the numbers show the same order of results. Conclusion Peer reviews as prescribed at Level 3 by both the CMM and the CMMI are immensely profitable, but only if they are done right. When attempted too soon in a process improvement program, they not only can disappoint but also prove counterproductive. (The disappointment is so great that it interferes with further process improvement.) Knowing when to perform peer reviews depends on understanding the silent links between practices associated with Level 2 and Level 3 of the CMM/CMMI improvement programs. Certain activities that seem peripheral to Level 2 goals, in fact, prepare the cultural foundations for more sophisticated activities. In trying to get through Level 2 as quickly as possible and neglecting the global logic of the CMM/CMMI, companies sidestep the momentum-builders that can catapult them to world-class status. This paper has discussed what some of these submerged links are. References Notes 1. Peer reviews in the CMM and CMMI concern the defect detection, removal, correction, and verification process carried out by small groups during the pre-test phases of the development life cycle. The primary objective of peer reviews is to remove defects early in the development process. Peer reviews supplement, not substitute for major milestone reviews. A trained moderator and a group of developers (limited to about four to six people) draw from the area of the life cycle being completed to carry out peer reviews. Everyone participating should have a vested interest in the work product. Peer reviews should never be used as a tool to evaluate workers or assign blame for defects. Team members, after undertaking special training, are assigned specific roles (for example, author, reader, recorder, moderator, etc.) Checklists of questions derived from previous experience are used to fine-tune defect finding. The checklist is regularly updated. Afterwards, statistics on the number and types of defects found and the time expended by engineers on peer reviews are kept as a historical database for later trend analysis. Peer reviews enhance the development life cycle by creating shorter feedback loops. They are not tied to any specific methodology or tool. They are usually done at the end of the following phases of the development life cycle: system requirements, functional design, software requirements, architectural design, detailed design, source code, test plan, and test specification. 2. Although these figures come from a 1990 study, and no more recent study is available, their accuracy has been informally confirmed in work with dozens of companies through 2003. 3. Presentation by A. Warman at GEC Marconi SPIRE 99. About the Author Marilyn Bush is an independent management consultant who specializes in working with executive managers. She is one of the authors of “The Capability Maturity Model: Guidelines for Improving the Software Process” and the Software Engineering Institute’s (SEI) Capability Maturity Model® (CMM®) Introductory Course, and is currently co-authoring a book on assessments. As a visiting scientist at the SEI, she helped revamp its CMM-Based Appraisal for Internal Process Improvement Assessment Method and Lead Assessor Course. She is a transition partner for the CMM Integration™ (CMMI®) and is authorized to lead CMMI assessments (SCAMPI) and to teach the SEI Introduction to the CMMI. Bush, who divides her time between the United States and Europe, is an expert on how European and American software practices overlap and diverge. Marilyn Bush Associates 8037 Seminole AVE Philadelphia, PA 19118 Phone and Fax: (215) 248-5391 United Kingdom: 39 ST Giles Oxford OX1 3LW Phone and Fax: 44 1865 512289 E-mail: m.w.bush@ieee.org
{"Source-Url": "http://www.crosstalkonline.org/storage/issue-archives/2004/200403/200403-Bush.pdf", "len_cl100k_base": 4637, "olmocr-version": "0.1.53", "pdf-total-pages": 4, "total-fallback-pages": 0, "total-input-tokens": 14307, "total-output-tokens": 5122, "length": "2e12", "weborganizer": {"__label__adult": 0.0003893375396728515, "__label__art_design": 0.0006279945373535156, "__label__crime_law": 0.0004508495330810547, "__label__education_jobs": 0.00943756103515625, "__label__entertainment": 8.344650268554688e-05, "__label__fashion_beauty": 0.00020170211791992188, "__label__finance_business": 0.0075836181640625, "__label__food_dining": 0.0005097389221191406, "__label__games": 0.0005345344543457031, "__label__hardware": 0.0005483627319335938, "__label__health": 0.0005521774291992188, "__label__history": 0.0002655982971191406, "__label__home_hobbies": 0.00019299983978271484, "__label__industrial": 0.0006155967712402344, "__label__literature": 0.00038743019104003906, "__label__politics": 0.0003657341003417969, "__label__religion": 0.00041294097900390625, "__label__science_tech": 0.00905609130859375, "__label__social_life": 0.00023174285888671875, "__label__software": 0.01114654541015625, "__label__software_dev": 0.955078125, "__label__sports_fitness": 0.00035858154296875, "__label__transportation": 0.0004901885986328125, "__label__travel": 0.0002543926239013672}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 24015, 0.02763]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 24015, 0.40924]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 24015, 0.95694]], "google_gemma-3-12b-it_contains_pii": [[0, 5921, false], [5921, 12768, null], [12768, 19167, null], [19167, 24015, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5921, true], [5921, 12768, null], [12768, 19167, null], [19167, 24015, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 24015, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 24015, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 24015, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 24015, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 24015, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 24015, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 24015, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 24015, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 24015, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 24015, null]], "pdf_page_numbers": [[0, 5921, 1], [5921, 12768, 2], [12768, 19167, 3], [19167, 24015, 4]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 24015, 0.05747]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
3492b5f9cd2796b096a7d77ba25bcd37918018f8
Index Symbols 3-D based figurative 385 3D CAD 385, 393 3D CAD system 385 5-dimensional grid 31 (GRAI) model 256 ε-constraint method 98, 106, 107 A abstract holistic 233 accounting information system (AIS) 82 ACM 503, 511, 512, 515, 517, 550 act global 291, 293 Action Workflow 66 Action Workflow approach 66 Activity Flow 43, 50, 51 ad-hoc 38 ad-hoc user-input 38 agent-based modeling (ABM) 436, 438 Aggregated Production Planning (APP) 180 AMENETIES method 259 AMENETIES methodology structures 255 analytic hierarchy process (AHP) 98 Analytic Network Process-ANP 97 AndroMDA 222, 229, 516 ANP Model 103, 104 anti-spyware tools 297 APO system 189 Application Lifecycle Management 232, 233, 249 Archimedean Goal Programming (AGP) 107 architectural planning 1 architecture 356, 359, 360, 361, 376, 378, 516, 518, 519, 549 architecture models 234 Architecture of Integrated Information Systems (ARIS) 176 ARIS 357 artifacts 215, 218, 219, 220, 221, 225, 228, 229 Artificial Neural Network (ANN) 109 artificial energy 331 artificial intelligence (AI) 97, 436, 331, 337, 347 Artificial Intelligence Based Models 97 Asset Development Model 45 B background 416, 419 BAT 66, 79, 526 Bertalanffian type 410 bill of material processing (BOMP) 11 BIM base 394 bio-mimicry 330, 331, 338 BPML model 172 BPMN 64, 65 BPR projects 373 Building Information Modeling (BIM) 394 business component architecture (BCA) 1, 25 Business Component Architecture (BCA) 1, 22 business enterprises 8 business mode 115 business models 81 Business Process Integration (BPI) 19 business process modelling (BPM) 173 business process modelling language (BPML) 172 business quality 400 Index Business-to-Business (B2B) 479 Business-to-Consumer (B2C) 479 C CADD 19 CAM 6, 12, 19 CAP 19 Capability Maturity Model (CMM) 32, 54, 55 Capacity Planning using Capacity Bills (CPCB) 183 Capacity Planning using Overall Factors (CPOF) 183 Capacity Planning Using Resource Profiles (CPRP) 183 Capacity Requirements Planning (CRP) 184 CAPP 19 Case-based-reasoning (CBR) 97 Case-based-reasoning (CBR) systems 97 CASE tools 263, 270, 541 causal loop modelling (CLM) 352, 365 cautious headway 330 centers of gravity (COG) 439 Central Computer and Telecommunications Agency (CCTA) 47 Chief Information Officers (CIO) 6, 12 CIMOSA 518, 357, 358, 360, 361, 527, 367, 531, 370, 371, 376, 377, 378, 550, 377 CIMOSA modelling framework 173 CIM systems 359, 360 CITI firm 115 cloud computing 1, 2, 4, 8 Cluster Analysis (CA) 96 COBRA 20 coders 40 cognitive approach 137, 153, 154 cognitive revolution 331, 346, 347 collaboration 272, 286, 287 collaborative ecosystem 290, 291, 292, 296 collaborative paradigm 294, 296, 307 Collaborative Work Systems (CWS) 144 COMIS 256, 257, 258, 259, 260, 269 COMIS methodology cycle 257 commercial process models 36, 45 Common Object Request Broker Architecture (CORBA) 177 communications tools 293 Community of Practice (CoP) 86 complex information technology-intensive (CITI) 114, 116 computer-aided design (3D CAD) 385 Computer-aided Publishing 19 computer information systems (CIS) 11 Computer Security Institute (CSI) 296 centric diagram 343 Concurrent Engineering (CE) 382 Conic Scalarization Method (CSM) 94, 107 conservation of information (COI) 435, 436, 439, 457 Conservation of Information (COI) 436, 457 textual data 232, 234, 235, 236, 237, 238, 239, 249 Control Design Pattern 242 Control Flow 177 collection-oriented perspective 63, 64, 65, 66, 68, 75, 78, 79 CRM 477, 479, 480, 481, 521, 528, 490, 491, 530, 492, 531, 495, 535 cultural conditions 332 customer-focused 480 Customer Relationship Management (CRM) 477, 480, 489 Customer-to-Business (C2B) 479 Cybernetics 5, 29, 30, 521, 549 cyberspace 3 D Data Envelopment Analysis (DEA) 96 data flow diagrams 35, 40 DC3 Algorithm 242, 243 DEA method 96 delivery structure 219 DEMO 66 DEMO approach 66 dendrogram 239, 240, 241, 242 Department of Defense (DOD) 7 Department of Energy (DOE) 435 DERN project 459, 472 design diagrams 220, 225 designers 40 design phase 259 development process 32, 33, 39, 41, 43, 46, 47, 48, 50, 53, 55, 56 Index Dialectical System Theory (DST) 401 Digital Enterprise Research Network 459 discrete event simulation (DES) 363, 364 Disjunctive and Lexicographical Screening 96 distributed hash table (DHT) 248 DOE 435, 440 Domain Knowledge 138 domain processes (DPs) 360, 362 Domain-specific Languages (DSL) 220 DOS 298, 299 Double-Loop Learning 287 DST 401, 402, 404, 405, 409 E Eclipse platform 222 Eclipse Process Framework (EPF) 215 economic nature 128 e-governance 298 EIS metrics 435, 438 EIS system 315, 435, 436, 442, 445, 457 enterprise 415, 416, 418, 419, 420, 422, 423, 424, 526, 428, 429, 430, 431 Enterprise Application Integration (EAI) 19, 25 Enterprise Architecture 6, 7, 8 Enterprise Engineering context 240 enterprise engineering (EE) 355 enterprise functional architecture (EFA) 1, 16 enterprise information architecture (EIA) 1, 19 enterprise information infrastructure (EII) 1, 13, 27 enterprise information system (EIS) 108, 273, 283, 313, 415 Enterprise Integration Ontologies 238 enterprise model 356, 357 enterprise modelling (EM) 352, 365 Enterprise Network Architecture (ENA) 1, 20 Enterprise Organization Architecture (EOA) 1 Enterprise Platforms 232, 233, 235, 236, 237, 239, 249 Enterprise Processive Architecture (EPA) 1 Enterprise Resource Planning systems (ERP) 6, 145 enterprise service architecture (ESA) 1 enterprise software 232, 233, 234, 235, 237, 247, 248, 249, 250 Enterprise Software Industry 233 enterprise systems 1, 2, 4, 5, 6, 8, 9, 12, 13, 14, 22, 28 enterprise systems (ES) 8 enterprise systems portfolio 2 Enterprise Tomograph Delta Operator 240, 241 Enterprise Tomography 232, 233, 235, 236, 237, 238, 241, 249, 250 ERP 386, 388, 477, 479, 480, 528, 489, 490, 494, 533, 495, 538, 539, 540, 543, 547 ERP legacy system 90 ERP systems 200 ES architect 10, 11, 16 ES architecture 1, 8, 9, 13 European culture 331 EVA system 189 Event-driven Architecture (EDA) 22 EWF-net 176 Executive Information Systems (EIS) 478 EXINUS 264, 265, 266, 267 Extended Workflow Nets (EWF) 176 F Facebook 290, 307 G Genetic Algorithms (GA) 109 German V-Modell 47 GET 288 Getting Things done-method (GTD) 222 Index GIM methodology 359 global competitiveness 308 global economy 81, 82 global environment 13 global/no-global dilemma 332 goal programming (GP) 93, 94 governance structure 388 GRAI approach 359 GRAI/GIM 357 GRAI modelling framework 359 graphical capture 361 graphical interface 63 Greco-military principles 117 gross requirements (GR) 182 H hardware function 307 HERMES method 45 hierarchical production planning 174, 184, 187, 191, 192, 535 holism 401, 402, 519, 407, 409, 410, 411, 412, 413, 537 holistic production management 340 Holsapple & Joshi model 142 hospital departments 323 human activity systems (HAS) 283 Human-Computer Interface 46 human intervention 380, 388, 392 human resources 290, 308 hypertext transfer protocol (HTTP) 288 I ICT 379, 380, 381, 382, 383, 386, 387, 388, 391, 392, 393, 395 ICT system 275 IDEF0 357, 358, 359 IIDP 401, 402, 403, 404, 406, 407, 409, 411, 412 indexing techniques 232 industrialism 329, 330, 331, 332, 345, 346 industrial revolution 331, 332, 333, 340, 343, 345, 346 industry economics 338 Inference Knowledge 138 information and communication technologies (ICTs) 81, 380 information and communication technology (ICT) 275 Information and Communication Technology (ICT) 31 information ecosystem 291, 292, 296, 297, 298, 300, 301, 303, 306, 307 information-flow model 283 information security 291, 292, 296, 297, 298, 300, 302, 303, 307, 308 information system architecture 359 information system (IS) 252, 273 information system planning model 309 Information Systems (IS) equipment 446 information systems planning models 290, 291, 308 information systems solutions 290 information technology-centric new economy 113 Information Technology (IT) 415 Information Technology Services (ITS) 447 input, control, output & mechanism (ICOM) 358 Institute for Enterprise Architecture Developments (IFead) 7 intangible assets 459, 462, 469, 470 intangible-based view 462, 463 integration context 242 Integration ontology mining algorithms 242 Interaction computer-human 264 Interactive Weighted Tchebycheff Procedure (IWTP) 105 Inter-Delta Operator 247 inter-organizational framework 66 inter-organizational knowledge environments 273 interpersonal communication 379, 380, 382, 383, 387, 388, 395 intra-enterprise training 459 invention-innovation-diffusion 400, 401 invention-innovation-diffusion process (IIDP) 401 IT 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 127, 128, 129, 130, 131 IT-driven enterprise 2, 28 IT-enabled customer 160 IT-infrastructure 217 IT solutions 2, 28 IT systems 2 K knowledge assets 462, 467, 469 Knowledge Based Systems (KBS) 137, 144 knowledge-based theory 462 knowledge-based view 462 Knowledge Management (KM) 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 145, 146, 147, 148, 150, 153, 154 knowledge networks 272, 275, 277, 281, 284 Knowledge resources 275 knowledge sharing 272, 273, 275, 276, 277, 278, 281 L Learning Organization 274, 288 legacy system 90 life cycle 42, 45, 46, 57, 59, 60, 145, 146, 153, 529 life-cycle 84 linear programming (LP) 93, 94 LMS systems 469 Local Area Networks (LANs) 166 local government 421 lock mechanism 246 M majority rules (MR) 440 Management Information Systems (MIS) 478 Mandarin language 336 manufacturing enterprises (MEs) 352 Market of Resources 194, 195, 199, 201, 52 3, 202, 203, 204, 206, 207, 209 Marx vision 82 Master Production Scheduling (MPS) 180 materials requirements planning (MRP) 181 Mathematical Programming Models 97 MDRC 434, 439, 440, 441, 442, 443, 449, 450, 451, 453 MDRCs (Medical Department Research Training Center) 439 medical department research centers (MDRC) 434 Meta-CASE tool based 254 meta-institution 201 metamodel-based process 35, 51 metamodel-based process models 51 metamodels 35, 53 method-based OD&C 355 Method knowledge 138 methodology 134, 136, 141, 146, 153, 154, 404, 407, 409, 410, 413, 537 metric-based scalarizing programs 108 Microsoft 87, 88 Microsoft Dynamics 20 Microsoft Excel-sheets 222 Microsoft Outlook 222 Microsoft Project 222 Microsoft SharePoint Server 222 Microsoft Solutions Framework (MSF) 215 Microsoft Visual Studio 218, 224, 226 military large-scale systems 5 mining algorithm 242, 243 Mintzberg’s dynamic organigram framework 121 mixed integer non-linear programming (MIN- LP) 93, 94 mixed integer programming (MIP) 93, 94 model a system 358 model exchange, 222 Modeling tools 220 modern large-scale organisations 415 MPI Expertise 503 MRP technique 182, 190 MS Dynamics 4, 20 multi-criteria 93, 94, 95, 97, 98, 112 multi-phase process 31 multi-product environments 100, 104 MySpace 298, 307 N net requirements (NR) 182 networked economy 82, 84 Networking 194, 196, 198, 209, 522 non-linear programming (NLP), 93, 94 NP-complete 243 O Object Management Group (OMG) 222 Index OD&C 353, 354, 355, 363, 364, 373, 374, 375 OD&C practice 355 ODT 225 OMIS 272, 273, 274, 277, 278, 279, 283, 287, 288 OMIS environment 272 Online Analytical Processing (OLAP) 481 Ontology Mining Algorithms 242 OPEN Process Framework (OPF) 214 open-source software 290 operational environment (OE) 1 Operation Iraqi Freedom (OIF) 439 orchestration-oriented perspective 64, 65, 73, 75, 78 organizational hierarchy 478 organizational memory information system (OMIS) 272, 274, 278 organizational memory (OM) 273, 278 organizational structure 219 Organizational Theory and COI 438 organization ecosystem 289, 298, 300, 304, 308, 309 Original Equipment Manufacturers (OEM’s) 200 P P2P network 247, 248 paper-based process 82 parsimony 329, 330 PAT Array 235, 241, 242, 243, 245, 246 peer-to-peer manner 200 People-Oriented Business Process Notation 63, 64 PERA 357, 358, 359 period model 98 Personal Software Process (PSP) 222 physical model 259 planned orders (PO) 182 planning model 291, 292, 301, 302, 304, 309 PPC process 188 pragmatic vantage point 115 PRBP 68, 69, 70, 72, 73, 75, 76, 77 preemptive goal programming (PGP) 98 Process-AHP 97 Process-aware tools 217, 218, 221, 222 process model 31, 32, 33, 34, 35, 36, 37, 38, 41, 42, 46, 47, 532, 48, 49, 51, 52, 53, 54, 55, 56, 57, 60, 61, 62, 546, 215, 217, 219, 221, 225, 226, 230, 60 process model metadata 226 Product Development Model 45 Product information Systems (PIS) 19 production-consumption dichotomy 117 production planning 179, 188, 189, 191 production planning and control (PPC) 172 Product Management systems (PM) 145 project management method 222 Prominent Process Models 32 public organisations 418, 421 purchase requisition (PR) 64 R RAND Corporation 5 Rational Unified Process (RUP) 38, 47, 215 R&D 82 real-life supplier 94, 105 reconfiguration dynamics 194, 195, 196, 197, 198, 207, 208 reengineering 252, 253, 260, 261, 264, 266, 271, 549 Relational Databases (RDBs) 143 remote procedure calls (RPC) 219 resource systems 353, 354, 357, 360, 361, 364, 365, 366, 367, 370, 373, 374 reverse engineering techniques 253, 264 RIA 298, 299 RLTP methods 106 Ronald Coase 113, 115 root node 240, 246 RTF 225 RUP 215, 218, 226, 228 RUP collapses Specification and Design 41 S SADT 358 Schekkerman Model of Enterprise Architecture 7 <table> <thead> <tr> <th>SCM</th> <th>6, 13, 19, 22</th> </tr> </thead> <tbody> <tr> <td>SCRUM teams</td> <td>233, 237, 238, 239</td> </tr> <tr> <td>semantic context</td> <td>88, 89</td> </tr> <tr> <td>semi-automatic environment</td> <td>233</td> </tr> <tr> <td>semi-structured information</td> <td>135</td> </tr> <tr> <td>service-oriented architecture (SOA)</td> <td>1, 20</td> </tr> <tr> <td>signal detection theory (SDT)</td> <td>436, 457</td> </tr> <tr> <td>simple information technology-intensive (SITI)</td> <td>116</td> </tr> <tr> <td>simulated annealing (SA)</td> <td>109</td> </tr> <tr> <td>simulation modelling (SM)</td> <td>352, 365</td> </tr> <tr> <td>Single European Electronic Market (SEEM)</td> <td>200</td> </tr> <tr> <td>small and medium enterprises (SME)</td> <td>213</td> </tr> <tr> <td>SMEs</td> <td>232</td> </tr> <tr> <td>social dynamics in sociology</td> <td>5</td> </tr> <tr> <td>social entrepreneurship</td> <td>131</td> </tr> <tr> <td>social network</td> <td>275</td> </tr> <tr> <td>society</td> <td>82, 90</td> </tr> <tr> <td>socio-economic</td> <td>118, 119, 128</td> </tr> <tr> <td>software</td> <td>81, 82, 83, 518, 84, 85, 87, 523, 90, 91, 292, 294, 298, 299, 300, 301, 305, 307, 533, 310</td> </tr> <tr> <td>software artifact</td> <td>31</td> </tr> <tr> <td>software components</td> <td>90</td> </tr> <tr> <td>software development</td> <td>213, 214, 217, 218, 219, 220, 229, 230, 231, 521, 522, 542, 544</td> </tr> <tr> <td>Software development</td> <td>213, 216, 217</td> </tr> <tr> <td>software development project</td> <td>33, 39</td> </tr> <tr> <td>Software Engineering</td> <td>234, 250, 528</td> </tr> <tr> <td>Software Engineering Environment</td> <td>45, 53</td> </tr> <tr> <td>software engineering environments (SEE)</td> <td>213</td> </tr> <tr> <td>software fragments</td> <td>234, 236, 237, 240</td> </tr> <tr> <td>software landscape</td> <td>240</td> </tr> <tr> <td>Software Process Engineering Meta-Model (SPEM)</td> <td>215</td> </tr> <tr> <td>Software Process Models</td> <td>35, 51</td> </tr> <tr> <td>Software Project Control Centers (SPCC)</td> <td>221</td> </tr> <tr> <td>Solution Assessment (SA)</td> <td>8</td> </tr> <tr> <td>Solution logic (SL)</td> <td>8, 11</td> </tr> <tr> <td>SPEM</td> <td>35, 47, 52, 53</td> </tr> <tr> <td>state of the art (SR)</td> <td>11</td> </tr> <tr> <td>Statistical Models</td> <td>97</td> </tr> <tr> <td>Stock Management</td> <td>186</td> </tr> <tr> <td>structure</td> <td>214, 217, 218, 219, 225, 227, 229</td> </tr> <tr> <td>submodel</td> <td>41, 42, 44, 53</td> </tr> <tr> <td>sub-processes</td> <td>216</td> </tr> <tr> <td>subsystems</td> <td>37</td> </tr> <tr> <td>sub-tree</td> <td>239, 241</td> </tr> <tr> <td>Supply Chain Management systems (SCM)</td> <td>145</td> </tr> <tr> <td>supporting process models</td> <td>213</td> </tr> <tr> <td>Sustainable enterprise</td> <td>4, 27</td> </tr> <tr> <td>sustainable growth</td> <td>331, 346</td> </tr> <tr> <td>SWOT analysis</td> <td>148, 151, 152</td> </tr> <tr> <td>system engineering</td> <td>5</td> </tr> <tr> <td>Systemic/holistic</td> <td>410</td> </tr> <tr> <td>System participation model</td> <td>72, 73, 76</td> </tr> <tr> <td>systems engineering</td> <td>353</td> </tr> <tr> <td>T</td> <td></td> </tr> <tr> <td>table tops (TT)</td> <td>373</td> </tr> <tr> <td>tabu search (TS)</td> <td>109</td> </tr> <tr> <td>Task knowledge</td> <td>138</td> </tr> <tr> <td>Tchebycheff Metric-based Scalarizing Methods</td> <td>94</td> </tr> <tr> <td>teamwork process</td> <td>276</td> </tr> <tr> <td>technical orientation (TO)</td> <td>9, 11</td> </tr> <tr> <td>technological knowledge management</td> <td>134, 135, 136, 147, 148, 151, 154</td> </tr> <tr> <td>Technological solutions</td> <td>297</td> </tr> <tr> <td>technological strategy</td> <td>135, 146, 154</td> </tr> <tr> <td>Test Driven Development (TDD)</td> <td>236</td> </tr> <tr> <td>Test Driven Development (TDD) software</td> <td>236</td> </tr> <tr> <td>textual representation</td> <td>238</td> </tr> <tr> <td>thinking/behavior</td> <td>410</td> </tr> <tr> <td>thrifty society</td> <td>329</td> </tr> <tr> <td>TKM Objectives</td> <td>151</td> </tr> <tr> <td>TKM Project</td> <td>151</td> </tr> <tr> <td>TKM Strategies</td> <td>151</td> </tr> <tr> <td>TKM strategy</td> <td>151</td> </tr> <tr> <td>Tool infrastructure</td> <td>216</td> </tr> <tr> <td>top-level process model</td> <td>74, 78</td> </tr> <tr> <td>total value of purchasing (TVP)</td> <td>98</td> </tr> <tr> <td>traditional hierarchical bureaucracy</td> <td>121</td> </tr> <tr> <td>tree based formats</td> <td>237</td> </tr> <tr> <td>U</td> <td></td> </tr> <tr> <td>UI Objects</td> <td>237</td> </tr> </tbody> </table> Index UI software engineers 236 UML 35, 40, 45, 57, 61, 520 UML modeling 222 UML-profile 35 under frames (UDF) 373 unified modelling language (UML) 173 unsystematic 117 user’s operational environment 41 USOMID 404, 405, 406, 407, 409, 412, 413, 537 V value-creation enterprise 4 value shop model 273 VE Design 201, 202, 204, 205, 207 VE dynamic integration 201 VE model 195, 196, 197, 199, 200, 205, 206 Very Large Business Applications (VLBA) 232 virtual engineering (VE) 355 virtual enterprise 84, 85 Virtual Enterprise model 194 virtual enterprises 3 Virtual Enterprise (VE) 3, 194, 196 Virtual Industry Cluster (VIC) 200 virtualization 1, 3 Virtual Organization (VO) 3 Visual Studio 218, 223, 224, 226, 227 VLBA data universe 240, 242, 246 VLBA locations 241 VLBA software 234, 236, 238, 239, 240, 249 V-Model-97 45 V-Modell XT 214, 218, 219, 224, 225, 226, 230, 531 W WEB 1.0 290, 293, 294 Web 2.0 232, 236, 240, 289, 290, 293, 298, 310, 311, 519, 521, 527, 542, 54 web-based enterprise control 436 web-based system 441 web services 84, 88, 90 Wiki-based systems 218 wikinomics society 293 Wiki Technology 279, 288 Work Breakdown Structures (WBS) 149 workflow 252, 253, 254, 256, 520, 257, 258, 260, 261, 262, 263, 264, 266, 267, 268, 269, 270, 533, 271, 549 workflow and the systems of management workflow (WFMS) 253 workflow management system (WiMS) 252 workflow maps 256 workflow modelling (WFM) 365 workflows 253, 254, 257, 261, 263, 264, 266, 267, 269 work in process (WIP) 188 Work Product Dependency 43, 50 X XML Metadata Interchange (XMI) 223 Y YAWL language 176
{"Source-Url": "http://www.igi-global.com/pdf.aspx?ctid=17&ptid=923&t=index&tid=110596", "len_cl100k_base": 7055, "olmocr-version": "0.1.53", "pdf-total-pages": 8, "total-fallback-pages": 0, "total-input-tokens": 33821, "total-output-tokens": 9402, "length": "2e12", "weborganizer": {"__label__adult": 0.0005359649658203125, "__label__art_design": 0.0017185211181640625, "__label__crime_law": 0.0008120536804199219, "__label__education_jobs": 0.004505157470703125, "__label__entertainment": 0.00016820430755615234, "__label__fashion_beauty": 0.00025916099548339844, "__label__finance_business": 0.0106048583984375, "__label__food_dining": 0.0003829002380371094, "__label__games": 0.0014934539794921875, "__label__hardware": 0.0025005340576171875, "__label__health": 0.0005474090576171875, "__label__history": 0.001102447509765625, "__label__home_hobbies": 0.00035572052001953125, "__label__industrial": 0.003597259521484375, "__label__literature": 0.0007753372192382812, "__label__politics": 0.00039839744567871094, "__label__religion": 0.0005517005920410156, "__label__science_tech": 0.1929931640625, "__label__social_life": 0.00016891956329345703, "__label__software": 0.049835205078125, "__label__software_dev": 0.7255859375, "__label__sports_fitness": 0.00029087066650390625, "__label__transportation": 0.0007567405700683594, "__label__travel": 0.0003337860107421875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 18436, 0.18561]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 18436, 0.1339]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 18436, 0.61187]], "google_gemma-3-12b-it_contains_pii": [[0, 1656, false], [1656, 4089, null], [4089, 6658, null], [6658, 9162, null], [9162, 11440, null], [11440, 13840, null], [13840, 16778, null], [16778, 18436, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1656, true], [1656, 4089, null], [4089, 6658, null], [6658, 9162, null], [9162, 11440, null], [11440, 13840, null], [13840, 16778, null], [16778, 18436, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 18436, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 18436, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 18436, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 18436, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 18436, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 18436, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 18436, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 18436, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 18436, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 18436, null]], "pdf_page_numbers": [[0, 1656, 1], [1656, 4089, 2], [4089, 6658, 3], [6658, 9162, 4], [9162, 11440, 5], [11440, 13840, 6], [13840, 16778, 7], [16778, 18436, 8]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 18436, 0.14011]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
42aa5b14033e7a32d24028b77a25c4f95581408e
IMusic: a Bluetooth music application Angel Aguilera Manglano, Borja Sierra Espin Abstract — nowadays, we can see a huge amount of customized services in lots of applications. A more customized experience get a real full satisfaction to the customers. The project was born with the aim of providing this kind of service. Thus a client takes part in the decision- making of the local songs, creating a playlist with songs ordered as the customer’s data preferences. The way is easy: a customer who enters the premises, install the software that local provides and then he has to indicate their customer likes and get it transmitted via Bluetooth. This information is received by the customer attention server and it generates a playlist with personalized songs. Keywords— AI system, Bluetooth connection, customized music application, mobile interface. XIII. INTRODUCTION Music is found in every known culture since ancient times. The "oldest known song" was dated 4,000 years ago. The music has been varying wildly between times and places and it can be divided into genres in many different ways. The goal of the application we want to develop is to serve customized music to places such as pubs, restaurants, hotels to help these places to offer a better service for their customers, to make this possible we are going to use: technologies as Bluetooth to set up the connection between customers and the music server, genie and smile library to pair each customer with the music genre he fits better, and a .Net application to receive all the information for the creation of the playlist. XIV. FIRST STEP: HOW TO RECEIVE THE CUSTOMER’S LIKES? The first problem we face is how to get the application closer to the customers. All of us are living in the communication era so there are lots of ways to make the connection between the application and clients: The first idea was to set up a point of connection at the local - a few computers linked to the main server for example- so clients go and fill in a simple form with their musical likes. Another possibility was to allow a Wi-Fi access point which makes possible links of customers with their laptops. Once connected, they could be redirected at the local main page, and all they have to do is fill in the form provided. But those ideas are quite hardworking or uncomfortable to the clients, in one hand have to stay in line – on the case there is no free computers on the local- to get the likes transmitted in the other hand with the second idea they have to carry with the computer on and it’s a nonsense to go party with all of these gadgets. So if we want the application was successful we need to find the technology that fits those problems, and we found it on Bluetooth technology. The most of the cell phones nowadays works with Bluetooth, and if we can use this mobile devices, to get an access to the local main server we could solve the connection problem. Due to the fact that Bluetooth technology is a standardized wireless technology and it is designed to be compatible across a range of very different operating systems and devices, makes us to choose this alternative. XV. SECOND STEP: HOW TO DO AN APPLICATION FROM CUSTOMERS? A. Initial decisions We want a customer’s application that allows sending their musical likes and getting it received by the customers dedicated server. At first we choose to create a .Net technology server for attending all the Bluetooth connections from the customers. All Bluetooth libraries that we found on .Net are under subscription, and those libraries such “IntheHand.Net.Personal” free of charge doesn’t work properly because their implementation and options are very limited and do not provide many possible cases of communication in Bluetooth. Because of that we decided to develop a server with Java technology. The functionality of this server is basically listen Bluetooth connections and to store the content of these connections (saving them into a database). This java library is in the API JSR-82 and defines two packages that depend on the CLDC javax.microedition.io package: - javax.bluetooth: core Bluetooth API - javax.obex: APIs for the Object Exchange (OBEX) protocol These two packages are totally independent: - The first one defines classes and basic interfaces for the discovery of devices, service discovery, connection and communication. The communication through javax.bluetooth is at low level: through data streams or by providing arrays of bytes. - The second one handles the high-level OBEX protocol, this protocol is very similar to HTTP and is mainly used for exchanging files. The OBEX protocol is a standard developed by IrDA and is also used on other wireless technologies than Bluetooth. The main development platform for the API JSR-82 is J2ME. The API is designed to rely on the CLDC configuration, however there are implementations to use this API in J2SE. Regarding the client side we did not have any problem at all as most of the mobile work perfectly with MIDlets. “A MIDlet is a Java program for embedded devices (dedicated to a single activity), more specifically for the Java Virtual Machine MicroEdition (JavaME). Generally MIDlets are games and applications that runs on a mobile phone.” But regarding the customers dedicated server side we found the following problems: • In the detection phase, our own Bluetooth device which we will send and receive it doesn’t be detected by the javax.bluetooth library. After several days of searching we discovered the problem, it was because our Bluetooth device is using a Bluetooth stack protocol that is not included in the library we are working with. The USB Bluetooth device that we had was running with the Microsoft protocol stack and it wasn’t compatible with the library we used. Thus we had to remove the J2ME library and replace it with “bluecove-2.0.2.jar” which accepted the Microsoft protocol stack. This library contains all the protocols the other library has and many others protocols, so the coding was the same but this time it works. • In the discovery phase we don’t find any problems because both server and client java use the same Bluetooth technology for communication so the bluetooth profiles are the same, if there is no correlation between these profiles could not be exchanging information with another device. It is worth to comment that we had to alternatives for the communication due to the API javax.bluetooth makes possible two different ways of connection: SPP and L2CAP: o With SPP we get an InputStream and an OutputStream. o with L2CAP we get an array of object that we could send or receive We choose SPP. Once these 2 problems were solved, everything related to Bluetooth was swimmingly. B. Developing the customer application Programming on J2ME, and using the Bluetooth API (JSR 82), which provides a standardized API for using Bluetooth networking, we made the customer application possible. After the implementation the result was that we have a functionally interface which allows clients to connect their own phones with a java application that performs the task of storing the client’s form. The basic navigation structure of the mobile application is: And finally the structure we want to build is: Third Step: Build the Bayesian Network At the point of view of the local, in order to set the best playlist, the application needs to access the customer’s data forms to help the application choose the songs that fit the best. All we have to do is perform an application that arranges the songs on the right position of the playlist. This is possible with the help of Genie (Artificial Intelligence) application that compares all songs on the database with the statistics music likes of all the customers at the local. The result is a preference ordered playlist which begins to play. C. Genie Application The GeNi (Graphical Network Interface) software package can be used to create decision theoretic models intuitively using the graphical click-and-drop interface. GeNi is the graphical interface to SMILE, a fully portable Bayesian inference engine developed by the Decision Systems Laboratory and thoroughly tested in the field since 1998. GeNi 2.0 is the latest version of GeNi. GeNi 1.0, released to the community in 1998, has received a wide acceptance within both academia and industry. Users of the programs have shared with us their experiences and their suggestions have led to the development of GeNi 2.0. GeNi 2.0 has many more new features to offer. Primary Features: - Graphical editor to create and modify network models - Platform independent, versions available for Windows, Unix (Solaris), Linux, Mac, Pocket PC, etc. - SMILE.NET available for use with .NET framework. Compatible with all .NET languages, including C# and VB.NET. May be used to create web-based applications of Bayesian networks. - Thorough and complete documentation. - Responsive development team support, we will compile SMILE for your platform on demand. D. SMILE LIBRARY SMILE (Structural Modeling, Inference, and Learning Engine) is a fully platform independent library of C++ classes implementing graphical probabilistic and decision-theoretic models, such as Bayesian networks, influence diagrams, and structural equation models. Their individual class, defined in SMILE API (Application Programming Interface), allows you create, edit, save, and load graphical models, and use them for probabilistic reasoning and decision making under uncertainty. SMILE supports directly object-oriented methodology. SMILE is implemented in C++ in a platform independent fashion. Individual classes of SMILE are accessible from C++ or (as functions) from C programming languages. As most implementations of programming languages define a C interface, this makes SMILE accessible from practically any language on any system. SMILE can be embedded in programs that use graphical probabilistic models as their reasoning engines. Models developed in GeNi can be equipped with a user interface which utilizes SMILE as the backend engine. SMILE is released as a dynamic link library (DLL). There are also several SMILE wrappers, such as SMILE.NET (.NET interface), SMILEX (Active X), jSMILE (Java interface), etc. Primary Features: - Graphical editor to create and modify network models. - Platform independent, versions available for Windows, Unix (Solaris), Linux, Mac, Pocket PC, etc. - SMILE.NET available for use with .NET framework. Compatible with all .NET languages, including C# and VB.NET. May be used to create web-based applications of Bayesian networks. - Thorough and complete documentation. - Responsive development team support, we will compile SMILE for your platform on demand. E. Let’s build it! We’ve got 12 nodes on which we make the comparison between the received statistics likes of customer and the current songs stored on the database of the local We are going to explain the meaning of this tree structure: - The nodes with no circle surrounded means the attributes of the songs, such attributes as genre (“genero de canción”), length (“duración de canción”) and origin (“procedencia de canción”). This information is set on the nodes by “setEvidence” method, a method of the library that SMILE provides us. All the songs of the database have to get this attributes. - The nodes surrounded with blue circles mean the statistic information of all the customers who send the form with the Bluetooth customer application. The joint of these nodes ends on nodes surrounded with red circles called: appropriate genre (“genero apropiado”), appropriate length ("duración apropiada") and appropriate origin ("procedencia apropiada") which includes the value of the result of evaluate the previous nodes. - The nodes surrounded with orange circles mean the information about number of reproductions the song has and if the song is recent. The first one penalized the songs with more number of reproductions; the second one generates more value to the song with this attribute. - All of those nodes ends on the node with the green circle; it has a value for each song on the database taking into consideration all the previous nodes. Once we get evaluated all the songs finally, it only remains to arrange the songs into a list and began the reproduction of this playlist. XVI. **FORTH STEP: HOW TO CREATE THE COMPARISON?** We are going to explain where we find our conclusion about decision rates selected on the different styles of music, this site is a metadata database of music called: "http://www.allmusic.com". The database consists of: - Basic Metadata: names, genres, credits, copyright info, product numbers, etc. - Descriptive Content: styles, tones, moods, themes, nationalities, etc. - Relational Content: similar artists and albums, influences, etc. - Editorial Content: biographies, reviews, rankings, etc. Allmusic also claims to have the world's largest digital archive of music, including approximately six million songs fully digitized. The Allmusic database is also used by several generations of Windows Media Player and Musicmatch Jukebox to identify and organize music collections. Windows Media Player 11 and the integrated MTV Urge music store have expanded the use of Allmusic data to include related artists, biographies, reviews, playlists and other metadata. A. **Related researches** Since IMUSIC is a customer likes oriented application it’s important to know what studies have been taken on this topic about criteria, needs, likes in order to set the decision of what kind of music they want: - Young Spaniards between 15-35 years old, lives surrounded of technologies since all of them have a mobile phone, about a 95% have personal computer, 84% have digital camera, 73% mp3 player and a 62% have a videogame-consol under a first trends research by Nokia. The first conclusion is that differences between men and women are quite few on use of technologies and the big group on use of new technologies is the young people. Nowadays young people want a comprehensive mobile phone with Bluetooth, USB connection, digital camera, mp3 player, external memory. And talking about design the preferred format for mobile is the opening slide, which is preferred by 31 per cent of young people, followed by monoblock with 26 percent. The research highlights the importance of music among young people who listen to an average of 23 hours per week and consider it to be more important than the sport, leaving march, politics or religion and that lie behind family and friends. - Another study on the people musical likes conducted by Renaud Lambiotte and Marcel Ausloos Statistical Physics experts contend that the musical likes of people are more diverse from what we know. These physicists have analyzed a website for exchanging music files and have found that people likes a wide variety of music for a mix of several predefined categories. The results could give a new way of classifying musical genres and be useful for analyzing market trends music. The study is based on the Audioscrobbler site, where users can upload their favorite music to a personal library on a central server. The site is designed to encourage their users to discover new types of music through the suggestions that other people do in their personal libraries. Using data from January 2005 researchers were able to examine the music heard by a total of 35,916 people together "possess" 617900 musical groups in their personal libraries. At the top of the list were Radiohead, Nirvana, Coldplay, Metallic and the Beatles. To analyze the list of users and music listeners used methods of the theory of complex networks in which people and music are two kinds of nodes in a network. Physicists began with a network "absolutely connected" in which two people are "connected" if at least share a song from the same artist. After applying an adjustable filter to the result network which took into account the correlations between entire collections of music rather than among individual musical groups it could see that as increasing the value of the filter structures found disconnected or "branches" formed along the overall structure of the original network, thus revealing trends and patterns in the form of a map of different music genres. This method of analysis allows study how music and new trends appears and it quantifies the musical signatures of a large number of individuals and visualizes their collective behavior that eventually leads to the emergence of new sociological communities. A investigation of Injuve has done a study about musical preferences, which indicates the percentage of young people who say they like "fairly" or "much" each of the following musical genres: <table> <thead> <tr> <th>Musical Genres</th> <th>Percentage</th> </tr> </thead> <tbody> <tr> <td>Pop, pop-rock</td> <td>50.1</td> </tr> <tr> <td>Dance</td> <td>40.2</td> </tr> <tr> <td>Latin, salsa</td> <td>36.4</td> </tr> <tr> <td>Cancioneros</td> <td>30.7</td> </tr> <tr> <td>Electronica</td> <td>29.6</td> </tr> <tr> <td>Belterianos, canción melódica</td> <td>29.5</td> </tr> <tr> <td>Rumba</td> <td>21.9</td> </tr> <tr> <td>Flamenco</td> <td>21.2</td> </tr> <tr> <td>Rock, rock'n'roll, rock cásico</td> <td>20.0</td> </tr> <tr> <td>Hip-hop, rap</td> <td>18.0</td> </tr> <tr> <td>Rock alternativo, grunge, radío-rock</td> <td>17.6</td> </tr> <tr> <td>Indie-pop, power-pop, pop alternativo</td> <td>16.7</td> </tr> <tr> <td>Popular a topos de su región o comunidad autónoma</td> <td>16.3</td> </tr> <tr> <td>Reggae, ska</td> <td>16.2</td> </tr> <tr> <td>Masicas del mundo, ensayos</td> <td>15.3</td> </tr> <tr> <td>Sinfónicas, soul, funk</td> <td>14.9</td> </tr> <tr> <td>Heavy, hard rock, metal</td> <td>14.9</td> </tr> <tr> <td>Clásica</td> <td>13.1</td> </tr> <tr> <td>Rock progresivo, postrock</td> <td>11.7</td> </tr> <tr> <td>Punk, hardcore</td> <td>11.6</td> </tr> <tr> <td>New age</td> <td>10.3</td> </tr> <tr> <td>Jazz</td> <td>9.5</td> </tr> <tr> <td>Folk, country, blues</td> <td>7.3</td> </tr> <tr> <td>Total</td> <td>1,500</td> </tr> </tbody> </table> Thus, among the styles like "fairly" or "a lot", highlights the pop-rock or pop (likes to half of those interviewed), dance music (40%), Latin music and salsa (36%), Songwriters (31%), electronic music (30%) and the trivial and melodic song (30%). The rest of styles presented acceptances below (all less than 22%). The classification is usually done in musical genres along the following criteria: 1. Features melodic, harmonic and rhythmic. 2. Instrumentation 3. Geographic place where it’s developed mainly. 4. Historical sources. 5. Structure of works (songs, movements, etc.). 7. Ways and methods of broadcasting B. Decisions making Conclusions on previous researches: - Referring to the first research we could deduce that it could be better to take the advantages of the current mobile technology for connect our application with the customers likes. Instead of use terminal input devices and all that it entails as the problem of setting up in each local, this solution is cheaper and better. But even so using mobile technology there are many options you can use instead, those options are: WiFi, infrared… - The second research gives us information on all genres that exist today in order to catalog all the music likes of customers. Through this research we find that we may be expanding and improving the Bayesian network that it will help us to decide what music is appropriate and what not as the likes of customers. Because there are so many musical genres, in our first version we will introduce only a few genres. In the future versions we will expand the application to get a better align with the likes of customers. Then we could establish the musical genre as an essential attribute to decide what kind of music we want. - With the third research we figure out what is the music likes globally. One of the objectives of our application is that any customer can find a way to express their musical tendency and to make it possible we have to develop an easy and friendly user interface that allows each user whatever likes he has can become an important build-part of the songs decision making of the local. Because the interface developed has to be simple we couldn’t include so many musical genres, so for a first version we have chosen the following genres: - Pop - Rock - Jazz After getting information about several researches we found we have reached the following conclusion about their influence on each other genres: <table> <thead> <tr> <th>Influence of</th> <th>over</th> <th>%</th> </tr> </thead> <tbody> <tr> <td>Pop</td> <td>Rock</td> <td>30%</td> </tr> <tr> <td></td> <td>Jazz</td> <td>10%</td> </tr> <tr> <td></td> <td>Chillout</td> <td>5%</td> </tr> <tr> <td>Rock</td> <td>Pop</td> <td>50%</td> </tr> <tr> <td></td> <td>Jazz</td> <td>20%</td> </tr> <tr> <td></td> <td>Chillout</td> <td>10%</td> </tr> <tr> <td>Jazz</td> <td>Pop</td> <td>10%</td> </tr> <tr> <td></td> <td>Rock</td> <td>36%</td> </tr> <tr> <td></td> <td>Chillout</td> <td>10%</td> </tr> <tr> <td>Chillout</td> <td>Pop</td> <td>15%</td> </tr> <tr> <td></td> <td>Rock</td> <td>20%</td> </tr> <tr> <td></td> <td>Jazz</td> <td>50%</td> </tr> </tbody> </table> We also found information about different styles and trends of music so the next step was quite easy: pair each musical genre at the Genie application with the others genres to make a intelligence decision making based on the origin of this style, trends, music speed (bits per second). Once make this step, we have to make decision of the results given for the customers as well, this decision consist on the form they had filled in. The fields with the relevant decision making weight was: - Genre - Nationality - Length This process is done for each song of our Database so at the end we have a “CUSTOMIZED PLAYLIST” ready to use into our local music application designed to play songs. XVII. Conclusions In the last few weeks we have spend a lot of time working on development of IMusic prototype, thinking if this project could get ahead. Sometimes we have the feeling that we can’t do this, but eventually, the reward of all this hard work is worth it. Technology talking, we have to learn a lot of packages and libraries to make possible the communication between a simple mobile phone, with a computer, which it comes to mind that there is a lot of applications that could make the daily life better. We even learnt, how to make a free chat using the phones with Bluetooth, and many others applications, that could fit well with our own interest (a little help on test evaluations, for instance). Talking about the IMUSIC application, we found very interesting the idea of being able to send, the kind of music you wants more, and this idea of business can be tempting for those locals that want to experiment a new idea of service for offering the customers. The next step that the application could overtake is to learn about new music tendencies and include them in our application. These procedures probably require a huge change on the application intelligence actions, but it is quite interesting to be developed in the future. References [1] Blue Cove [http://sourceforge.net/projects/bluencove/] is a JSR-82 J2SE implementation that currently interfaces with the Mac OS X, WIDCOMM, BlueSoleil and Microsoft Bluetooth stack found in Windows XP SP2 and newer [2] javaBluetooth [http://www.javabluetooth.org/] The JavaBluetooth Stack is a 100% (no native) Java implementation of the Bluetooth Specifications Version 1.1. It currently supports HCI, L2CAP and SDP.
{"Source-Url": "http://www.ijimai.org/journal/sites/default/files/IJIMAI1-1-11.pdf", "len_cl100k_base": 5296, "olmocr-version": "0.1.53", "pdf-total-pages": 6, "total-fallback-pages": 0, "total-input-tokens": 19219, "total-output-tokens": 5612, "length": "2e12", "weborganizer": {"__label__adult": 0.0007071495056152344, "__label__art_design": 0.0012388229370117188, "__label__crime_law": 0.0003495216369628906, "__label__education_jobs": 0.0004119873046875, "__label__entertainment": 0.0016832351684570312, "__label__fashion_beauty": 0.00025582313537597656, "__label__finance_business": 0.0003993511199951172, "__label__food_dining": 0.0007123947143554688, "__label__games": 0.0012807846069335938, "__label__hardware": 0.003719329833984375, "__label__health": 0.0003502368927001953, "__label__history": 0.00020015239715576172, "__label__home_hobbies": 8.83340835571289e-05, "__label__industrial": 0.00032210350036621094, "__label__literature": 0.0003964900970458984, "__label__politics": 0.00021588802337646484, "__label__religion": 0.0004737377166748047, "__label__science_tech": 0.0191802978515625, "__label__social_life": 0.00011688470840454102, "__label__software": 0.024200439453125, "__label__software_dev": 0.9423828125, "__label__sports_fitness": 0.0003788471221923828, "__label__transportation": 0.0005192756652832031, "__label__travel": 0.00020134449005126953}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 24729, 0.01624]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 24729, 0.18244]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 24729, 0.92735]], "google_gemma-3-12b-it_contains_pii": [[0, 4869, false], [4869, 7284, null], [7284, 11632, null], [11632, 15569, null], [15569, 20950, null], [20950, 24729, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4869, true], [4869, 7284, null], [7284, 11632, null], [11632, 15569, null], [15569, 20950, null], [20950, 24729, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 24729, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 24729, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 24729, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 24729, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 24729, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 24729, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 24729, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 24729, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 24729, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 24729, null]], "pdf_page_numbers": [[0, 4869, 1], [4869, 7284, 2], [7284, 11632, 3], [11632, 15569, 4], [15569, 20950, 5], [20950, 24729, 6]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 24729, 0.24242]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
bc550d378282c41adc3533aff662d25a69f2f321
SMT-Based Refutation of Spurious Bug Reports in the Clang Static Analyzer Mikhail R. Gadelha*, Enrico Steffinlongo†, Lucas C. Cordeiro‡, Bernd Fischer§, and Denis A. Nicole† *SIDIA Instituto de Ciência e Tecnologia, Brazil. E-mail: m.gadelha@samsung.com †University of Southampton, UK. ‡University of Manchester, UK. §Stellenbosch University, South Africa. Abstract—We describe and evaluate a bug refutation extension for the Clang Static Analyzer (CSA) that addresses the limitations of the existing built-in constraint solver. In particular, we complement CSA’s existing heuristics that remove spurious bug reports. We encode the path constraints produced by CSA as Satisfiability Modulo Theories (SMT) problems, use SMT solvers to precisely check them for satisfiability, and remove bug reports whose associated path constraints are unsatisfiable. Our refutation extension refutes spurious bug reports in 8 out of 12 widely used open-source applications; on average, it refutes ca. 7% of all bug reports, and never refutes any true bug report. It incurs only negligible performance overheads, and on average adds 1.2% to the runtime of the full Clang/LLVM toolchain. A demonstration is available at https://www.youtube.com/watch?v=ylW5iRYNsGA. I. INTRODUCTION LLVM comprises a set of reusable components for program compilation [1], unlike other popular compilers, e.g., GCC and its monolithic architecture [2]. Clang [3] is an LLVM component that implements a frontend for C, C++, ObjectiveC and their various extensions. Clang and LLVM are used as the main compiler technology in several closed- and open-source ecosystems, including MacOS and OpenBSD [4]. The Clang Static Analyzer (CSA) [5] is an open-source project built on top of Clang that can perform context-sensitive interprocedural data-flow analysis for programs written in the languages supported by Clang. CSA symbolically executes the program, collects constraints, and reasons about bug reachability using a built-in constraint solver. It was designed to be fast, so that it can provide results for common mistakes (e.g., division by zero or null pointer dereference) even in complex programs. However, its speed comes at the expense of precision, and it can provide results for common mistakes (e.g., division by zero or null pointer dereference) even in complex programs. However, its speed comes at the expense of precision, and it cannot handle some arithmetic (e.g., remainder) and bitwise operations. In such cases, CSA can explore execution paths along which constraints do not hold, which can lead to incorrect results being reported. Consider the program in Fig. 1. This program is safe, i.e., the unsafe pointer dereference in line 4 is unreachable because the guard in line 3 is always false. ``` unsigned int func(unsigned int a) { unsigned int *z = 0; if ((a & 1) && ((a & 1) ^ 1)) return *z; return 0; } ``` Fig. 1: A small C safe program. The dereference in line 4 is unreachable because the guard in line 3 is always false. The null pointer dereference reported here means that CSA claims to nevertheless have found a path where the dereference of z is reachable. Such spurious bug reports are in practice common; in our experience, about 50% of the reports in large systems (e.g., git) are actually spurious. Junker et al. [6] report similar numbers for a similar static analysis technology. Identifying spurious bug reports and refactoring the code to suppress them puts a large burden on developers and runs the risk of introducing actual bugs; these issues negate the purpose of a lightweight, fast static analysis technology. Here we present a solution to this conundrum. We first use the fast but imprecise built-in solver to analyze the program and find potential bugs, then use slower but precise SMT solvers to refute (or validate) them; a bug is only reported if the SMT solver confirms that the bug is reachable. We implemented this approach inside the CSA and evaluated it over twelve widely used C/C++ open-source projects of various size using five different SMT solvers. Our experiments show that our refutation extension can remove false bug reports from 8 out of the 12 analyzed projects; on average, it refuted 11 (or approximately 7% of all) bug reports per project, with a maximum of 51 reports refuted for XNU; it never refuted any true bug report. Its performance overheads are negligible and on average our extension adds only 1.2% to the runtime of the full Clang/LLVM toolchain. II. THE CLANG STATIC ANALYZER CSA performs a context-sensitive interprocedural data-flow analysis via graph reachability [7] and relies on a set of checkers, which implement the logic for detecting specific types of bugs [5], [8]. Each path in a function is explored, which includes taking separate branches and different loop unrollings. Function calls on these paths are inlined whenever possible, so their contexts and paths are visible from the caller’s context. Real-world programs, however, usually depend on external factors, such as user inputs or results from library components, for which source code is not always available. These unknown values are represented by symbols, and the built-in constraint solver in the static analyzer reasons about reachability based on expressions containing these symbols. The CSA relies on a set of checkers that are engineered to find specific types of bugs, ranging from undefined behaviour to security property violations, e.g., incorrect usage of insecure functions like strcpy and strcat [10]. The checkers subscribe to events (i.e., specific operations that occur during symbolic execution) that are relevant to their bug targets; for example, the nullability checker subscribes to pointer dereferences. They then check the constraints in the current path and throw warnings if they consider a bug to be reachable. These checkers can report incorrect results since the symbolic analysis is incomplete (i.e., they can miss some true bugs) and unsound (i.e., they can generate spurious bug reports). The sources of these incorrect results are approximations in two components, namely the control-flow analysis and the constraint solver. The control-flow analysis evaluates function calls inside the same translation unit (TU); if the symbolic execution engine finds a function call implemented in another TU, then the call is skipped and pointers and references passed as parameters are invalidated while the function return value is assumed to be unknown. Cross translation unit support (CTU) is under development [8]; it is not part of the CSA main branch yet. The built-in constraint solver (based on interval arithmetic) was built to be fast rather than precise, and removes expressions from the reasoning if they contain unsupported operations (e.g., remainders and bitwise operations) or are too complex (e.g., contain more than one operator symbol). The bug reports generated by the checkers are then post-processed before they are reported to the user. In this final step, a number of heuristics are applied to remove incorrect bug reports and to beautify the reports. The reports are also deduplicated, so that different paths that lead to the same bug only generate one report. As an example of this process, consider the exploded graph in Fig. 2 which contains bitwise operations that are not handled by CSA’s original constraint solver, generating a spurious bug report. ![Exploded graph of the program](https://example.com/graph.png) **Fig. 2:** Exploded graph of the program in Fig. 1 which contains bitwise operations that are not handled by CSA’s original constraint solver, generating a spurious bug report. III. **Refuting False Bugs Using SMT Solvers** One approach to address the limitations of the built-in constraint solver is to replace it by an SMT solver. This approach has been implemented in Clang but empirical evaluations show that this approach can be up to 20 times slower [1]. ![Architecture of our solution](https://example.com/solution.png) **Fig. 3:** The refutation extension in the Clang Static Analyzer. We developed an alternative solution: we use the more precise SMT solvers to reason about bug reachability only in the post processing step. CSA already has heuristics in place to remove incorrect bug reports, so we extended those heuristics to precisely encode the constraints in SMT and to check for satisfiability. Fig. 3 illustrates the architecture of our solution. After the static analyzer generates the bug reports, the SMT-based refutation extension will encode the constraints as SMT formulas and check them for satisfiability. CSA already supports constraint encoding in SMT using Z3 [11] but we also implemented support for Boolector [12], Yices [13], MathSAT [14], and CVC4 [15]. A bug report $BR$ is a straight line graph representing the path to a property violation (i.e., an $\epsilon$-node). Our refutation extension walks backwards through all nodes $s_i \in BR$, collects their constraints, and checks their conjunction for satisfiability. If the formula is unsatisfiable, the bug is spurious. Our constraint encoding algorithm is shown in Algorithm 1. Let us assume a set of constraints $C$, an SMT formula $\Phi$, and a method $\text{encode}(expr, \Phi)$, which encodes an expression $expr$ in the SMT formula $\Phi$. Algorithm 1 contains two optimizations. --- https://reviews.llvm.org/D28952 Algorithm 1: encodeConstraint(\(cs, \Phi\)) \[\textbf{Input: A set of constraints } C \text{ and an SMT formula } \Phi\] \[\textbf{Output: The formula } \Phi \text{ with all constraints } c \text{ encoded in SMT}\] \[\textbf{foreach } c \in C \text{ do}\] \[\text{ if } c.\text{var} \in \Phi \text{ then continue;}\] \[\text{ if } c.\text{interval.lower} == c.\text{interval.upper} \text{ then}\] \[\text{ encode}(c.\text{var} == c.\text{interval.lower}, \Phi)\] \[\text{ else}\] \[\text{ encode}(c.\text{var} \geq c.\text{interval.lower} \land c.\text{var} \leq c.\text{interval.upper}, \Phi)\] \[\textbf{end}\] \[\textbf{end}\] when encoding constraints: duplicated symbol constraints are ignored (line 2) and if the constraint is a concrete value (the lower bound is equal to the upper bound), the constraint is encoded as an equality (line 3). Note that ignoring symbol constraints in line 2 is only possible because the refutation extension runs from the last node in a bug report (the property violation) to the initial node; any new symbol constraint found when walking backwards will always be a subset of the symbol constraints already encoded. Fig. 4 shows the SMT formula of the bug found when analyzing the program in Fig. 1. The formula is equivalent to the path \([s_0, s_1, s_2, s_4, \epsilon]\) in Fig. 2 and \(s_0\) is the value of the variable \(a\). Since the formula is unsatisfiable, CSA will not produce a bug report for this path. \[ \begin{align*} \text{(declare-fun } \_0 \_ (}\_ \text{ BitVec 32)) \\ \text{(assert (= (} (\_ \text{ extract 0 0}) \_0 \_ b1))} \\ \text{(assert (= (} (\_ \text{ extract 0 0}) \_0 \_ b0))} \end{align*} \] Fig. 4: The SMT formula of the bug report from Fig. 1 IV. EXPERIMENTAL EVALUATION The experimental evaluation of our refutation extension consists of two parts. We first present the research questions, projects evaluated and the environment setup, before we compare the analysis results of the CSA with and without the bug refutation extension enabled; the two approaches are compared in terms of number of refuted bugs and verification time. A. Experimental Objectives and Setup Our experimental evaluation aims to answer two research questions: - **RQ1 (soundness)** Is our approach sound and can the refuted bugs be confirmed? - **RQ2 (performance)** Is our approach able to refute spurious bug reports in a reasonable amount of time? We evaluated the new bug refutation extension in twelve open-source C/C++ projects: tmux (v2.7), a terminal multiplexer; redis (v4.0.9), an in-memory database; OpenSSL (v1.1.1-pre6), a software library for secure communication; twin (v0.8.0), a windowing environment; git (v2.17.0), a version control system; PostgreSQL (v10.4), an object-relational database management system; SQLite3 (v3230100), a relational database management system; curl (v7.61.0), a command-line tool for transferring data; libWebM (v1.0.0.27), a WebM container library; memcached (v1.5.9), a general-purpose distributed memory caching system; xerces-c++ (v3.2.1), a validating XML parser; and XNU (v4570.41.2), the operating system kernel used in Apple products. All experiments were conducted on a desktop computer with an Intel Core i7-2600 running at 3.40GHz and 24GB of RAM. We used Clang v7.0. A time limit of 15s per bug report was set per bug report. All scripts to analyze the projects are available in https://github.com/mikhailramalho/analyzer-projects. B. Bug Refutation Comparison <table> <thead> <tr> <th>Projects</th> <th>time (s) (no ref)</th> <th>time (s) (ref)</th> <th>reported bugs (no ref)</th> <th>refuted bugs</th> </tr> </thead> <tbody> <tr> <td>tmux</td> <td>86.5</td> <td>89.9</td> <td>19</td> <td>0</td> </tr> <tr> <td>redis</td> <td>347.8</td> <td>338.3</td> <td>93</td> <td>1</td> </tr> <tr> <td>OpenSSL</td> <td>138.0</td> <td>128.0</td> <td>38</td> <td>2</td> </tr> <tr> <td>twin</td> <td>225.6</td> <td>216.7</td> <td>63</td> <td>1</td> </tr> <tr> <td>git</td> <td>488.7</td> <td>405.9</td> <td>70</td> <td>11</td> </tr> <tr> <td>PostgreSQL</td> <td>1167.2</td> <td>1112.4</td> <td>196</td> <td>6</td> </tr> <tr> <td>SQLite3</td> <td>1078.6</td> <td>1058.4</td> <td>83</td> <td>15</td> </tr> <tr> <td>curl</td> <td>79.8</td> <td>79.9</td> <td>39</td> <td>0</td> </tr> <tr> <td>libWebM</td> <td>43.9</td> <td>44.2</td> <td>6</td> <td>0</td> </tr> <tr> <td>memcached</td> <td>96.0</td> <td>96.2</td> <td>25</td> <td>0</td> </tr> <tr> <td>xerces-c++</td> <td>489.8</td> <td>433.2</td> <td>81</td> <td>2</td> </tr> <tr> <td>XNU</td> <td>3441.7</td> <td>3405.1</td> <td>557</td> <td>51</td> </tr> </tbody> </table> **Total** 7683.7 | 7408.5 | 1270 | 89 Table I shows the results of CSA with and without bug refutation enabled. **Note:** the time analysis (no ref) is the analysis time without refutation, time (s) (ref) is the analysis times with refutation enabled, averaged over all supported solvers (Z3, Boolector, MathSAT, Yices and CVC4), reported bugs (no ref) is the number of bug reports produced without refutation and refuted bugs is the number of refuted bugs. All solvers refuted the same bugs. There were bugs refuted in 8 out of the 12 analyzed projects: redis, openssl, twin, git, postgresql, sqlite3, xerces and XNU. On average, 11 bugs were refuted when analyzing these projects, with up to 51 bugs refuted in XNU. In total, 89 bugs were refuted and an in-depth analysis of them shows that all of them were false positives, and thus affirm RQ1. Our technique is unable to refute all false bugs as the unsound interprocedural analysis is another source of false positives in CSA, which was not addressed in this work. The average time to analyze the projects with refuted bugs was 35.0 seconds faster, a 6.25% speed up, and thus affirm RQ2. This is because the static analyzer generates html reports for each bug, which involves intensive use of IO (e.g., the html report produced for the program in Fig. [1]is around 25kB), and by removing these false bugs, fewer reports are generated and the analysis is slightly faster. Out of the four projects, where no bug was refuted (tmux, curl, libWebM and memcached), the analysis was 1.0 second slower on average: a 1.24% slowdown. We average the analysis time of all solvers because their performance was equivalent. For that reason, we did not submit the other backends to the mainstream Clang; we expected different performance between the solvers but all they refuted the same bugs and the analysis times were within 5% from each other. More solvers offer more flexibility specially license-wise, however, currently their is no demand for having more solvers in the CSA. V. RELATED WORK Static analysis of programs has seen a great improvement in the last years and in many cases it has been applied for the analysis of big real-world projects. Frama-C [16] is an extensible analysis framework based on abstract interpretation for the C language. It also has a large number of plugins for checking different program properties. Infer [17] is an open-source static code analysis tool used for the verification of the Facebook code base and on many mobile apps (e.g., WhatsApp) and is adopted by many companies (e.g., Mozilla, Spotifoy). Cppcheck [18] focuses on detecting dangerous coding practices and undefined behaviours. It was used for detecting many vulnerabilities including a stack overflow in X.org. The use of SMT solvers as backends for static analysis tools is a well known approach. It has been adopted in the ESIBM [19] C/C++ bounded model checker. It encodes the program as an SMT formula and depending on its satisfiability it detects possible bugs. This encoding technique is proved to be sound, however, it does not scale up to real-world programs. An approach similar to the one adopted in this paper has also been used in Goanna [6]: a C/C++ static analyzer able to scale up to real-world programs (e.g., OpenSSL, WireShark). After detecting all bugs, false ones are eliminated by analyzing the feasibility of error paths using SMT solvers. The biggest difference between Goanna and our approach is on the first (imprecise) analysis: Goanna uses NuXmv and MathSAT5 to generate the bug reports, while we use a custom built-in constraint solver. Similarly to our approach, they use Z3 to encode and refute false bug reports, but we offer a wider selection of SMT solvers to choose from. VI. CONCLUSIONS Our SMT-based bug refutation extension in CSA is a simple but powerful extension; it prevents reporting the class of false bugs generated by the unsound constraint solver while introducing minimal overhead to the analysis. Our empirical evaluation shows that the bug refutation extension can consistently reduce the analysis time if bugs are removed, while the slow down when no bug is refuted is negligible. We used five different solvers in our experiments (Z3, Booleter, MathSAT, Yices and CVC4) and their performance is equivalent; our refutation extension using Z3 is already part of the Clang v7. Our experiments show that the CSA constraint solver is not the largest source of imprecision, as replacing it by a more precise SMT solver leaves an estimated 85% of the spurious bug reports unfreted. We conjecture that these are caused by the approximations in the TU-based control flow analysis (CFA). We will replace it by a CTU-based CFA during refutation and also extract test inputs from the counterexamples to double-check reachability to increase our precision. Acknowledgements. We would like to thank George Karpenkov and Artem Dergachev for the guidance during the development of this project and, in particular, George Karpenkov for the initial idea of this project. REFERENCES
{"Source-Url": "https://ssvlab.github.io/lucasccordeiro/papers/icse2019.pdf", "len_cl100k_base": 4735, "olmocr-version": "0.1.49", "pdf-total-pages": 4, "total-fallback-pages": 0, "total-input-tokens": 15090, "total-output-tokens": 6025, "length": "2e12", "weborganizer": {"__label__adult": 0.0003211498260498047, "__label__art_design": 0.00023066997528076172, "__label__crime_law": 0.0003230571746826172, "__label__education_jobs": 0.00023221969604492188, "__label__entertainment": 4.804134368896485e-05, "__label__fashion_beauty": 0.0001266002655029297, "__label__finance_business": 0.00015294551849365234, "__label__food_dining": 0.0002760887145996094, "__label__games": 0.00038743019104003906, "__label__hardware": 0.000823974609375, "__label__health": 0.0003204345703125, "__label__history": 0.0001512765884399414, "__label__home_hobbies": 6.240606307983398e-05, "__label__industrial": 0.0003104209899902344, "__label__literature": 0.0001647472381591797, "__label__politics": 0.0002269744873046875, "__label__religion": 0.00038814544677734375, "__label__science_tech": 0.0090484619140625, "__label__social_life": 6.914138793945312e-05, "__label__software": 0.004978179931640625, "__label__software_dev": 0.98046875, "__label__sports_fitness": 0.0002675056457519531, "__label__transportation": 0.0003972053527832031, "__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, 21886, 0.04001]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 21886, 0.19705]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 21886, 0.87335]], "google_gemma-3-12b-it_contains_pii": [[0, 5113, false], [5113, 9448, null], [9448, 14532, null], [14532, 21886, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5113, true], [5113, 9448, null], [9448, 14532, null], [14532, 21886, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 21886, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 21886, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 21886, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 21886, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 21886, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 21886, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 21886, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 21886, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 21886, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 21886, null]], "pdf_page_numbers": [[0, 5113, 1], [5113, 9448, 2], [9448, 14532, 3], [14532, 21886, 4]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 21886, 0.1157]]}
olmocr_science_pdfs
2024-11-24
2024-11-24
4b4bfc4e80d951e2e1add440e23ea7bbc8d71823
<table> <thead> <tr> <th>Title</th> <th>Speech processing tools - An introduction to interoperability</th> </tr> </thead> <tbody> <tr> <td>Authors</td> <td>Christoph Draxler, Toomas Altosaar, Sadaoki Furui, Mark Liberman, Peter Wittenburg</td> </tr> <tr> <td>Citation</td> <td>Proc. INTERSPEECH 2011, , , pp. 3229-3232,</td> </tr> <tr> <td>Pub. date</td> <td>2011, 9</td> </tr> <tr> <td>Copyright</td> <td>(c) 2011 International Speech Communication Association, ISCA</td> </tr> <tr> <td>DOI</td> <td><a href="http://dx.doi.org/">http://dx.doi.org/</a></td> </tr> </tbody> </table> Speech Processing Tools – An Introduction to Interoperability Christoph Draxler¹, Toomas Altosaar², Sadaoki Furui³, Mark Liberman⁴, Peter Wittenburg⁵ ¹Institute of Phonetics and Speech Processing, LMU Munich, Germany ²Aalto University School of Science and Technology, Espoo, Finland ³Dept. of Computer Science, Tokyo Institute of Technology, Japan ⁴Dept. of Linguistics, University of Pennsylvania, Philadelphia PA, USA ⁵Max Planck Institute for Psycholinguistics, Nijmegen, The Netherlands draxler@phonetik.uni-muenchen.de, Toomas.Altosaar@hut.fi, furui@cs.titech.ac.jp, myl@cis.upenn.edu, Peter.Wittenburg@mpi.nl Abstract Research and development in the field of spoken language depends critically on the existence of software tools. A large range of excellent tools have been developed and are widely used today. Most tools were developed by individuals who recognized the need for a given tool, had the necessary conceptual and programming skills, and were deeply rooted in the application field, namely spoken language. Excellent tools are a prerequisite to research. However, tool developers rarely receive academic recognition for their efforts. Journals, conferences and funding agencies are interested in the results of the work on a research question while the tools developed to achieve these results are of less interest. This makes it difficult to publish articles on tools, and it is next to impossible to obtain funding for their development. The Interspeech 2011 special event on speech processing tools aims to provide a forum for tool developers to improve their academic visibility and thus enhance their motivation to continue developing the software needed by the community. This year, the focus is on interoperability – how can different tools be integrated into the workflow, data be exchanged between tools, queries work across tools, and a consistent user interface be achieved. 1. Introduction Historically, the development of software tools for speech processing can be divided into three phases. In the pre-PC era, processing power, memory and network bandwidth were limited, and only very few institutions could afford computers. Furthermore, only trained operators could use the software which in general was highly specialized. In this era, the mainframe was the dominant system architecture and software was often designed to reuse existing modules and to share data since resources were limited. The PC era saw an exponential increase in processing power and available memory, and a high degree of standardization for hardware, programming languages and graphical user interfaces. A typical desktop computer allowed processing hitherto unknown amounts of data while standardization resulted in software being developed for large audiences. Researchers, technology developers and the general audience now had access to sophisticated software tools for processing speech, ranging from simple audio recording to annotation editors, signal processing, speech recognition and speech synthesis systems. As a side effect, the “old” ideals of tools sharing resources and data became less and less important. In the current Internet era, corpus and data sizes have outgrown the capabilities of individual workstations. Resources are now increasingly made available on the web, and web services provide the necessary processing power. This will create a fundamental change in the way research is performed: researchers will expect to have their data, as well as their favorite working environment and tools, accessible in a virtual workplace in a browser. During the transition of the pre-PC era to the post-PC era, several software systems were developed for operating on discrete-time signals - and more specifically - on speech. They represent real cases where software development for signals and speech was funded and reported through Ph.D. theses, reports, and deliverables that nearly every speech researcher is aware of, has used, or is still even using today. Today’s speech researchers may not be aware that early software tools played an integral role in speech research with far reaching effects. For example, the TIMIT corpus was processed and annotated on a software system called SPIRE [1] that ran on Symbolics Lisp machines and was freely available to universities via a license. SPIRE itself was influenced by earlier work by Gary Kopec who formulated a representation for discrete-time signals in software [2]. Kopec extended his theoretical work to cover both signal representation and processing, as well as a system called SDB [3] that was used for the storage and management of signals and their properties. This latter work was used especially for speech processing research and applications. Funded work on other speech-specific software tools also existed, e.g., QuickSig [4] that was applied to speech corpus annotation and speech processing, as well as Stanis-LAX that noted the need for advanced tools and architectures for speech processing environments [5]. 1.1. Workflow The typical phases of an end-to-end workflow in speech processing, along with the associated data types and a selection of well-known tools are shown in fig. 1. Clearly, proceeding through the workflow involves the use of many different tools, but even more it requires handling different types of data: signal data (audio, video, sensor), graphics data, program code and plain, mark-up or styled text. Presently, every tool in the workflow uses its own native data format. Some tools provide import- and export functions, but significant amounts of data conversion and reformatting is still necessary. A global data model for the speech processing workflow, based on the concept of a corpus, has been proposed by [6]. Such a data model will be immediately useful for web-based and collaborative work, but transformation costs, both in terms of converting data and in terms of adapting software to access data in the global data model, are high. 1.2. Tools workshops and conferences In recent years there have been a number of initiatives to disseminate knowledge about existing tools, to share development efforts, and to bring together researchers and tool developers to define the requirements for future tools. These initiatives include, e.g., a workshop on standards for phonological corpora organized by U. Gut in Augsburg in 2009 and the workshop on ‘New Tools and Methods for Very-Large-Scale Phonetics Research’ organized by the Phonetics Laboratory of UPenn in 2011, and others, e.g., the European CLARIN project [7]. As a result, informal cooperation between tool developers and discussion groups have been established. For example, the effort of the developers of ELAN, ANVIL, and EXMARaLDA to define and implement a common data exchange format [8], the language archive technology (LAT) discussion groups hosted by the Max Planck Institute of Psycholinguistics in Nijmegen, the newsletters and discussion forums of LDC, ELRA and other speech resource providers, now exist. However, contributions to these initiatives do not result in publications, let alone high-impact publications. In the last 10 years, only one issue of ‘Speech Communication’ has been devoted to tools (Vol. 22, Numbers 1-2, 2001). The Romans knew what this means: *Quod non est in actis non est in mundo*. On the other hand, tools are mentioned in many publications. Table 1 summarizes the results of a simple Google search for a given tool in the body of web-accessible PDF documents of large speech-related conferences1. ### Table 1: Google query hits for tool names in the PDF documents of major speech-related conferences <table> <thead> <tr> <th>name</th> <th>type</th> <th>count</th> </tr> </thead> <tbody> <tr> <td>htk</td> <td>speech recognition toolbox</td> <td>2,760</td> </tr> <tr> <td>Prat</td> <td>annotation editor and processor</td> <td>1,100</td> </tr> <tr> <td>Sphinx</td> <td>speech recognition toolbox</td> <td>882</td> </tr> <tr> <td>NXT</td> <td>corpus toolbox</td> <td>343</td> </tr> <tr> <td>ELAN</td> <td>annotation editor</td> <td>222</td> </tr> <tr> <td>ESPS</td> <td>signal processing toolbox</td> <td>230</td> </tr> <tr> <td>ANVIL</td> <td>annotation editor</td> <td>226</td> </tr> <tr> <td>Emu</td> <td>annotation editor and processor</td> <td>201</td> </tr> <tr> <td>WaveSurfer</td> <td>signal processor and viewer</td> <td>151</td> </tr> <tr> <td>Audacity</td> <td>signal editor</td> <td>64</td> </tr> <tr> <td>EXMARaLDA</td> <td>annotation editor</td> <td>44</td> </tr> <tr> <td>MAUS</td> <td>forced aligner</td> <td>41</td> </tr> <tr> <td>SpeechRecorder</td> <td>audio recording tool</td> <td>10</td> </tr> </tbody> </table> 1The Google search expression was: ‘allintext: “SpeechRecorder” LREC OR Interspeech OR ICASSP OR Eurospeech OR ICSLP site:.org filetype:pdf’ query date was 23 March 2011. Software interoperability. In the context of speech processing tools, the following definition from the IEEE Glossary is useful: interoperability is the ability of two or more systems or components to exchange information and to use the information that has been exchanged. The article distinguishes syntactic from semantic interoperability and has a paragraph on software interoperability. The article also emphasizes the importance of standardization. ### 2. Standardization With large amounts of text becoming available on the Internet, and with the growing number of well-defined speech and text corpora, standardization has received increased attention. Several standards bodies have taken up the task of standardizing terminology, methods and tools for speech and text processing. These bodies include institutions such as the International Standards Organisation (ISO), the World Wide Web Consortium (W3C) and national standards bodies, interest groups such as the Text Encoding Initiative (TEI) and the ISOCat data category registry, and industry consortia such as the MPEG forum. ### 3. Semantic interoperability Among spoken language researchers and technology developers there is now a general consensus about the entities involved in speech processing: Speech is a *time-dependent physical signal*, it is processed using digital signal processing methods and algorithms, and it is described (transcribed, segmented, annotated, etc.) using textual representations. A speech corpus is a structured collection of speech, possibly derived signal data, and textual data [9]. A segment is a tuple consisting of an anchor, an optional extension, and a label. In time-dependent segments, the anchor is a time-point, the extension is a duration. In time-independent segments the anchor is a unique identifier. The label describes the segment contents, commonly in free-form or structured text. A tier holds segments of a common type. Within a tier, segments are ordered, e.g., according to the time points or a sequence index. Constraints govern the organization of segments in a tier: segments may overlap, there may be gaps, etc. For a given collection of speech and text data, there may exist many tiers. In general, tiers relate to each other by some relationship which can be named and which specifies quantitative constraints. The schema specifies the tiers and the relationships between the tiers. A schema not only allows checking the formal integrity of corpus data, but it supports semantically meaningful cross-tier queries and may also be used to build flexible query and visualization tools. The Annotation Graph formalism provides a formal framework for speech processing, notably the annotation of speech [10]. However, it lacks a schema description. Many speech processing tools implicitly implement a schema in which the tiers are independent of each other. Other tools have implicit or explicit 1:n relationships, only Emu has explicit 1:n and n:m relationships [11]. 3.1. Data model overview A data model is a formal framework describing a collection of data. The hierarchical data model organizes data in 1:n relationships: there is a single root element, only one path from the root to any given element, and the relationships are not named. The network data model allows more than one root element and named 1:n relationships; different paths are distinguished by name. The query languages in both data models are navigational, i.e., searching for a specific element is achieved by traversing the hierarchy or network. The relational data model organizes data in relational tables with attributes, relationships are expressed via the relational join operator based on comparisons between attributes of relational tables; in principle, relationships may exist between any two relational tables. The query language is declarative, i.e., queries are formulated using relational algebra or calculus, and the concept of navigation is alien to the relational model. The object-oriented data model distinguishes two basic types of relationship: is-a and uses. The is-a-relationship organizes all data in a hierarchy (single inheritance) or a network (multiple inheritance), the uses-relationship is named and may link arbitrary elements. Object-oriented query languages are navigational. Mathematically, the above data models can be seen as graphs with different directionality, quantity and naming constraints. 3.2. Data models for speech processing The data types relevant for speech processing are highly structured: data streams, sequences, trees and network structures are common. Generally speaking, the relational data model is an abstract representation of data; any structure can be represented, but this inflates the number of relational tables and results in lengthy queries. However, due to the simplicity of the data model and the small number of basic data types, relational models of speech corpora will always be very similar, facilitating the exchange of data and the reuse of code. The object-oriented data model is a natural choice for representing the richness of speech processing data. However, due to the unlimited possibilities of constructing complex data types out of other data types, no two object-oriented models of speech corpora will look the same, and hence the exchange of data and the reuse of code is heavily affected. 4. Syntactic interoperability Syntactic interoperability must be divided into at least four levels: the basic encoding level, the data format level, the implementation level, and the programming interface or service level. 4.1. Encoding level The encoding level comprises the digital representation of the basic data types: signal data and text data. Many different audio, video and sensor data formats have been defined, they are often tool- or platform-specific. For uncompressed data and open data formats, this does not pose a problem – in general, data can be converted without loss from one format to another. For text data, Unicode is becoming the de facto standard character set. However, the transition from older character sets and encodings to Unicode is still in progress. Unfortunately, some tools do not yet support Unicode. Although interoperability on the encoding level is feasible – in general, doing a round trip is possible – it often requires a lot of manual work and can be quite time-consuming. 4.2. Data format level The data format level comprises the organisation of the data as it is being used by an application or a web service; it is what is commonly known as an application dependent file format, e.g., a Praat TextGrid or an ELAN annotation file. Only a minority of the file formats in use today’s tools are formally defined with the specifications being publicly available. Some tools require files to be in a given storage location, others do not. None of the common tools stores its data in a DBMS or has an interface to a database system. Since different file formats have become de facto standards most tools provide import and export functionality. However, most work on individual files or directories but cannot process entire corpora. Converting from one file format to another normally leads to loss of information, and in general, round-tripping is not possible. 4.3. Implementation level The implementation level relates to the programming languages and libraries used to implement a given speech processing application. Naturally, technology advances, applications become available or software becomes obsolete. Interoperability is a moving target. Currently, the programming languages most commonly used for the implementation of speech processing tools are strongly typed and compiled languages like Java, C++ and C, and interpreted script languages like perl, tcl and python, as well as JavaScript. Besides these, application or domain specific languages are used, e.g., the built-in script language of Matlab, the Statistics language R, or the database query language SQL. Every language comes with its own syntax, execution model, basic data types and with its specific programming libraries. Some languages provide features to include precompiled modules, thereby allowing the reuse of existing code. 4.4. Programming interface or service level Many program libraries are accessible via public interfaces. Wrapper classes take care of the conversions necessary on the data format level and thus enable the exchange of data. Such interfaces are common in high level applications, e.g., spreadsheet programs and statistics packages. Carrying the concept of client-server computing one step further is cloud computing. Here, a user establishes a virtual workspace, where he or she has access to all the required data and tools. The tools are implemented as web services, and they are run by some service provider somewhere on the net. For basic tasks such as text processing or standardized workflows such as web link management or financial services, and especially social networks, cloud computing has become very popular and successful. For language research, especially text corpus work, virtual workplaces have started to appear [12]. For speech processing, work on web services and the infrastructure necessary to establish virtual workspaces has begun [13, 7]. 5. Users’ view on interoperability Interoperability has another facet, not covered by the definitions given above: the users’ view. A user works with a given software tool for many reasons: suitability, availability, joy of use, familiarity, etc. and by using a tool he or she wants to get work done. In an ideal world, the tool should reflect the users’ knowledge, skills and best practices in the application domain, i.e., support the user by using the data, algorithms, workflow and terminology of the field. In reality, things are often the other way around: tools impose a specific world view upon the user, so that switching from one tool to the other means moving from one mini-environment to the next. On an abstract level, speech processing can be seen as searching for data according to some conditions and then manipulating this data. Query languages range from very general to highly application- or tool-specific, and they can be written as text, constructed using a wizard, or by interactive exploration of the data itself. In fact, currently every tool implements its own query language, and often this query language directly reflects the data structures of the tool. An alternative is to separate the surface form of the query from the underlying query evaluation mechanism. This underlying mechanism reflects the global domain data model and the formal properties of this model, e.g., relational tables or graphs, whereas the surface form is determined by the user interface which is tool or task specific. This approach encourages tool developers to provide more than one user interface for queries, or to develop application independent query interfaces that can access different query evaluation mechanisms. Furthermore, this approach allows the user to select the query input method that best suits his or her needs, and even to switch between input modes. 6. Conclusion The field of speech and language processing is alive and productive. There is a general consensus about the application domain; formal frameworks have been proposed which underlie and guide the development of tools and systems. Excellent tools have been developed and are widely available – in fact, the large number of tools mirrors the richness of the field. Interoperability is a key issue. This may be a bold statement, but semantic interoperability is not the problem, it’s the data format level interoperability in combination with disagreement on the extent of a global data model. Thus, a common minimal core data model encompassing the concept of a corpus is needed, and this data model must be supported by all tools – [6, 8] are first examples of how this ambitious goal can be reached. In the future we need to go even further. 7. References
{"Source-Url": "http://t2r2.star.titech.ac.jp/rrws/file/CTT100631017/ATD100000413/", "len_cl100k_base": 4473, "olmocr-version": "0.1.53", "pdf-total-pages": 5, "total-fallback-pages": 0, "total-input-tokens": 14715, "total-output-tokens": 5217, "length": "2e12", "weborganizer": {"__label__adult": 0.0005869865417480469, "__label__art_design": 0.0007052421569824219, "__label__crime_law": 0.0006189346313476562, "__label__education_jobs": 0.0031337738037109375, "__label__entertainment": 0.0005230903625488281, "__label__fashion_beauty": 0.0002071857452392578, "__label__finance_business": 0.0002968311309814453, "__label__food_dining": 0.0004677772521972656, "__label__games": 0.0010251998901367188, "__label__hardware": 0.0012407302856445312, "__label__health": 0.0012578964233398438, "__label__history": 0.0004575252532958984, "__label__home_hobbies": 7.468461990356445e-05, "__label__industrial": 0.0004551410675048828, "__label__literature": 0.0031414031982421875, "__label__politics": 0.0005207061767578125, "__label__religion": 0.0007796287536621094, "__label__science_tech": 0.212890625, "__label__social_life": 0.0002956390380859375, "__label__software": 0.052764892578125, "__label__software_dev": 0.71728515625, "__label__sports_fitness": 0.0004787445068359375, "__label__transportation": 0.00066375732421875, "__label__travel": 0.00022733211517333984}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 23255, 0.02776]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 23255, 0.77954]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 23255, 0.90721]], "google_gemma-3-12b-it_contains_pii": [[0, 480, false], [480, 6049, null], [6049, 10458, null], [10458, 17093, null], [17093, 23255, null]], "google_gemma-3-12b-it_is_public_document": [[0, 480, true], [480, 6049, null], [6049, 10458, null], [10458, 17093, null], [17093, 23255, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 23255, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 23255, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 23255, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 23255, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 23255, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 23255, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 23255, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 23255, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 23255, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 23255, null]], "pdf_page_numbers": [[0, 480, 1], [480, 6049, 2], [6049, 10458, 3], [10458, 17093, 4], [17093, 23255, 5]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 23255, 0.18966]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
17da544536c2f8da31ffecda7aebf625fd283848
CREATIVE DESIGN IN OBJECT-ORIENTED ENVIRONMENTS AUTHORS Zenon Rychter Faculty of Architecture, Technical University of Bialystok, Krakowska 9, 15-875 Bialystok, Poland rychter@cksr.ac.bialystok.pl ABSTRACT Object-oriented approach to software development is discussed as a conceptual framework and working computational model for creative architectural design. Two modes of object orientation in design are elaborated. The more conservative mode is static, based on class-type/object-instance hierarchies. The other mode is dynamic, based on a modern view of computation as multi-threaded evolution of interacting objects. The Internet and Web as computing environment Today, an architectural design process involves users, designers and computers. While users and designers, being humans, are rather conservative and set in their ways, computers are undergoing explosive growth and revolutionary change. Computing power has become ubiquitous. The information highway commonly called the Internet reaches everywhere. The World Wide Web (Klander 1997) is still in its infancy being only 7 years old but it is here to stay as technology grows, with over 80 million sites on the Internet now and limitless boundaries as to what you can do. The most important ingredient to the success of the Internet has been its neutrality. No matter what country you live in, what language you speak or even what operating system you are running, you can access the nearly unlimited information published on the Internet. We owe this to WWW standards. These standards encompass everything from programming languages used on the Internet to connection protocols like TCP/IP or modem command strings. The core development has been language standardization. Back in 1986, with literally thousands of word processing programs out on the market, each of which encoded text in a different way when saved to disk, it was virtually impossible to create a single text file that could be viewed by every operating system in existence. And if something as simple as text could not be portable, then one could forget about graphic files or program files. At the time, the Internet as we know it was not possible, simply because the operating systems and programs of the day had major difficulties translating files written in a foreign program. This is where Standard Generalized Markup Language (SGML) came in, a meta-language, a guideline for how other languages should be developed. The foundation for the web sites we see today comes from SGML, without which there would have probably developed an Internet for Microsoft OS systems, another for systems running Mac OS, and yet another for UNIX. Since its inception, several sub-languages have developed out of SGML. The most notable of these is Hyper Text Markup Language (HTML), however additional languages such as Virtual Reality Markup Language (VRML) and Extensible Markup Language (XML) were also developed out of the mold of SGML. HTML was originally intended only to handle the formatting of text. Only now is HTML broadening its horizons to encompass more than text. HTML 2.0 was the first revision of HTML to actually be solidified into a standard, which was released in September 1995. HTML 3.2 was the next revision of the language, published in May of 1996. HTML 4.0 became a standard in 1997. Previous versions of HTML were developed to match the capabilities of the browsers currently deployed on the market. This has changed in HTML 4.0, which is the first attempt to really expand the functionality of the language by adding support for object tags, as well as support for Cascading Style Sheets (CSSs). The object tag is notable because it enables scripts, code from scripting languages, to be embedded directly in the HTML source code for a site. The development of the object tag has a direct relation to the Object-Oriented Model for programming languages, found in application programming languages for years now. Between the object tag --- 1 This research was sponsored under grant S/WA/5/97 from Technical University of Bialystok and Cascading Style Sheets, the possibilities for the coding of a web site will be limited only to the imagination of the site developer. Dynamic HTML is Microsoft’s latest advance in HTML, intended to make the language more functional by adding abilities normally found in application programming languages like C++ (Stroustrup 1993) or Java (Jamsa 1996). For the first time, a site developer can code an HTML document that uses animated text, can be set for timed events, scrolling text as well as the ability to access databases all without the need for additional components. Extensible Markup Language (XML) was announced as a proposed standard in December 1997. Like SGML, XML is not really a programming language, but a meta-language. However, whereas SGML was designed as a universal code for the formatting of text, XML is designed as a universal code for the formatting of data, a universal code for how Internet applications share information between one another. As the abilities of online technologies like HTML develop, the differences between web sites and applications are beginning to fade. However, a major hindrance to programmers who wish to develop online applications is the way that current programming languages encode their information. Because of this, it is exceedingly difficult for developers to create web applications intended to share information like databases, spreadsheets or even games simply because the developer has no control over whether or not the software installed on the user’s system will be capable of interpreting and using the information delivered to it. This is where XML comes in. XML is designed as an open classification, whereby packets of data transmitted from one computer to another will contain all the information needed to be able to decode itself using any application that can handle XML. Just as SGML enabled electronic text to be useable by any computer with an SGML capable browser installed, XML provides this same function for data itself. There is no limit in the Web specifications to the graphical formats that can be used on the Web. Vector Graphics (SVG) is a recent language for describing two-dimensional graphics in XML. SVG allows for three types of graphic objects: vector graphic shapes, images and text. Graphical objects can be grouped, styled, transformed and composited into previously rendered objects. The feature set includes nested transformations, clipping paths, alpha masks, filter effects, template objects and extensibility. SVG drawings can be dynamic and interactive. SVG allows for straightforward and efficient vector graphics animation via scripting. A rich set of event handlers such as onmouseover and onclick can be assigned to any SVG graphical object. Because of its compatibility and leveraging of other Web standards, features like scripting can be done on HTML and SVG elements simultaneously within the same Web page. Mathematical Markup Language (MathML) is a recent low-level specification for describing mathematics as a basis for machine to machine communication. It provides a much needed foundation for the inclusion of mathematical expressions in Web pages. MathML is intended to facilitate the use and re-use of mathematical and scientific content on the Web, and for other applications such as computer algebra systems, print typesetting, and voice synthesis. MathML can be used to encode both the presentation of mathematical notation for high-quality visual display, and mathematical content, for applications where the semantics plays more of a key role such as scientific software or voice synthesis. MathML is cast as an application of XML. As such, with adequate style sheet support, it will ultimately be possible for browsers to natively render mathematical expressions. MathML consists of a number of XML tags which can be used to mark up an equation in terms of its presentation and also its semantics. MathML attempts to capture something of the meaning behind equations rather than concentrating entirely on how they are going to be formatted out on the screen. This is on the basis that mathematical equations are meaningful to many applications without regard as to how they are rendered aurally or visually. With the launch of Java language and Jini technology, Sun kicks off a new era of distributed computing. Businesses are leaving behind a motley system of fax, phone, and proprietary software by shifting to Java technology. In Boston Computer Museum, thanks to the virtual fish tank exhibit, visitors can interact with playful, brightly colored fish propelled by Java technology. Embedded Java will support real-time capabilities, providing consumer and industrial devices, such as mobile phones, pagers, and medical devices, with a precise, predictable response time and the ability to coordinate functions without any lapse between operations. With Jini technology we can imagine a huge global network with a host of myriad devices and it all just works. Java applets, those nimble servants of the network, are popping up in browsers everywhere. Servlets support dynamic web site applications in ways never dreamed of. The Java platform is making major inroads into every area of computing, offering portable, highly scalable, multiplatform, and simple to use, “Write Once, Run Anywhere” application development. Jini Technology makes computers and devices able to quickly form impromptu systems unified by a network. Such a system is a federation of independent, flexible, smart devices, including computers, that are simply connected. Within a federation, devices are instant on, no one needs to install them. The network is resilient, you simply disconnect devices when you don’t need them. This creates a work environment where the tools are ready to use and largely invisible. Jini technology provides simple mechanisms which enable devices to plug together to form an impromptu community, a community put together without any planning, installation, or human intervention. Each device provides services that other devices in the community may use. These devices provide their own interfaces, which ensures reliability and compatibility. Devices permeate our lives: TVs, VCRs, DVDs, cameras, phones, PDAs, radios, furnaces, disk drives, printers, air conditioners, CD players, pagers, and the list goes on. Today devices are unaware of their surroundings, they are rigid and cannot adapt. When you buy a disk drive, you expend a lot of effort to install it or you need an expert to do it for you. But now devices of even the smallest size and most modest capabilities can affordably contain processors powerful enough for them to self-organize into communities that provide the benefits of multi-way interactions. A device can be flexible and negotiate the details of its interaction. We no longer need a computer to act as an intermediary between a cell phone and a printer. These devices can take care of themselves, they are flexible, they adapt. A device can take charge of its own interactions, can self-configure, self-diagnose, and self-install. When computers were the size of large rooms, it made sense to have a staff of people to take care of them. But now technology creates the possibility of impromptu, self-managing device communities popping up in all kinds of places far from any system administrator. The final stretch of the computational power dimension is that now processors are powerful enough to support a high-level, object-oriented programming language in such a way to support moving objects between them. And such a processor is small enough and cheap enough to sit in the simplest devices. Once there is sufficient computational power, the ability to connect and communicate is the dominant factor. Today for most people, a computer runs only a few applications and mainly facilitates communication: email, the Web. Internet's popularity soared first with email and more recently once the Web and browsers became prevalent. When the Internet was developing, there were two essential activities: defining and perfecting the underlying protocols and infrastructure, and creating applications and services on top of that infrastructure: email composers and readers, file fetching programs, Web browsers, and the Web itself. No single company or organization did all the work, and none could, if the venture was to be successful, because underlying it all is a standard protocol, and a protocol can be successful only if it is widely adopted. The Java programming language is the key to making Jini technology work. Java was originally developed for programming intelligent home appliances. Java leverages software reuse across projects, tools, and architectural layers. Astronomers and engineers use Java to monitor and control second-by-second movements of the Hubble Space Telescope. A sophisticated Java applet controls a rover on the surface of Mars. Java gadgets in the works include a finger ring that opens locked doors, a home telephone that offers movie reviews and ticket ordering, a wireless pen-based network computer that manages on-the-floor inventories. Applets run from simple to sophisticated, and uses range from management of business transactions, to sharing and analyzing scientific data, to gaming and consumer-oriented purposes, generally to breathing intelligence into the devices you'll use every day. The Internet(technology)/WWW(language) story demonstrates that technology cannot be exploited to the full without a proper standard, commonly understood language. We need the language first to conceptualize the system we are interested in and, second, to interact with the system, control it, or be a part of it. Object-Oriented Languages (OOLs) provide both the conceptual framework (Coad, Yourdon 1991) and computational efficiency to model the most complex systems, the heterogeneous Internet and architectural design included. OOLs, notably C++, have been the standard for system programming for some time now. But it is only recently that an OOL, Java, is becoming a standard on the Internet. The structure of the Internet is similar to the brain (Klander 1997). Thanks to Java we can understand the workings of this brain and can plug-in our own brains. The Internet plus Java form an incredibly rich computing environment, on Object-Oriented-Environment (OOE), ready to support all computing needs and styles. OOEs are relevant to creative, conceptual architectural design on two levels, static and dynamic, which correspond to two modes or models of architectural design, static-sequential-manual-controlled and dynamic-multithreaded-asynchronous-automatic. **Static object-oriented approach: design from components** In the static-sequential mode, developing an architectural design is likened to developing a windowed application with a graphical user interface (GUI) or an interactive Web site. The basic concept is the metaphor of objects (Stroustrup 1993). This is a natural way we interpret and interact with the world around us. Objects, whether real-world or computer representations, are described in terms of what they are and how they behave. Objects have certain characteristics or attributes, called properties, that define their appearance or state—for example, color, size, and modification date. Properties are not limited to the external or visible traits of an object. They may reflect the internal or operational state of an object, such as an option. Things that can be done with or to an object are considered its operations. Moving or copying an object are examples of operations. You can expose operations in the interface through a variety of mechanisms, including commands and direct manipulation. Objects always exist within the context of other objects. The context, or relationships, that an object may have often affects the way the object appears or behaves. Common kinds of relationships include collections, constraints, and composites. As in the natural world, the metaphor of objects implies a constructed environment. Objects are compositions of other objects. You can define most tasks supported by applications as a specialized combination or set of relationships between objects. A text document is a composition of text, paragraphs, footnotes, or other items. A table is a combination of cells; a chart is a particular organization of graphics. When you define user interaction with objects to be as consistent as possible at any level, you can produce complex constructions while maintaining a small, basic set of conventions. In addition, using composition to model tasks encourages modular, component-oriented design. This allows objects to be adapted or recombined for other uses. Applying object-based concepts offers greater potential for a well-designed interface. As with any good user interface design, a good user-centered design process ensures the success and quality of the interface. The first step to object-based design should begin with a thorough understanding of what users’ objectives and tasks are. When doing the task analysis, you should identify the basic components or objects used in those tasks and the behavior and the characteristics that differentiate each kind of object, including the relationships of the objects to each other and to the user. Also identify the actions that are performed, the objects to which they apply, and the state information or attributes that each object in the task must preserve, display, and allow to be edited. An effective user-centered design process involves a number of important phases: designing, prototyping, testing, and iterating. The initial work on a software’s design can be the most critical because, during this phase, you decide the general shape of your product. If the foundation work is flawed, it is difficult to correct afterwards. This part of the process involves not only defining the objectives and features for your product, but understanding who your users are and their tasks, intentions, and goals. This includes understanding factors such as their background — age, gender, expertise, experience level, physical limitations, and special needs; their work environment — equipment, social and cultural influences, and physical surroundings. Ideally, you want to create a design model that fits the user’s conceptual view of the tasks to be performed. You should consider the basic organization and different types of metaphors that can be employed. Observing users at their current tasks can provide ideas on effective metaphors to use. After you have defined a design model, prototype some of the basic aspects of the design. A prototype is a valuable asset in many ways. First, it provides an effective tool for communicating the design. Second, it can help you define task flow and better visualize the design. Finally, it provides a low-cost vehicle for getting user input on a design. This is particularly useful early in the design process. User-centered design involves the user in the design process. Usability testing a design, or a particular aspect of a design, provides valuable information and is a key part of a product's success. There can be different reasons for testing. You can use testing to look for potential problems in a proposed design. You can also focus on comparative studies of two or more designs to determine which is better. Usability testing provides you not only with task efficiency and success-or-failure data, it also can provide you with information about the user's perceptions, satisfaction, questions, and problems. When testing, it is important to use participants who fit the profile of your target audience. Because testing often uncovers design weaknesses, or at least provides additional information you will want to use, you should repeat the entire process, taking what you have learned and reworking your design or moving onto reprototyping and retesting. Continue this refining cycle through the development process until you are satisfied with the results. Working in OOE is further simplified by using classes. For example, the classes in the Microsoft Foundation Class Library (MFC) make up an "application framework" — the framework on which you build an application for Windows. At a very general level, the framework defines the skeleton of an application and supplies standard user-interface implementations that can be placed onto the skeleton. Your job as programmer is to fill in the rest of the skeleton — those things that are specific to your application. You can get a head start by using the application wizard to create the files for a very thorough starter application. You use resource editors to design your user-interface elements visually, class wizard to connect those elements to code, and the class library to implement your application-specific logic. Your role in configuring an application with the framework is to supply the application-specific source code and to connect the components by defining what messages and commands they respond to. You use standard OOL techniques to derive your own application-specific classes from those supplied by the class library and to override and augment the base class's behavior. It is crucial to understand the relationship between your source code and the code in the framework. When your application runs, most of the flow of control resides in the framework's code. The framework manages the message loop that gets messages from Windows as the user chooses commands and edits data in a view. Events that the framework can handle by itself don't rely on your code at all. For example, the framework knows how to close windows and how to exit the application in response to user commands. As it handles these tasks, the framework gives you opportunities to respond to these events as well. But your code is not in the driver's seat, the framework is. You can use the framework to write sophisticated programs, even if you are not an experienced programmer. The reason is the component library: a collection of routines that make it easy to work with the Windows environment. You don't need to understand the low-level workings of Windows. You don't have to be able to define a class. You just have to learn a few simple techniques for using the library components. At the same time, experienced programmers can use the full facilities of OOL whenever necessary. OOE provides the best of both worlds: a simple way to produce application programs using a comprehensive component library and the full power of a standardized programming language for those with more far-reaching requirements. All said above about developing GUI applications in OOE is valid for developing architectural designs: user-centered design, the design cycle, the skeleton-framework-class-object hierarchical approach, the available framework tools. It is hard to define what's creativity about, but ignoring what OOE already has in store is anything but creative. It's reinventing the wheel, ignoring what is readily available. Within an OOE each designer can draw upon and add to what others have done in the form of architectural class hierarchies. If you come across an idea of general utility, make it a class or component and publish it on the Web, for all to use and re-use. If you can be more specific than others, derive your class from someone else's more abstract class. If a composition of features is needed, derive your class from several parents. An architectural style can become a class, or a hierarchy of classes. An individual architect or a group can develop their own style, based on someone else's effort. All sorts of legal codes and technical standards, once put into classes, will be automatically fulfilled in designs that use object-instantiations of such classes, with obvious increase of design quality. Clearly developing useful classes is creative. And the effort put into transforming the subjective and vague ideas in the designer's brain into the objective structure and intelligence of a class is illuminating. It also enables sharing with others, humans or machines. But it is equally creative finding the best of available classes for a design job, customizing the objects, and turning them into a harmonious whole. And because the Web is becoming an OOE, orchestrating distributed design by a community of networked users, designers, consultants may soon be more creative and productive than the current, disintegrated approach, where each designer and each design is an isolated island. Dynamic object-oriented approach: design as a networked game The second, radical view of architectural design is based on a whole new way of thinking about computation, where computations are about concurrent interactions with users, networks, and environments. Almost any software program of significance today is composed of concurrent interactions among communities of entities. Today's programmer can never be ignorant of the context in which a program will run. There are always many things going on, inside your program and around it. That means you need to know how to think concurrently. The questions become: What are the services my system provides? Who are the entities that make up the community that is my system? How do these entities interact to provide those services? In the old system, computation is a process of sequencing steps, there is a single thread of control and you own it, and all you have to do as a programmer is tell the computer what to do next. That's not reality. A computer is a system of continuously, simultaneously interacting parts, you can't really isolate the pieces. Today, user actions often affect the computation's execution. And increasingly, computations have pieces that run simultaneously. The Java language presumes these types of computations at the most fundamental level. In designing the language, the Java developers were aware that computation is about constituting communities of interacting entities. The fact that threads are a part of Java is evidence of that. The fact that GUIs were built into Java is evidence. The fact that networking was built in is a natural consequence of that thinking. This isn't surprising because Java technology was originally designed for set-top boxes, which are embedded systems that have to interact simultaneously with users and televisions and networks. They have to be able to handle a lot of things going on, if not concurrently, at least conceptually concurrently. It's not at all surprising that the Java language was the right language for programming the Web. Because in building a programming language that would fit the needs of embedded systems, the people at Sun were building something that anticipated that things would be coupled together concurrently rather than sequentially, and that the world was full of an ever-expanding community of entities, each of which might be communities within themselves. Java is a simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language. But we are still entrenched in an outdated computational model: a single-thread-of-control static problem-solving view of the role of the computer program, and computation as calculation, which does not correspond to our computing environments. Instead, we should conceptualize computation with a model of computer programs as simultaneous ongoing entities embedded in and interacting with a dynamic environment: computation as interaction, computation as it occurs in spreadsheets and video games, web applications and robots. Perhaps the most fundamental idea in modern computer science is that of interactive processes. Computation is embedded in a (physical or virtual) world; its role is to interact with that world to produce desired behavior. While von Neumann serial programming has it that computation-as-calculation uses inputs at the beginning to produce outputs at the end, computation-as-interaction treats inputs as things that are monitored and outputs as actions that are taken over the lifetime of an ongoing process. Current practice changes the fundamental vocabulary of computation: not only are functions replaced by interaction patterns, but these interaction patterns take place concurrently and asynchronously. Programming no longer (necessarily) involves designing the flow of control in a system; instead, it is fundamentally about constituting a community of autonomously interacting entities, deciding what goes inside and what goes between them. Systems today are increasingly difficult to describe in the old paradigm. Networks, distributed computing, and concurrency are integral parts of the computational world. And languages such as Java force us to confront these issues. In the new vision, accounting for the role of the user becomes straightforward: the user is another member of the community of interacting processes that together constitute our computation. A program of this type is judged by the set of services or behaviors it provides. This description characterizes robots and software agents; it is descriptive of operating systems and network services; it fits video games and spreadsheets and modern word processing programs, as well as the controllers for nuclear power plants and automotive cruise controls. In modern computational systems, much of the interesting behavior is generated not by individual components per se, but by the interactions among these components. New approaches to computation are needed at many levels, from theoretical foundations to design methodologies. This is less a shift in the systems that we build and more an upgrading of our understanding of these systems. Every Java program with a graphical user interface is inherently concurrent. We must get rid of our sequentialist illusions and live from the very beginning in a potentially concurrent, distributed, interactive, embedded environment. The atomic unit of the new vocabulary is an infinite loop that senses and reacts, handles service requests in turn, or behaves. This approach to computation has the potential to build bridges with neighboring and less obviously related disciplines. The community model of computation is similar to foundational concepts in organizational science and other social sciences. Reconceptualized, the truth of computational practice is much closer to complex systems engineering. Taking this model of computation as a model for architectural design is only a matter of time. All operating systems of significance work like this, even those inside modest desktop PCs. The Internet and the Web work this way. We find here a general conceptual framework and a living, all embracing, omnipresent, ready 24 hours a day environment. All arrangements of users (clients), designers, consultants, hardware and software are supported here and all modes of their interaction are enabled. Everything and everybody is just an object in a community of interacting objects. Cybernetics as the theory of design (Glanville 1997) can be put here into practice. The fundamental concepts of cybernetics are supported in a natural way. There is feedback between objects-actors enabling them correction of their state and behavior and evolution by trial and error towards a common goal. Control is distributed between the actors and works in two directions between any pair of objects. Humans (designers, users) can work personally, on-line with each other and with software objects, or can be represented in a computation through tireless software agents. Actually, humans are, at one extreme, too slow to control a computation in real-time. At the other extreme, they are to impatient to wait for the result of a lengthy computation, the more so that it may be not at all clear what kind of result to expect. Furthermore, software agents can be anyplace, anytime, and there can be a host of them. They can check each and every aspect of an evolving design, real-time. They can have and use all senses (touch, smell, hear, feel the temperature, not just see), unlike a human designer (detached classical observer) observing a walk- or even fly-through. Thus software agents acting on behalf of human actors seem a viable alternative to personal involvement. The intellectual effort spent on trying to define such an agent (or many of them for different aspects of design) is an invaluable added value, and occasion to learn. The variety of such systems is enormous, compared to what we have today, and so is the potential for emergent, surprising forms. References Glanville R (1997). The value when cybernetics is added to CAAD, AVCAAD First International Conference (Ed. J. Verbeke, T. Provoost et al), Hogeschool voor Wetenschap en Kunst, Brussels. Klander L (1997), Hacker Proof, Jamsa Press. Stroustrup B (1993), The C++ Programming Language, Addison-Wesley, Reading, MA.
{"Source-Url": "http://papers.cumincad.org/data/works/att/b9ec.content.pdf", "len_cl100k_base": 6256, "olmocr-version": "0.1.50", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 25943, "total-output-tokens": 6723, "length": "2e12", "weborganizer": {"__label__adult": 0.0006880760192871094, "__label__art_design": 0.016845703125, "__label__crime_law": 0.0004611015319824219, "__label__education_jobs": 0.0025157928466796875, "__label__entertainment": 0.00023162364959716797, "__label__fashion_beauty": 0.00033211708068847656, "__label__finance_business": 0.00034046173095703125, "__label__food_dining": 0.0006151199340820312, "__label__games": 0.0007395744323730469, "__label__hardware": 0.0014629364013671875, "__label__health": 0.0006122589111328125, "__label__history": 0.0006737709045410156, "__label__home_hobbies": 0.00021564960479736328, "__label__industrial": 0.0008149147033691406, "__label__literature": 0.000903606414794922, "__label__politics": 0.0003421306610107422, "__label__religion": 0.0012292861938476562, "__label__science_tech": 0.0465087890625, "__label__social_life": 0.00013744831085205078, "__label__software": 0.011810302734375, "__label__software_dev": 0.9111328125, "__label__sports_fitness": 0.0003781318664550781, "__label__transportation": 0.0008344650268554688, "__label__travel": 0.0003612041473388672}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 33178, 0.01477]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 33178, 0.80612]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 33178, 0.94497]], "google_gemma-3-12b-it_contains_pii": [[0, 625, false], [625, 625, null], [625, 4084, null], [4084, 7750, null], [7750, 11547, null], [11547, 14812, null], [14812, 18784, null], [18784, 22610, null], [22610, 26270, null], [26270, 30179, null], [30179, 33178, null]], "google_gemma-3-12b-it_is_public_document": [[0, 625, true], [625, 625, null], [625, 4084, null], [4084, 7750, null], [7750, 11547, null], [11547, 14812, null], [14812, 18784, null], [18784, 22610, null], [22610, 26270, null], [26270, 30179, null], [30179, 33178, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 33178, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 33178, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 33178, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 33178, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 33178, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 33178, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 33178, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 33178, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 33178, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 33178, null]], "pdf_page_numbers": [[0, 625, 1], [625, 625, 2], [625, 4084, 3], [4084, 7750, 4], [7750, 11547, 5], [11547, 14812, 6], [14812, 18784, 7], [18784, 22610, 8], [22610, 26270, 9], [26270, 30179, 10], [30179, 33178, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 33178, 0.0]]}
olmocr_science_pdfs
2024-12-02
2024-12-02
1b4415e5c6815819f25378a47b64271a31668af4
SUMMARY By concentrating on defining and improving specific Configuration Management (CM) functions, processes, procedures, personnel selection/development, and tools, internal and external customers received improved CM services. Job performance within the section increased in both satisfaction and output. Participation in achieving major improvements has led to the delivery of consistent quality CM products as well as significant decreases in every measured CM metrics category. GETTING STARTED In early 1989, the Network Control Center Data System (NCCDS) Configuration Management Section was composed of two full-time technical people, one technical person on loan (to be used as required), one task leader, and the section manager. People had been in these positions for two-three years and knew their jobs. The section manager was new to the company, but not to the CM function, the software/engineering field, nor to Total Quality Management (TQM). The main functions of the CM group are to: - Provide support to formal project reviews, and baseline and control documentation - Support configuration item identification and discrepancy reporting system activities - Maintain software product baselines - Control changes to various software releases at different testing levels - Provide status, accounting, reporting, and traceability - Conduct internal audits and support formal project audits - Coordinate, track, and report Data Management function activities The challenge was to "coach" the CM group into one which recognized all of the above responsibilities and responded with quality output to the NCCDS community, consistently. WHAT WAS IT LIKE BEFORE IMPROVEMENT? In order to fully appreciate the tremendous gains that have taken place in the CM section, a little time must be devoted to understanding where the section needed improvement. The major areas were: - Section Characteristics - Procedures - Tools - Communication Section Characteristics: There were 3.0 staff to support over 100 people project wide, which produced a total of 450k DSI for the NCCDS system. Although the staff was working in the CM functional area, most were only familiar with the product control aspect. There was no CM status, reports, involvement with the Technical Review Board (TRB) or Configuration Review Board (CRB), no documentation reviews, and no emphasis on quality of work at every level. The task leader was the only person with a college degree and the only person who knew most all machine platforms as well as being able to troubleshoot and analyze CM problems. The task leader was the only person who was cross trained and could step in and help out all areas in addition to helping out during crisis situations. The hours for all personnel were long and frustrating, with little praise for good work. CM had the responsibility to support 7 different software segments (CCS, GNSS, ITS, NFE, NTS, RAP, and SPS), on 4 different hardware platforms (VAX, UNISYS 1100, MASSCOMP, and Intel architecture), in 2 facility areas: The Development Test & Training (DT&T) and Operations. The Section Manager, although experienced and knowledgeable of the CM function, was new to the company and new to the NCCDS. Emphasis on training CM personnel or improving CM processes did not seem to be a priority. Procedures: Of the 7 segments which CM supported, only 4 systems had any written procedures. Three of these procedure sets were poorly written, incomplete, and incorrect in several areas. The other set of procedures were more of a history of the segment, rather than procedures needed to perform routine functions of that segment. There were few clear steps to follow in any sequential order. Because a new software segment was being developed, there were no procedures in that segment. With no staff assigned to that CM segment on a full time basis, there was little emphasis to write CM procedures for that segment. There were many ideas, troubleshooting mechanisms, tips, procedures, and methods written on sheets of paper gathered in notebooks which tended to be lost easily. The procedures that were documented were inconsistently written across segments. This did not support staff cross training. There was also no one place which housed all CM procedures. Worse, few people used the correct procedures which did exist. **Tools:** Simply stated, most tools which were available to the CM group at that time did not work. Custom made tool sets were not maintained thereby causing errors when unknowing staff used them. There was no time scheduled to investigate the root causes and correct problems, just time to fix them. There were many laborious work-arounds that staff used because automated routines were not available or the ability to keep them current did not exist. The inefficiencies resulted in long processing times, incorrect output, and longer fix times. The mere difficulty in using some of the tools themselves caused errors. These internal CM problems were having enormous effects on the rest of the project, in terms of schedule, reliability, cost, causing staff frustration and lowering confidence in the ability of CM to do the job. **Communication:** During this time, CM processing time requirements were not recognized on any official project schedules. The time CM required was discussed in management meetings, although internal schedules never reflected the resource. The section manager discussed with the development and test managers the need to "steal" a day on each end of "their" schedules to accommodate CM requirements. This method of acquiring schedule was not conducive to smooth transitions. Most times, the software deliveries were made on the last day of their schedule at 6:00pm and test expected to start the next day at 6:00am. There was no routine status accounting or reporting to the project of CM units processed, reports tracking documentation, or CM efficiency and productivity. In addition, there was little input from CM to the overall project planning process, needs, and problem areas. Participation in CSC Project Management System (PMS) planning, weekly reporting of CM activities to the Assistant Technical Representatives (ATRs), and monthly presentations to GSFC management of CM accomplishments/problems areas was weak. **WHAT WAS DONE?** There were two efforts undertaken to improve the CM function: 1) A management initiative to improve section processes and routine ways of conducting business, and 2) Establishment of process improvements through the participation of CM team members in the Task Oriented Process Improvement Committee (TOPIC). **MANAGEMENT INITIATIVES:** After assessing the situation, management devoted emphasis to 1) staffing 2) project participation 3) defining procedures 4) improving tools 5) providing status and reports, and 6) self evaluation of CM processes. Several areas were totally re-engineered. To remedy the staffing situation, over the next year and a half, there were 8-9 staff personnel hired to work in the CM function. An additional person was on loan, part time, to assist with tools and CM sponsored a summer hire, who helped with the CM database development. At the end of the CM personnel transition, all personnel had completed their bachelors, 3 people had completed their masters, 3 people were working on their masters, and 1 person was working on a PhD. This higher level of educated personnel was then applied to every segment, which allowed a different degree of work to be performed. In reality, this transition of personnel took nearly 2 years to evolve, and has never stopped. The increased capabilities of the personnel have allowed a much easier cross training of different personnel on different software segments. It reinforced the necessity to have educated and trained personnel and precipitated regular training for CM including internal classes, SEAS courses, vendor classes (both brought into CSC and attendance on vendor sites), and attendance at conferences. The higher level of personnel expertise enabled CM to be able to analyze, troubleshoot, and resolve problems within our own section. People who were doing the work and making errors were able to begin fixing them. This also enabled the group to have insight into what and where some of the root causes of the problems were. As CM began working more with project management, quality assurance, release leaders, and other technical people, the need for CM to identify processing time on schedules became a reality. Internal schedules contained references to CM time required as well as providing detailed planning schedules prepared by release leaders used to plan Integration, System Test, Acceptance Test, and Operations transitions. CM personnel were able to plan for work and knew what the project deadlines were and where CM fit into the big picture. CM also began to schedule machine/facility resources in the Software Development Facility (SDF), the DT&T, Emergency NCC (ENCC), and Operations areas. By this time the NCCDS had added two facilities; one a development facility in the CSC Greentec I area, and the other an ENCC at the GSFC facility. This added to the CM responsibility of maintaining equal configurations for each release. Having to maintain multiple releases at different test levels sometimes necessitated that CM have their own machine time to perform some processing and installation functions. CM therefore began to schedule resources in the required facilities and "piggy-backed" off other's scheduled time when there was no CM or other function impact. Procedures were another area which improved dramatically. Personnel have documented or updated all CM procedures. Procedure formats were standardized across all segments in a logical step by step fashion. They were also written to be user friendly, incorporating helpful processing notes. Today the procedures are used as a training tool for new CM personnel. They are also updated on a routine basis, as a part of the CSC Program Management System (PMS) accountability system. In addition to the documented detailed procedures, an NCCDS CM Software Plan was developed and is revised periodically. Two major efforts were undertaken to improve CM tools used on the CCS and SPS segments. 1. In 1989 a study was undertaken to determine the best CM tool to use on the VAX. After the investigation was complete a presentation and report was provided to GSFC. The decision was to continue to use the existing CSC written tool which would be enhanced and coupled with Digital Equipment Corporations MMS (Module Management System) tool. Task personnel basically completed the VAX tool effort in 1990. Upgrades have been added each year to continue improving tool productivity and efficiency. 2. Another effort was undertaken in 1990 to improve the Unisys tool. Although there were off-the-shelf tools evaluated, none provided the control, reporting, and speed that were desired. Over a period of one year, task personnel first identified the areas which required immediate attention and made the proper fixes. Second, desired enhancements were identified and gradually added. Both the fixes and enhancements were applied in an internal controlled manner. Internal Problem Reports were written and resolution recommendations were evaluated. Various fixes and enhancements were packaged together and released in builds to the tool. The build was first tested in a testbed on the SDF Unisys. After all bugs had been eliminated, it was inserted into the regular controlled tool which was used in the SDF. Figure 1 contains a high level overview of the SPS tool fixes and enhancements. A summary was presented to the project CRB, approved and then applied to the DT&T controlled version of the tool. These enhancements allowed the tool to run more efficiently and later several utilities were automated into a menu program. The benefits as a result of the tool improvements have been noticeable throughout the section and the project. No longer are incorrect software versions of a unit delivered to test. Listings are routinely run, reviewed, and archived for traceability purposes. These are used later for troubleshooting, if required. The two-three day test sessions have not been hindered by the inability of CM to locate an incorrectly assigned level dependent file. Should there be a problem, listings with diagnostic error messages assist in locating the source of the problem quickly and easily. Another tool enhancement to the section was the creation of a CM relational data base to provide traceability, reports, and on line information. Up to this time there was no routine accountability of CM activities to the project. There were no reports or statistics kept within the section. Task personnel developed a data base to house CM data from the Internal Software Delivery Forms (ISDF) and data regarding the CM processing. Data such as segment, subsystem, type of delivery, ISPR/SPR/STR number, unit name, type of unit, date received, and date processed was collected and entered. A units processed report for each release is provided to the project each week. Another report showing elapsed time indicates CM efficiency in processing deliveries from the time of receipt to the time available at any level for testing. Graphs are produced at each project phase for each release and show what (if any) CM problems are occurring on each segment. Figure 2 shows the CM problems by segment for Release 93.1 during the System Test phase. These weekly graphs act as a catalyst for internal CM Defect Causal Analysis (DCA) and in continuing process improvement. This database eventually was merged with the System Engineering Project Database (SEDB) and is known today as the Configuration Management Database (CMDB) and is maintained and has been improved by the System Engineering database section. CM has code counter tools for each of the NCCDS segments. Over the last two years, each tool has been upgraded to be more efficient, easier to use, and has been fixed to reduce errors. All of the tool improvements have enabled the CM section to provide products to both internal and external customers faster, better, cheaper, and more accurately. THE CM TASK ORIENTED PROCESS IMPROVEMENT COMMITTEE (TOPIC): At the same time the above management initiatives were taking place, the CM group began setting aside a small amount of time each week to discuss changes in the section that would improve quality, productivity, worker satisfaction, and reduce errors. In 1990, with CSCs increased interest in Total Quality Management, the group became known as the Task Oriented Process Improvement Committee (TOPIC). The section manager sponsored the group, and every six-eight months the group chose a new facilitator. The first project the group undertook was to design a set of checklists which were to be used as a verification tool and used in conjunction with the processing procedures. Although the processing procedures were being revised, the group wanted a high level composite list of "musts" that should be accomplished that a second person could verify to ensure the proper steps had been followed. Each segment lead prepared a set of "checks" for each segment and each processing phase. For example, the CCS checklist for processing a delivery includes seven "checks". The verifier completes the checklist as the actual item is checked. The verification is a combination of checking on the terminals and checking the printouts. The checklists can be used for test levels 1, 2, and 3 and are signed and dated by the verifier. An example of an SPS checklist is shown in Figure 3. Other checklists have been designed for phases such as: 1) Creating a Baseline, 2) Processing a Delivery, 3) SDP/DDT Transfer Tape Update, 4) Creating Failover Tapes, 5) Installing a Release, 6) Making Operational Tapes, 7) Processing Symbolics, Procs, Schema, Templates, Maps and QLP Reports, 8) Updating a Baseline, 9) Installing a Release Into OPS, and ![Figure 3](image-url) 10) Deleting Units. The checklists are tailored to incorporate segment differences. Another process established to be used with the checklists, was the incorporation of a reviewer. Usually, the reviewer is either the task leader or the section manager. The review session takes place prior to the delivery or product being installed in the SDF. The processor, verifier, and reviewer go over the delivery from beginning to end to ensure all steps have been completed properly and without error. All printouts, listings, checklists, and original delivery paperwork are reviewed and retained by the CM lead for the segment. Any future inquiries into a delivery, can be recovered and investigated if required. This three-pronged approach has added discipline to the overall process and assisted greatly in the reduction of errors. A partial list of CM TOPIC achievements is shown in Figure 4. <table> <thead> <tr> <th>CM TOPIC ACHIEVEMENTS</th> </tr> </thead> <tbody> <tr> <td>• Standard Verification Check Lists</td> </tr> <tr> <td>• Standard Code Count Form</td> </tr> <tr> <td>• Computer Time Usage Log Form</td> </tr> <tr> <td>• Operational Software Installation Form (OSIF)</td> </tr> <tr> <td>• Monthly Backup Forms</td> </tr> <tr> <td>• Delivery Form Error Reductions</td> </tr> </tbody> </table> Figure 4 The TOPIC also initiated what they called a "shake down" test. CM processes all the deliveries for a given release for a particular group (i.e Integration Test, System Test, or Acceptance Test) to begin testing. After the installation is made on either the SDF or the DT&T machines, but prior to turnover to the test group, CM coordinates a "shake down" test. This test is a multi discipline team effort comprising the CM segment leads, an integration tester or system tester, a computer operator, maintenance and data base personnel. The CCS, ITS, and SPS segments are brought up, connected, and are checked to ensure all segments "talk" to each other. Although no functions are performed, data passed, or test cases run, this simple check has pinpointed several errors. These problems were cleared up prior to the baseline being provided to the "internal test customer". Time is saved by CM and the testing groups and customer satisfaction is enhanced. **WHAT WAS IT LIKE AFTER IMPROVEMENTS?** **Specific:** There have been many improvements over the past three years. In addition to the overall management initiatives and TOPIC achievements there have been other individual task improvements. Listed below are only those specific improvements which have been documented through either the CSC Code 550 or 530 ### Cost Avoidance System: <table> <thead> <tr> <th>IMPROVEMENT</th> <th>STAFF HOURS</th> <th>$ SAVINGS/YEAR</th> </tr> </thead> <tbody> <tr> <td>1. Revised NTS Build Procedure</td> <td>- 24 staff hours</td> <td></td> </tr> <tr> <td></td> <td>- 5500 sheets of treated paper per year</td> <td></td> </tr> <tr> <td>2. Improved CM Procedures</td> <td>- 60 staff hours</td> <td></td> </tr> <tr> <td>3. Simplified Delivery Process</td> <td>- 32 staff hours</td> <td></td> </tr> <tr> <td>4. Modified CCS Compilation Process</td> <td>- 150 staff hours</td> <td>- 18 VAX CPU hours in 1991</td> </tr> <tr> <td></td> <td></td> <td>98 VAX CPU hours in 1992</td> </tr> <tr> <td></td> <td></td> <td>106 VAX CPU hours in 1993</td> </tr> <tr> <td>5. Designed Standard DSI Form</td> <td>- 114 staff hours</td> <td>- $14,022 over 3 years</td> </tr> <tr> <td>6. Eliminated Duplicate DSI Counts and Reduced Errors</td> <td>- $5,530 over 3 years</td> <td></td> </tr> <tr> <td>7. Revised and Designed New CM Valtab Procedures and Form</td> <td>- 26 staff hours</td> <td></td> </tr> </tbody> </table> **Statistical:** Because either little or partial data was maintained in the late 80's in the CM section, the best possible attempt has been made to present fair and accurate data. Emphasis has been placed over the last few years on quality deliveries to our internal customers. Some of those internal customers are Integration and System Test. During the Integration Testing phase, Integration Software Problem Reports (ISPRs) are written to document problems. Available data show there was a 50% reduction in errors over the three builds after the 89.1 Release series. From Release 90.1 to Release 93.1, CM ISPR errors decreased to around 11%. During the Release 3 Build 0 integration testing, there were zero CM errors out of a total of 51 problems. CM was accountable for nearly 20% of the project's Software Problem Reports (SPRs), written during System Test phase, up through the 89.1 Release series. Figure 5 shows the SPR trend for earlier releases. During the time many of the improvements were initiated, Release 90.1 was being developed and CM SPRs fell to about 13%. This trend continued into the development of Release 91.1A, and CM SPRs dropped to under 6%. By the time Release 92.1 was being System Tested, CM SPRs were down to just over 4%. More recently, as shown in Figure 6, the trend has continued to be the same. Release 93.0 found CM SPRs at zero. Release 93.1 was a much larger development effort and CM SPRs were around 2.5%. Release 3 Build 0 is currently under test and to date, CM SPRs are .8%. Clearly, the number of errors attributable to CM has decreased substantially. Obviously, the time spent in correcting problems has decreased accordingly, and a much greater confidence level has been achieved from groups receiving CM products. The project can now count on CM to make internal schedules. Figure 7 shows a composite of the number of total problems against the number of CM problems. This improvement has also been seen in installations and products delivered to GSFC. During the Release 89.1 series of deliveries to Acceptance Test, CM accounted for over 13% of the errors identified in the release. Acceptance Test documents problems on a System Trouble Report (STR). Over the next three releases, problems attributable to CM fell to less than 2.5%. There were also no CM STRs for Release 93.0 and only one CM STR for Release 93.1.1, which went operational recently. The turn around in the percentage of CM problems has been dramatic over the past few years. The quality and dependability of CM products and services to our customers has been increased by these measurable results. **Participation:** Key to the improvements has been the acceptance of all CM team members to want to make a difference and to make things better. Early in the process, team members recognized the need to become more efficient and more productive. As the opportunity became available to participate in TQM committees all CM section members took advantage. The contributions to the CM TOPIC through the years has been directly responsible for many of the CM successes and improvements. CM has had 100% participation in the five major TQM committees. Two of the five first committees were facilitated by CM members. All CM team members have been involved in Process Improvement Committee (PIC) Process Action Teams (PATs). This participation across project functions to improve a process has provided team members with insight into resolving multi disciplined problems which benefit everyone. The enthusiasm and willingness of CM team members to participate at all levels of TQM activities has strengthened the project, the section, and the individuals involved. Everyone wins. **Recognition:** When a job needs to be done, it should not be done to seek recognition. Over time, as each year rendered better results, individuals within the CM group and the team as a whole realized technical and professional recognition. Listed below are some of those achievements: - Documented and received four Flight Dynamics Quality Improvement Ledgers citing success stories - Many of the CM achievements have been publicized in the SEAS Total Quality Management Highlights - Individual CM members and the CM team have received NCC Awards and Recognition Committee (ARC) monthly recognition certificates - Documented and received three recent cost avoidance success reports - Two CM team members received FDTG Engineering Employee of the Year Awards - One CM team member was honored as the first recipient of the NCC Project Dedication, Adaptability, Team Spirit, Unique Solutions and Motivation (DATUM) Award - One CM team member was a winner of the SEAS TQM Involvement Award The team was also nominated for the 1992 SEAS Quality Service Award and an individual nominated for the 1993 NTG Quality Service Award. In addition, there have been letters of commendation from other CSC codes and from the GSFC customer on CM team members excellent service and support. CONCLUSION This paper has listed many CM improvements over a wide spectrum and shown meaningful statistical evidence of positive results. The above findings, however, do not mean the group is perfect or that the job is done. The challenge is to provide "continuous" improvements. Because the gap has been tremendously narrowed, future improvements will probably not be measured in whole percentages. The hard job will be to continue to chip away until the goal is obtained. The goal is to have zero processing errors, to provide internal and external customers CM products and services which are error free, and to continue to increase CM efficiency and productivity. "In CM, we don't make the software... we make it better!"
{"Source-Url": "https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19940016854.pdf", "len_cl100k_base": 5275, "olmocr-version": "0.1.53", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 28788, "total-output-tokens": 5599, "length": "2e12", "weborganizer": {"__label__adult": 0.00041413307189941406, "__label__art_design": 0.000568389892578125, "__label__crime_law": 0.00048661231994628906, "__label__education_jobs": 0.0078887939453125, "__label__entertainment": 9.518861770629884e-05, "__label__fashion_beauty": 0.00022041797637939453, "__label__finance_business": 0.01210784912109375, "__label__food_dining": 0.0003767013549804687, "__label__games": 0.0007023811340332031, "__label__hardware": 0.0026416778564453125, "__label__health": 0.00048613548278808594, "__label__history": 0.0003504753112792969, "__label__home_hobbies": 0.00025916099548339844, "__label__industrial": 0.002849578857421875, "__label__literature": 0.000263214111328125, "__label__politics": 0.0002002716064453125, "__label__religion": 0.0003864765167236328, "__label__science_tech": 0.031219482421875, "__label__social_life": 0.00018084049224853516, "__label__software": 0.0596923828125, "__label__software_dev": 0.87744140625, "__label__sports_fitness": 0.0002849102020263672, "__label__transportation": 0.0006999969482421875, "__label__travel": 0.0002639293670654297}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 25228, 0.01415]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 25228, 0.08646]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 25228, 0.96891]], "google_gemma-3-12b-it_contains_pii": [[0, 1653, false], [1653, 4240, null], [4240, 6919, null], [6919, 9895, null], [9895, 11910, null], [11910, 13972, null], [13972, 16062, null], [16062, 18553, null], [18553, 20510, null], [20510, 21771, null], [21771, 24369, null], [24369, 25228, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1653, true], [1653, 4240, null], [4240, 6919, null], [6919, 9895, null], [9895, 11910, null], [11910, 13972, null], [13972, 16062, null], [16062, 18553, null], [18553, 20510, null], [20510, 21771, null], [21771, 24369, null], [24369, 25228, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 25228, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 25228, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 25228, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 25228, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 25228, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 25228, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 25228, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 25228, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 25228, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 25228, null]], "pdf_page_numbers": [[0, 1653, 1], [1653, 4240, 2], [4240, 6919, 3], [6919, 9895, 4], [9895, 11910, 5], [11910, 13972, 6], [13972, 16062, 7], [16062, 18553, 8], [18553, 20510, 9], [20510, 21771, 10], [21771, 24369, 11], [24369, 25228, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 25228, 0.22727]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
baeea5ac763c4d73dbc1caf66b8d83cd856dac53
RasPipe: A Raspberry Pi Pipeline Viewer, Part 1 Created by Brennen Bearnes https://learn.adafruit.com/raspipe-a-raspberry-pi-pipeline-viewer Last updated on 2021-11-15 06:25:06 PM EST # Table of Contents ## Overview ## Shell Filters ### machine_stars.py - Clone the Adafruit-RasPipe Repo with Git - Line by Line ### raspipe.py - Imports - RasPipe is a Class - What the Heck is a Class? - raspipe.py is a Utility and Takes Options - RasPipe Has a Grepping Penguin - RasPipe Handles Mouse Clicks - RasPipe Plays Sound ## Pygame on the PiTFT and Next Steps - raspipe_pitft.sh & machine_stars_pitft.sh - What Now? Overview The other day I was thinking about how I could use a Raspberry Pi for a practical demonstration of some Unix shell basics. At right around the same time, I was using a neat little shell utility called pv (https://adafruit.it/eMk), for pipe viewer. What pv does is sit in the middle of a pipeline and display a progress bar, so you can have some idea of whether a long-running process is actually processing, and how much longer you'll have to wait for it to finish. It's great for things like copying big disk images to SD cards. ``` root@exuberance:/home/brennen/ios# pv ./raspbian-victim.img | dd of=/dev/sdc ``` So ok, I thought, I have this PiTFT display (https://adafruit.it/dDE). What if I made a pipeline viewer out of the Pi and stuck it on top of my regular monitor? It turns out the basics of that are pretty easy to do, but the specifics are a good chance to experiment with some interlocking little technologies to make something useful (or at least cool to look at). In part one, we'll look at: - Pipes, filters, and basic data processing with shell tools in Bash. - Simple Python filter scripts. - Pygame for data visualization, optionally displayed on the PiTFT. In part two, we'll look at - netcat for easily slinging data over network sockets. - SSH as a secure and authenticated channel for data pipelines between machines. - Node.js streams. - Creating a simple Flask (https://adafru.it/cFR) application. This guide assumes a little familiarity with basic programming concepts and the command line (https://adafru.it/slE), but is generally aimed at the beginner. Shell Filters In An Illustrated Guide to Shell Magic: Typing Less & Doing More (https://adafru.it/sds), I talked about writing shell filters (https://adafru.it/Cfg) in a handful of languages. Let's revisit a version of one of those, stars.py: ```python #!/usr/bin/env python # encoding: utf-8 import sys import re line = sys.stdin.readline() while line: stars = re.sub(r'\S', '★', line) sys.stdout.write(stars) line = sys.stdin.readline() ``` This is some fairly simple Python. It takes some text from standard input one line at a time, uses a regular expression to convert any non-space character to a ★, and writes each line back to standard output. In practice, that looks like this: ``` pi@raspberrypi ~ $ ``` Usually, we write code like this to search, transform, store, or otherwise munge data. But what if, to start, we just want to do something more visually interesting with the output than view some characters? Pygame (https://adafru.it/eMm) is a set of Python libraries for making it easy to write games. In turn, it wraps up SDL (https://adafru.it/eMn), a popular cross-platform graphics and sound library. You probably won't be writing the next blockbuster first-person shooter in Pygame, but it's a great way to experiment with simple games that will run on all sorts of computers, including the Pi. For some good examples, you can have a look in the python_games folder in your home directory on the Pi. Here's squirrel.py, which you can run with python squirrel.py: If you cd ~/python_games and run nano squirrel.py, you can see it's about 400 lines of Python (https://adafru.it/Cfh). This could be a little intimidating if you don't know Python - let's start with something a little simpler. machine_stars.py If you read our guide on standard I/O (https://adafru.it/CeM), you might remember this little metaphor for a filter program like stars.py that takes standard input and produces transformed output: I just wrote a program called `machine_stars.py` that uses Pygame to animate this idea like so: Clone the Adafruit-RasPipe Repo with Git In order to experiment with this program and the other code covered in this guide, you should get a copy on your Raspberry Pi. Open up a terminal and enter the following: ```bash $ git clone https://github.com/adafruit/Adafruit-RasPipe.git ``` What just happened? Well, Git is a version control system, a tool used to record the changes made to a repository of files over time. GitHub is a popular hosting service for Git repositories. (In addition to cloning a local copy onto your own computer, you can [browse all of the code used in this guide on GitHub](https://adafruit.it/eMp).) You should now have a directory with some Python files and other miscellaneous things in it. Have a look around: ```bash cd Adafruit-RasPipe ls ``` In order to test `machine_stars.py`, you can do something like the following: ```bash shuf /usr/share/dict/words | head -50 | ./machine_stars.py ``` This will shuffle a long list of dictionary words, chop off the first 50, and pass them to the input of `machine_stars.py`, which should animate them falling into a little machine and being transformed into stars. If you’re using an Adafruit PiTFT display, do the following instead: ```bash export SDL_FBDEV=/dev/fb1 shuf /usr/share/dict/words | head -50 | ./machine_stars.py ``` Open up `machine_stars.py` in Nano and have a look: ```bash nano machine_stars.py ``` Let's step through this program a chunk at a time. ```python #!/usr/bin/env python import sys import random import pygame ``` The first line is a shebang. It tells the Linux kernel to run the rest of the program using `/usr/bin/python`. The next three are imports, telling Python that we'll be using modules or libraries which contain code already written for us. - `sys` contains various ways to interact with the larger system - in this case stdin and stdout. - `random` lets us grab pseudo-random numbers so we can vary certain parts of our program. - `pygame` lets us do lots of things with graphics and sound. These lines build the initial state of our program, starting the Pygame engine with `pygame.init()` (https://adafru.it/eMq), and creating a 320x240 pixel screen, then painting it white. `pygame.Color(255, 255, 255)` returns a Color object (https://adafru.it/eMr) with its red, green, and blue values set to the maximum of 255. Each of these can be changed to anything between 0 and 255. `pygame.display.set_mode()` (https://adafru.it/aQC) actually returns a Surface object (https://adafru.it/eMs). You don't need to worry about that very much now, but later you'll want to remember that in Pygame, Surfaces are how you work with images in general. Next we load some image files (https://adafru.it/aQE). These are Surfaces too! With `pygame.image.load('machine.png')`, we get a Surface for the file `machine.png`. The `.convert_alpha()` method returns a version of this image converted to display faster on our screen, complete with transparency - it's not strictly necessary, but it might make things run smoother. If you have a Surface, you can get an object that represents the rectangle it occupies with `get_rect()` (https://adafru.it/eMs). In turn, you can position the Surface by changing values like `machine_rect.left`. Here, we set the left edge of our machine image at 10 pixels from the left of the screen and the top at 120 pixels from the top. Screen.blit(machine_img, machine_rect) draws the machine image on top of the screen Surface (https://adafruit.it/eMs), at the coordinates provided by machine_rect. We only need to do this once, because everything else we draw will be on different parts of the screen. We also get an image of a star. We’ll display copies of this a bunch of times later on. ```python # This will hold some input lines: stars_length = 0 offset = 0 # Start building a list of things to display from stdin: display_lines = [sys.stdin.readline()] ``` stars_length will be the number of stars to display - more about that in a while. offset will be used later to offset the falling words from the top of the screen. display_lines = [sys.stdin.readline()] creates a list with one element: The first line in our standard input. sys.stdin.readline() gets the stdin one line at a time. ```python while len(display_lines) > 0: ``` Next, we start a loop. While the length of the display_lines list is greater than zero, everything in the following indented section will be executed repeatedly. Each trip through this loop will serve two purposes: 1. Get the next line of standard input, if there is one. 2. Perform one frame of animation. ```python # Get the next available line from stdin: line = sys.stdin.readline() if line: display_lines.insert(0, line) ``` First, we get the next line of stdin. Next, we check the truth value of line. The sys.stdin.readline() call will only return an empty string if there's no more input, and Python considers empty strings false, so we put the value of line at the front of the display_lines list only if it contains new input. Next, we're going to decide how many stars to display. If we have more than six lines to display, or we're not going to get any more lines, we'll pop() the last line off of display_lines, then set stars_length to the number of characters it contains. (The different ways we use a len() call here may be a bit confusing: In Python, it's a built-in function used to get the length of many different types of things, including both lists like display_lines and strings like the individual elements contained in display_lines.) If we got an empty string for line, we'll also increment a variable called offset, which we'll use to push the lines of text further down the screen once no more are coming in from stdin. This makes it look like they're falling towards the machine. Now we render the contents of display_lines falling towards the machine. The heart of this code is a for loop. render_me is set equal to each element of display_lines in turn, and the indented code is executed with that value. Inside the loop, we use pygame.font.Font() to get a Font object which can render a Surface containing text, and then (just like with the machine image above), draw this on top of the screen, centered at 64 pixels from the left and y pixels from the top of the screen. We call `render_me.rstrip()` to get a version of the string with any whitespace chopped off (including newlines, which will usually be present). Each time through the `for` loop, we increase `y` by 20. After all of `display_lines` has been rendered, we update the display with this frame of the animation. ```python # Display stars leaving machine's output. Stars are scaled to a random height & width between 8 and 30 pixels, then displayed at a random vertical location on the screen +/- 8 pixels from 185: if stars_length &gt; 0: star_x = machine_rect.right for i in range(0, stars_length): star_w = random.randrange(8, 30) star_h = random.randrange(8, 30) star_img = pygame.transform.smoothscale(orig_star_img, (star_w, star_h)) star_rect = star_img.get_rect() star_rect.left = star_x star_rect.top = 185 + random.randrange(-8, 8) screen.blit(star_img, star_rect) pygame.display.update() # Chill out for 15 milliseconds: pygame.time.wait(15) # Move start of next star to end of the current one, and quit # drawing stars if we’ve run off the edge of the screen: star_x += star_w if star_x &gt;= 320: break pygame.time.wait(100) ``` Finally, we'll show `stars_length` stars emerging from the side of the machine. `star_x = machine_rect.right` sets the first star's horizontal position to the righthand side of the machine. `for i in range(0, stars_length)` starts a loop that will run `stars_length` times. Inside the loop, we use `random.randrange()` to get stars of different widths and heights each time through, where `pygame.transform.smoothscale(orig_star_img, (star_w, star_h))` makes a smoothly scaled copy of the original star image. We also randomize each star's vertical placement a bit. `pygame.time.wait(15)` pauses for 15ms between each star, and `pygame.time.wait(100)` waits for 100ms before the main `while` loop starts over. You can play with all of these timing and randomization values to get different effects. You should also be able to pipe just about any text in. Try, for example: ``` dmesg | tail -10 | ./machine_stars.py ``` **raspipe.py** The star-making machine is an interesting visualization of a pipeline, but maybe it would be better to use more of the available screen real-estate. For something a bit different, try running some text through `raspipe.py`: ``` shuf /usr/share/dict/words | head -500 | ./raspipe.py ``` ``` parqueted caeulist's thoughtfulness Semitic flanks Christendoms gate's Triangulum's Salinas kith rightfully resurgent operational ``` With raspipe.py running, try clicking anywhere in the window and the display should switch to something a little more abstract: ``` Xia Xia Xia ``` You can click again to switch back to the text display. The script itself reads a lot like `machine_stars.py`, but there are a few key differences. Open it up with Nano and let's have a look at some of the important ones (if you'd rather view it in a browser, you can [find the code on GitHub](https://adafru.it/eMu)): ``` nano raspipe.py ``` ### Imports The first thing you'll probably notice is that there're a couple of extra imports: ``` #!/usr/bin/env python import getopt import re import sys import pygame ``` The `re` module, which you might remember from `stars.py`, will let us match on regular expressions. We use this to let the user optionally specify a pattern to highlight. More about that when we get to the penguin. The `getopt` module will let us easily parse some command-line options. ### RasPipe is a Class Next, instead of just writing a series of procedural statements in order, I wrote RasPipe as a class. An outline of its structure looks something like this: ```python class RasPipe: # Some properties are here. def __init__(self, infile): """Create a RasPipe object for a given input file.""" def setfont(self, size): """Set a display font of a given size.""" def wait_for_click(self): """Wait for the user to click on the screen (or quit).""" def toggle_stars(self): """Toggle whether we should display stars.""" def scale_display(self): """Set the current font size and delay based on amount of input.""" def penguin_think(self, thought): """Have a penguin appear and think a thought.""" ``` What the Heck is a Class? Python, like most modern languages, provides support for a technique known as Object Oriented Programming, often abbreviated OOP or OO. OO can be a very deep topic, but at heart it isn't as complicated as it's often made out to be. The short version is that it offers a way to bundle together state (variables, often called properties when they're part of an object) with behavior (functions, often called methods when they're part of an object). The RasPipe class describes an object. You can think of an object as a sort of box around a collection of variables (properties) and functions (methods). Here's a very simple Python class and some code which gets an object (an instance of this class) and calls one of its methods: ```python #!/usr/bin/env python class HelloSayer: name = "" def __init__(self, name): self.name = name def speak(self): print("Hello " + self.name) s = HelloSayer("Ralph") s.speak() ``` `def foo(param1, param2):` is how you define a function in Python. The first parameter to object methods in Python is always the object instance itself. This is how objects refer to their own properties and call their own methods. `__init__()` is a special method that gets called when we create an object instance with something like `s = HelloSayer("Ralph")`. RasPipe works just the same, with more properties and methods. raspipe.py is a Utility and Takes Options Most of what's in `raspipe.py` is a class definition, but if you look at the bottom you'll see a few lines that turn it into a standalone utility program and let it take some useful options: ```python # Handle running this file as a standalone script. if __name__ == '__main__': rp = RasPipe(sys.stdin) opts, args = getopt.getopt(sys.argv[1:], 'sx:y:) for opt, arg in opts: if opt == '-x': rp.size[0] = (int(arg)) if opt == '-y': rp.size[1] = (int(arg)) if opt == '-r': rp.grep_for = arg if opt == '-s': rp.toggle_stars() rp.run() ``` The `if __name__ == '__main__':` bit is a little magic that lets us check whether the current file is being run as the main Python program. (This way, other programs can include and reuse the RasPipe class for their own purposes - we'll get to that in Part 2.) With `rp = RasPipe(sys.stdin)` we create an instance of RasPipe with `self.infile` set to `sys.stdin`. (To see everything that happens here, have a look at the `__init__()` defined at the top of the class.) Next, we use the `getopt` ([https://adafruit.it/eMv](https://adafruit.it/eMv)) module to see if the user passed in any command line arguments. This lets us do the following: <table> <thead> <tr> <th>Option</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>-s</code></td> <td>Start with stars enabled instead of scrolling text.</td> </tr> <tr> <td><code>-x 640</code></td> <td>Start with a screen 640 pixels wide.</td> </tr> <tr> <td><code>-y 480</code></td> <td>Star with a screen 480 pixels tall.</td> </tr> </tbody> </table> We could easily add other options here. As an exercise, you might try adding a feature to change a property like `bgcolor` from the command line. Finally, we call `rp.run()`, which is the method that does most of the heavy lifting. **RasPipe Has a Grepping Penguin** Suppose you have a lot of output streaming through `raspipe.py`, and want to highlight lines that match a particular pattern? Normally, you'd use a tool like `grep` (https://adafruit.it/Cfi) to accomplish this. Fortunately, Python supports its own variety of regular expressions, so it's pretty easy to give our program its own simple version of grep-like features. For example, if I wanted to check the output of `dmesg` for things about ethernet interfaces, I could do: ``` dmesg | ./raspipe.py -r '.*eth0.*' ``` And see something like the following: This is done inside `run()` by checking each line to render against a regular expression: for render_line in to_render: # Show a penguin thinking if we have a regular expression to # search for and found a match: if self.grep_for is not None: if re.match(self.grep_for, render_line): matched_line = render_line And later calling a special method to draw the penguin and its thought: if matched_line is not None: self.penguin_think(matched_line) That function looks like this: def penguin_think(self, thought): """Have a penguin appear and think a thought."" r = self.penguin.get_rect(left=50, bottom=self.height) self.screen.fill(self.fgcolor, [0, 10, self.width, r.top]) self.screen.blit(self.penguin, r) thought_surface = self.font.render(thought, True, self.bgcolor) thought_r = thought_surface.get_rect(left=5, top=30) self.screen.blit(thought_surface, thought_r) pygame.display.update() RasPipe Handles Mouse Clicks Pygame offers a way to process all sorts of user input. In this case, we only really deal with one interaction: When the user clicks on the screen, we toggle the display between a scrolling-text mode and a mode that displays little star images. To see how this is done, have a look at the first few lines of `run()`: def run(self): """Process standard input."" line = self.infile.readline() while line: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: self.toggle_stars() Just like in `machine_stars.py`, we’re looping over the contents of standard input. Here, however, we also check the Pygame event loop (https://adafruit.it/eMx) and make a decision if there’s been a mouse click (or if the window has been closed, which will give us a pygame.QUIT). RasPipe Plays Sound You may have noticed this bit in `__init__`: ``` # A little bit of sound. pygame.mixer.init() self.click = pygame.mixer.Sound('./tick.wav') ``` ...and later on in `run()`: ``` if self.tick % self.display_lines == 0: self.click.play() ``` This just plays a clicking noise every so often. Pygame's `pygame.mixer.music` can be used to do all sorts of things with individual sound files, and `pygame.mixer.music` allows for a custom soundtrack. Pygame on the PiTFT and Next Steps If you have a PiTFT display, you can use it to display the output from Pygame, and avoid the overhead of running the desktop system at the same time. Since my goal is to use a PiTFT as an auxiliary display to my main computer, I've been targetting a 320x240 display. For this guide, I'm using the 320x240 2.8" TFT+Touchscreen for Raspberry Pi. We have [detailed installation instructions here](https://adafruit.it/eZZ). Make sure you configure the console to appear on the PiTFT. Under the hood, Pygame uses SDL for graphics and audio. SDL needs to be told what device it should use as a framebuffer display. Remember these commands from earlier? ``` export SDL_FBDEV=/dev/fb1 shuf /usr/share/dict/words | head -50 | ./machine_stars.py ``` `export` just tells the shell that a variable should be available to processes you start within the shell. `SDL_FBDEV=/dev/fb1` tells the SDL library what device file maps to the display we want it to use. raspipe_pitft.sh & machine_stars_pitft.sh You could remember to export this variable every time you open up a new shell, but there’s a good chance you’ll forget. A better approach might be to write a wrapper script like this one: ```bash #!/usr/bin/env bash # A wrapper for displaying raspipe.py output on /dev/fb1 export SDL_FBDEV=/dev/fb1 cat /dev/stdin | ./raspipe.py $@ ``` Since `/dev/stdin` is just a file from the perspective of the script, we can pass it off to a command really easily. We also tack on `$@`, which is all the arguments to the script. This way we can say things like `./raspipe_pitft.sh -r '*.foo.*'` and `raspipe.py` will see the right options. You can see this in the Adafruit-RasPipe repository, as `raspipe_pitft.sh`, and it can be invoked like so: ``` shuf /usr/share/dict/words | head -50 | ./raspipe_pitft.sh ``` If you write your own wrapper script, you’ll want to tell Linux that it’s executable. Let’s say you decide to write the equivalent for `machine_stars.py`. First, open a new file in Nano: ```bash nano machine_stars_pitft.sh ``` And then add the following: ```bash #!/usr/bin/env bash # A wrapper for displaying machine_stars.py output on /dev/fb1 export SDL_FBDEV=/dev/fb1 cat /dev/stdin | ./machine_stars.py $@ ``` Finally, use `chmod` to set the executable bit on your new script: ```bash chmod +x ./machine_stars_pitft.sh ``` Now you should be able to test like so: What Now? By now, hopefully you have a better idea of how to use Pygame for simple visualizations. Next, we'll explore building a simple network wrapper for RasPipe so you can send it data to visualize from anywhere on the network. Stay tuned for Part 2!
{"Source-Url": "https://cdn-learn.adafruit.com/downloads/pdf/raspipe-a-raspberry-pi-pipeline-viewer.pdf", "len_cl100k_base": 5911, "olmocr-version": "0.1.50", "pdf-total-pages": 22, "total-fallback-pages": 0, "total-input-tokens": 37169, "total-output-tokens": 7007, "length": "2e12", "weborganizer": {"__label__adult": 0.00033020973205566406, "__label__art_design": 0.00037479400634765625, "__label__crime_law": 0.00013947486877441406, "__label__education_jobs": 0.00033211708068847656, "__label__entertainment": 9.310245513916016e-05, "__label__fashion_beauty": 0.00010913610458374023, "__label__finance_business": 6.335973739624023e-05, "__label__food_dining": 0.00031447410583496094, "__label__games": 0.0007615089416503906, "__label__hardware": 0.00543975830078125, "__label__health": 0.00017392635345458984, "__label__history": 0.00014090538024902344, "__label__home_hobbies": 0.00016570091247558594, "__label__industrial": 0.0003669261932373047, "__label__literature": 0.00013566017150878906, "__label__politics": 0.00010567903518676758, "__label__religion": 0.0004329681396484375, "__label__science_tech": 0.007110595703125, "__label__social_life": 7.456541061401367e-05, "__label__software": 0.01419830322265625, "__label__software_dev": 0.96826171875, "__label__sports_fitness": 0.00020444393157958984, "__label__transportation": 0.0003199577331542969, "__label__travel": 0.00014591217041015625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 23766, 0.00757]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 23766, 0.57822]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 23766, 0.84593]], "google_gemma-3-12b-it_contains_pii": [[0, 187, false], [187, 619, null], [619, 1408, null], [1408, 1811, null], [1811, 3159, null], [3159, 4165, null], [4165, 4549, null], [4549, 5575, null], [5575, 6282, null], [6282, 7644, null], [7644, 9301, null], [9301, 10573, null], [10573, 12538, null], [12538, 13402, null], [13402, 14957, null], [14957, 16361, null], [16361, 17901, null], [17901, 18818, null], [18818, 20629, null], [20629, 22086, null], [22086, 23510, null], [23510, 23766, null]], "google_gemma-3-12b-it_is_public_document": [[0, 187, true], [187, 619, null], [619, 1408, null], [1408, 1811, null], [1811, 3159, null], [3159, 4165, null], [4165, 4549, null], [4549, 5575, null], [5575, 6282, null], [6282, 7644, null], [7644, 9301, null], [9301, 10573, null], [10573, 12538, null], [12538, 13402, null], [13402, 14957, null], [14957, 16361, null], [16361, 17901, null], [17901, 18818, null], [18818, 20629, null], [20629, 22086, null], [22086, 23510, null], [23510, 23766, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 23766, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 23766, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 23766, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 23766, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 23766, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 23766, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 23766, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 23766, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 23766, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 23766, null]], "pdf_page_numbers": [[0, 187, 1], [187, 619, 2], [619, 1408, 3], [1408, 1811, 4], [1811, 3159, 5], [3159, 4165, 6], [4165, 4549, 7], [4549, 5575, 8], [5575, 6282, 9], [6282, 7644, 10], [7644, 9301, 11], [9301, 10573, 12], [10573, 12538, 13], [12538, 13402, 14], [13402, 14957, 15], [14957, 16361, 16], [16361, 17901, 17], [17901, 18818, 18], [18818, 20629, 19], [20629, 22086, 20], [22086, 23510, 21], [23510, 23766, 22]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 23766, 0.01316]]}
olmocr_science_pdfs
2024-11-29
2024-11-29
4e77e92ac6f7a7ac6e40a8c196e36626f6ab2f51
Retina: An open-source tool for flexible analysis of RTC traffic Original Retina: An open-source tool for flexible analysis of RTC traffic / Perna, Gianluca; Markudova, Dena; Trevisan, Martino; Garza, Paolo; Meo, Michela; Munafò, Maurizio. - In: COMPUTER NETWORKS. - ISSN 1389-1286. - ELETTRONICO. - 202:(2022), p. 108637. [10.1016/j.comnet.2021.108637] Availability: This version is available at: 11583/2944312 since: 2021-12-10T14:14:19Z Publisher: Elsevier Published DOI:10.1016/j.comnet.2021.108637 Terms of use: This article is made available under terms and conditions as specified in the corresponding bibliographic description in the repository Publisher copyright Elsevier postprint/Author's Accepted Manuscript © 2022. This manuscript version is made available under the CC-BY-NC-ND 4.0 license http://creativecommons.org/licenses/by-nc-nd/4.0/. The final authenticated version is available online at: http://dx.doi.org/10.1016/j.comnet.2021.108637 (Article begins on next page) Retina: An Open-Source Tool For Flexible Analysis of RTC Traffic Gianluca Perna\textsuperscript{a}, Dena Markudova\textsuperscript{a}, Martino Trevisan\textsuperscript{a,}\textsuperscript{*}, Paolo Garza\textsuperscript{a}, Michela Meo\textsuperscript{a}, Maurizio M. Munafò\textsuperscript{a} \textsuperscript{a}Politecnico di Torino, Italy Abstract Retina is an open-source command-line tool that produces rich and complex statistics from real-time communication (RTC) traffic. Starting from raw packet captures, it creates summaries of observed streams with flexible statistics and tracks the evolution of the stream over time. Retina is modular and highly configurable, providing the ability to configure output statistics, temporal resolution as well as many other parameters. Furthermore, if the packet captures are accompanied by application logs, it can reconcile the data and enrich its output with application and QoE-related statistics. Retina helps troubleshoot RTC applications and enables the use of Machine Learning models for traffic classification and Quality of Experience assessment. We believe Retina can be extremely useful for researchers studying RTC traffic and network professionals interested in effective traffic analysis. Keywords: Network Traffic Monitoring, Real-Time Communications 1. Context and Motivation In recent years, the proliferation of broadband Internet access and mobile networks has spurred the adoption of Real-Time Communication (RTC) applications that allow people to communicate via voice and video. They are now essential for both leisure and business, helping people to reach friends and relatives and enabling remote working. The importance of RTC was particularly evident during the COVID-19 pandemic, when social distancing and lockdown measures adopted to curb the outbreak forced millions of people to communicate exclusively through RTC platforms. This led to a global increase of RTC traffic by more than 200\% \cite{1, 2}. It is therefore of utmost importance that researchers and practitioners are supported with tools to analyze RTC traffic and gain insights into the operation of RTC applications. In this paper we present Retina, an easy-to-use command-line tool that extracts advanced network statistics for RTC sessions found in packet captures. It also generates graphical output with various charts and visualizations of the statistics for easy analysis. Retina focuses on the Real-Time Protocol (RTP) \cite{3} protocol used in most RTC applications \cite{4}, with its encrypted version SRTP (which however leaves the packet headers in clear). Retina goes deeper than general tools in understanding RTC traffic. Starting from a capture, Retina searches for RTC traffic, identifies streams and outputs more than 130 statistics on packet characteristics, such as timing and size, and tracks the evolution of the stream over time bins of a chosen duration. It is highly configurable, and the user can customize the output statistics as well as a number of other parameters. Retina can enrich its output by merging the information available in the RTC application logs to provide the ground truth required for many classification problems. Retina is open-source and available to the research community and network practitioners\cite{1}. We believe it can be useful for traffic monitoring, and we have successfully used it for data processing and feature extraction to feed Machine Learning (ML) algorithms in the context of RTC-aware network management. 1.1. Literature Review Several tools already perform in-depth traffic analysis, and packet dissectors such as Wireshark\cite{2} (and its command-line version Tshark) are the first resources for network troubleshooting. Flow monitoring is also commonly used to analyze traffic summaries \cite{3}, and NetFlow \cite{4} is the de facto standard for collecting and processing flow records. Sophisticated network meters also expose application-level statistics using Deep-Packet Inspection on Layer-7 protocols. Tstat \cite{5}, for example, provides global statistics on RTP streams, while nProbe \cite{6} offers a VoIP plugin as a closed-source commercial product. In contrast to these works, Retina provides comprehensive statistics both per time unit and per flow. It specializes in RTC traffic and detects numerous RTC applications, including some that modify the RTP protocol. It also offers a wide range of parameters for personalized log creation. \textsuperscript{*}Corresponding author Email address: martino.trevisan@polito.it (Martino Trevisan) \begin{itemize} \item \url{https://github.com/GianlucaPoliTo/Retina} \item \url{https://www.wireshark.org/} \end{itemize} 2. System overview In this section, we describe Retina’s operation. As input, Retina takes one or more packet captures as well as optional configuration parameters. It processes the traffic and outputs the desired output in various forms. We depict its overall architecture in Figure 1. Retina is written in Python and depends on Tshark and a number of modules that can be installed via the package manager pip. We also provide a dockerized version to allow the use as a standalone container. 2.1. Inputs and Configuration Retina requires the user to specify one or more captures in PCAP format, the most common format used in many traffic capture softwares (Wireshark, TCPdump, etc.). Retina can also process an entire directory by searching for all captures in it. If it finds more than one, Retina uses multiprocessing to process multiple files at once. The number of processes is a configurable parameter. For some RTC applications, the user can provide application log files that Retina uses to calculate additional statistics and enrich the output. The application logs typically contain details about the media sessions, including the Source Identifiers of the RTP streams, the type of media (audio, video, or screen sharing), the video resolution, the number of frames per second, etc. When available, Retina uses this additional information to provide finer-grained per-second statistics – e.g., media type, video resolution or concealment events at the codec level. Currently, Retina supports log files of: (i) Cisco Webex, which logs second-by-second details for each RTP stream, and (ii) Google Chrome when collecting WebRTC debugging logs with WebRTC browser-based RTC services. In Retina, the user can customize a variety of parameters. All are optional, with carefully set default values. Retina has personalized features for many RTC applications, which can be enabled by specifying the name of the RTC application whose traffic is included in the capture as an input parameter. While it supports all applications that use RTP at their core, we have tested it extensively for Webex, Jitsi, Zoom, and Microsoft Teams. Retina accepts threshold parameters, such as the minimum number of packets or the minimum duration of a stream for it to be considered valid. The user can also control the statistics computed at each time bin (see Section 2.3) and can ask Retina to create (interactive) graphs. The full list of parameters can be found in the documentation, while in the rest of the paper we will only mention the most important ones. 2.2. System core We show the overall architecture of Retina in Figure 1 with the middle rectangle indicating the building blocks at its core. At the bottom, in blue, there are the basic functionalities, while, on the top, in purple, the optional modules. We also show a sample command line at the top of Table 1. The basic functionalities of Retina analyze the raw packets contained in the input PCAP captures and gather statistics, organized in tables per stream and per time-bin. For example, consider a PCAP capture collected at a user side, containing RTP traffic from a two-party call consisting of 4 RTP streams (outgoing and incoming audio and video). Setting a time bin duration of 1 s, Retina... Retina maintains a table where, for each of the 4 streams and for each second, it accumulates several statistics. Given a packet characteristic, such as packet size or interarrival time, Retina calculates several statistical indicators, such as mean, median, third and fourth moments, or percentiles. We report the list of packet features and available statistics in Figure 2, which summarizes the whole process of statistics extraction. The user can configure the duration of the time bin for this aggregation of packets, which is 1 s by default. The duration of the time bin directly affects the number of packets used to compute the statistics, and should therefore be varied judiciously. For example, in 1 s of audio, 50 packets are sent, while, in 1 s of HD video, more than 200. Clearly, if the time window is 200 ms for audio, no significant features can be computed, while this would be fine for video. To identify RTP streams in traffic, Retina relies internally on Tshark, the command-line version of Wireshark. This step is not straightforward, as RTP packets often appear in a UDP flow along with other protocols. In fact, many applications use STUN [9] to establish the media session and/or TURN [10] to relay the streams if no direct connection between peers is possible. In addition, it is common to use DTLS [11] interleaved among RTP packets to exchange control information such as encryption keys. Retina supports two methods for identifying RTP streams: (i) with a user-defined list of ports or (ii) by examining the STUN-initiated UDP flows. Retina attempts to decode the UDP payload as RTP and verifies that the protocol headers are compatible with RTP. We define an RTP stream using the combination of IP addresses and ports (the classic tuple) plus the RTP Synchronization Source Identifier (SSRC), which is used to multiplex multiple streams within a single UDP flow. For some RTC applications, we also use the RTP Payload Type (an RTP field that specifies the media codec). Retina maintains internal data structures to efficiently collect statistics for each RTP stream. Retina has a number of optional modules that target RTC applications, for which we have implemented special support. First, the traffic of some popular RTC applications (Zoom and Microsoft Teams) needs to be preprocessed to become standard RTP traffic. This is because they use the RTP protocol in a non-standard form. Microsoft Teams encapsulates RTP in a proprietary version of TURN called MTURN, while Zoom adds its own undocumented header. To make Retina work for these RTC applications, we have created specific modules that can also be used as standalone command line tools. They can be found in a separate folder in the code repository. Second, Retina can read and process the application log of (i) Webex and (ii) Google Chrome, as mentioned in Section 2.1. Retina can parse these logs and provide additional information about the RTP flows. If the application logs are available, we enrich the output logs from Retina with information such as the video resolution, employed codec, frames per second, jitter, codec concealment events, etc. We also provide a classification of media types into 7 classes, such as audio, FEC streams, 3 different qualities of video and screen sharing, for easier recognition. Note that the information in the application logs is particularly useful for training ML models, as it contains the necessary ground truth for many problems and Retina can match it with the network traffic. Lastly, Retina includes a plotting engine based on the Matplotlib and Plotly libraries\(^7\) to create both static and responsive graphs of all RTP streams. It draws the time-series of stream characteristics, such as bitrate or interarrival time, so that the user can easily get an overview of the traffic or debug an RTC application. It also draws several histograms for each stream to show the stream-wise distribution of packet characteristics (e.g. packet size). For an example graph, see Figure 3. Here we show the bitrate of 4 RTP streams present in a portion of a Webex call. The plotting engine also labels the time-series with their media type (audio, video, FEC etc.), if the information is provided (e.g. through an application log file). \(^7\)https://matplotlib.org/ https://plotly.com/ Command line: ``` ./Retina.py -d capture.pcap -so webex -log webex.log ``` <table> <thead> <tr> <th>Timestamp</th> <th>Packet size (mean)</th> <th>Packet size (std dev)</th> <th>Bitrate (kbit/s)</th> <th>Interarrival (max)</th> <th>Packets/s</th> <th>Frame width</th> <th>Frame height</th> <th>Frames/s</th> </tr> </thead> <tbody> <tr> <td>2021-06-08 14:32:11</td> <td>1041.84</td> <td>66.74</td> <td>1163.93</td> <td>0.043</td> <td>143</td> <td>600</td> <td>270</td> <td>30</td> </tr> <tr> <td>2021-06-08 14:32:12</td> <td>1080.72</td> <td>101.75</td> <td>1578.86</td> <td>0.045</td> <td>187</td> <td>640</td> <td>360</td> <td>30</td> </tr> <tr> <td>2021-06-08 14:32:13</td> <td>1023.49</td> <td>72.21</td> <td>1023.49</td> <td>0.045</td> <td>128</td> <td>640</td> <td>360</td> <td>30</td> </tr> <tr> <td>2021-06-08 14:32:14</td> <td>1076.39</td> <td>52.11</td> <td>1362.32</td> <td>0.044</td> <td>192</td> <td>640</td> <td>360</td> <td>30</td> </tr> <tr> <td>2021-06-08 14:32:15</td> <td>1055.50</td> <td>52.41</td> <td>1441.08</td> <td>0.044</td> <td>171</td> <td>640</td> <td>360</td> <td>30</td> </tr> <tr> <td>2021-06-08 14:32:16</td> <td>1074.62</td> <td>62.71</td> <td>1959.73</td> <td>0.089</td> <td>237</td> <td>640</td> <td>360</td> <td>30</td> </tr> <tr> <td>2021-06-08 14:32:17</td> <td>1056.22</td> <td>40.09</td> <td>2588.59</td> <td>0.033</td> <td>314</td> <td>640</td> <td>360</td> <td>30</td> </tr> <tr> <td>2021-06-08 14:32:18</td> <td>1057.73</td> <td>51.07</td> <td>1179.17</td> <td>0.040</td> <td>179</td> <td>640</td> <td>360</td> <td>30</td> </tr> </tbody> </table> Table 1: Example command line and Retina log for an RTC stream. The last three columns are derived from the application logs. ### 2.3. Outputs Retina produces a CSV file for each RTP stream found in the input capture, reporting the selected statistical features for each time bin. The logs contain different columns according to user preferences and additional stream information if the RTC application log is provided. We show an example output log in Table 1 along with the command line used to create it. Optionally, Retina creates a summary log file in which it reports stream-wise statistics. The file contains the most important information for each stream – i.e., the source and destination IP addresses and ports as well as general statistics such as the number of packets, duration, etc. Having per-stream information is useful for many applications that rely on the analysis of flow/stream records for e.g., traffic accounting. Additionally, Retina provides traffic plots, which we described in Section 2.2. Finally, Retina also provides a dashboard for analyzing RTC traffic through an interactive interface. The dashboard requires an input .pickle file, which can be produced by passing one or more packet captures to Retina and specifying an argument for the plot. Here the user can see interactive plots of stream statistics and compare streams of interest. ### 3. System design assets We have designed Retina following principles of scalability and modularity, so that it can be easily extended. It adopts a multiprocessing architecture, so when there are multiple PCAP files to process, it uses an independent process for each of them and stores separate output log files. These files can then be merged at the end of the processing. This also increases the robustness of the tool. Retina is highly modular, with separate functions organized into logical modules for all the different operations. This also allows for extensibility, as a user can write new functionalities with minimal effort. For example, it is easy to support the application log of a new RTC application (e.g., Microsoft Teams), as it is only necessary to add a parser function and call it with an argument. Retina can be used to analyze any kind of RTP traffic, and it is not limited to video conference applications. For example, we have successfully used Retina to gain insights into the operation of cloud gaming applications running over the browser [12]. Similarly, our parser for the Chrome WebRTC log works seamlessly for any type of browser-based application. Finally, Retina, as described in Section 2.2, is highly configurable. The user can limit the statistics to be computed (potentially speeding up the computation), the desired time aggregation, and several internal parameters - e.g., the minimum length of an RTP stream for it to be considered - which are detailed in the README file. ### 4. Publications enabled by the software Retina was first developed at the end of 2019, and within 2 years of its existence, it has already been a valuable asset for 4 scientific publications that target RTC traffic. Retina sits at the core of [13], where we used it to study cloud gaming, cloud gaming traffic, and it allowed us to understand the networking operation behind Google Stadia, GeForce NOW and PS Now in [12]. ### 5. Limitations and Future work While Retina supports most RTC applications, it still does not support those that do not use RTP (or a modified version of it), like GoToMeeting or Telegram. Moreover, it relies on the RTP headers, so if in a future protocol version these are encrypted, the tool will need major revisions. As future work we aim to make Retina work in real-time and be able to support traffic at high speeds (e.g., 40 Gb/s links). We also want to introduce better support... for gaming traffic, cover different cloud gaming platforms, and output more gaming-specific ML features. We also plan to support Retina in the long run and follow the future developments of the underlying protocols such as RTP, STUN, and TURN, as well as tackle new protocols from novel providers. 6. Conclusion This article presented Retina, a flexible command-line tool for extracting advanced statistics from network traffic of RTC applications. We provided a schematic description of all its features: the inputs, the system core and the outputs with examples. We also highlighted the design strengths of Retina, its modularity, scalability and configurability. We believe Retina can help both the scientific community in studying RTC applications and network administrators in troubleshooting RTC traffic. Our final goal is to make in-network devices regain visibility of RTC traffic and promote network management policies that favor this type of traffic. In particular, we designed it to be used directly for feature engineering of ML algorithms, since it can provide the ground truth for classification problems by processing the application log files. 7. Acknowledgements This work has been supported by the Smart-Data@Politecnico di Torino center for BigData and Data Science and Cisco Systems Inc. References
{"Source-Url": "https://iris.polito.it/retrieve/handle/11583/2944312/e384c434-0ffb-d4b2-e053-9f05fe0a1d67/ComNet_Retina%20%284%29.pdf", "len_cl100k_base": 4622, "olmocr-version": "0.1.49", "pdf-total-pages": 6, "total-fallback-pages": 0, "total-input-tokens": 18373, "total-output-tokens": 6109, "length": "2e12", "weborganizer": {"__label__adult": 0.0004432201385498047, "__label__art_design": 0.0003829002380371094, "__label__crime_law": 0.0005855560302734375, "__label__education_jobs": 0.0006656646728515625, "__label__entertainment": 0.0003371238708496094, "__label__fashion_beauty": 0.00019228458404541016, "__label__finance_business": 0.00039005279541015625, "__label__food_dining": 0.0003464221954345703, "__label__games": 0.0009632110595703124, "__label__hardware": 0.00499725341796875, "__label__health": 0.0006303787231445312, "__label__history": 0.0005087852478027344, "__label__home_hobbies": 9.816884994506836e-05, "__label__industrial": 0.0007300376892089844, "__label__literature": 0.00034546852111816406, "__label__politics": 0.00041604042053222656, "__label__religion": 0.0005655288696289062, "__label__science_tech": 0.322021484375, "__label__social_life": 0.0002290010452270508, "__label__software": 0.1527099609375, "__label__software_dev": 0.5107421875, "__label__sports_fitness": 0.0004334449768066406, "__label__transportation": 0.0008511543273925781, "__label__travel": 0.0002865791320800781}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 23024, 0.06025]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 23024, 0.33103]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 23024, 0.85464]], "google_gemma-3-12b-it_contains_pii": [[0, 997, false], [997, 5700, null], [5700, 8964, null], [8964, 13289, null], [13289, 18799, null], [18799, 23024, null]], "google_gemma-3-12b-it_is_public_document": [[0, 997, true], [997, 5700, null], [5700, 8964, null], [8964, 13289, null], [13289, 18799, null], [18799, 23024, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 23024, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 23024, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 23024, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 23024, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 23024, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 23024, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 23024, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 23024, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 23024, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 23024, null]], "pdf_page_numbers": [[0, 997, 1], [997, 5700, 2], [5700, 8964, 3], [8964, 13289, 4], [13289, 18799, 5], [18799, 23024, 6]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 23024, 0.10204]]}
olmocr_science_pdfs
2024-11-25
2024-11-25
3ed9dd7784a45689d79f22ba817cc7acced59d5a
Adding Publish/Subscribe to the Scripted Battle Management Language Web Service Douglas Corner, Dr. J. Mark Pullen, Samuel Singapogu, and Bhargava Bulusu C4I Center George Mason University Fairfax, VA 22030, USA +1 703 993 3682 {dcorner, mpullen, ssingapo, bbulusu}@c4i.gmu.edu Keywords: Battle Management Language, Web Services, JC3IEDM The approach to defining a coalition battle management language (BML) now being pursued by SISO requires mapping of BML into a JC3IEDM database, which is accessed via a Web service. In previous SIW papers we have reported on a new approach to implementing such a Web service, based on the notion of an interpreter module. This scripting engine takes as its input the schema of the Web service and a script, coded in XML, that defines the mappings concisely. The interpreter, which will be available as open source software, has the virtues that it is quicker and easier to change than a hard-coded service and also requires a lower level of expertise for development, once the interpreter has been completed. Implementing the BML server capability in a simple Web service results in a bottleneck at the server because the clients must poll the server for updates. This paper provides a detailed description of implementation and use of a publish/subscribe paradigm to improve performance in the Scripted BML Web Service. The implementation uses the JBoss environment and the Java Message Service (JMS). The paper ends with a description of the way this server was used by NATO MSG-048 in its November 2009 experimentation event and some enhancements we plan to implement as a result of that experience. 1. Overview This paper describes how and why the Scripted Battle Management Web Service (SBML) was extended to provide a publish/subscribe capability, and how the result was used in NATO MSG-048 experimentation 2009. 2. SBML Background Battle Management Language (BML) and its various proposed extensions are intended to facilitate interoperation among command and control (C2) and modeling and simulation (M&S) systems by providing a common, agreed-to format for the exchange of information such as orders and reports. This is accomplished by providing a repository service that the participating systems can use to post and retrieve messages expressed in BML. The service is implemented as middleware, essential to the operation of BML, and can be either centralized or distributed. Recent implementations have focused on use of the Extensible Markup Language (XML) along with Web service (WS) technology, a choice that is consistent with the Network Centric Operations strategy currently being adopted by the US Department of Defense and its coalition allies [1]. Experience to date in development of BML indicates that the language will continue to grow and change. This is likely to be true of both the BML itself and of the underlying database representation used to implement the BML WS. However, it also has become clear that some aspects of BML middleware are likely to remain the same for a considerable time, namely, the XML input structure and the need for the BML WS to store a representation of BML in a well-structured relational database, accessed via the Structured Query Language (SQL). This implies an opportunity for a re-usable system component: a Scripting Engine, driven by a BML Schema and a Mapping File, that accepts BML push and pull transactions and processes them according to a script (also written in XML). While the scripted approach may have lower performance when compared to hard-coded implementations, it has several advantages: • new BML constructs can be implemented and tested rapidly • changes to the data model that underlies that database can be implemented and tested rapidly • the ability to change the service rapidly reduces cost and facilitates prototyping • the scripting language provides a concise definition of BML-to-data model mappings that facilitates review and interchange needed for collaboration and standardization The heart of SBML is a scripting engine, introduced in [2], that implements a BML WS by converting BML data into a database representation and also retrieving from the database and generating BML as output. It could implement any XML-based BML and any SQL-realized underlying data model. Current SBML scripts implement the Joint Command, Control and Consultation Information Exchange Data Model (JC3IEDM). In the following description, any logically consistent and complete data model could replace JC3IEDM. Reference [3] describes the second generation of SBML. The current SBML implementation and scripts support two JC3IEDM database interfaces, as shown in Figure 1: one is a direct SQL interface, used with a MySQL database server. The other, SIMCI_RI [4], passes java objects through Red Hat’s Hibernate persistence service, which performs the actual database interface function. Version 2 implements a publish/subscribe capability, using the Java Message Service (JMS) as implemented by JBoss in open source (see http://www.jboss.com). Version 2 also implements the XML Path Language (XPATH) (see http://www.w3.org/TR/xpath), wherever a relative path in the XML input is required. ![Figure 1: SBML Configuration](image) The BML/JC3IEDM conversion process is accomplished under control of the scripting language which is described in [3]. ### 3. Polling Interface M&S systems generally process two kinds of messages, orders and reports. Orders are larger and more complex than reports, however, the frequency of reports is much higher. For example as a military unit moves from one position to another the M&S system may generate updated position reports every few seconds. With the previous release of the SBML service it was necessary for C2 systems to poll the server to determine if updated report information was available. This is inefficient in several ways: - The server must reread information that may have just been written to the database - The poll may retrieve no new information - The request for each client will be processed separately Client applications have no way to determine what messages might have been posted to the server since sending the last query; they must first determine what reports are available. Scripting was developed within the SBML framework to retrieve a list of reports posted over a specified period of time. It was then necessary for the client to format a query to retrieve those messages that might be of interest. The precision of this method turns out to be low in that many of the messages retrieved tend to be status reports that are then updated by later messages in the same group. An additional problem is that it is necessary for each client using the server to perform this process in parallel. The load resulting on the server from polling and the large amount of redundant network traffic clearly is inefficient. In this environment it was necessary for M&S systems to limit the rate of report production so that the server was not overloaded. ### 4. Publish/Subscribe Implementation A publish subscribe capability was added to the SBML server in order to eliminate the inefficiencies of the polling interface. SBML runs under JBoss 4.2.3 (http://jboss.org). The messaging service provided by this release of JBoss, JBoss Messaging or JBossMQ is an implementation Java JMS 1.1 [6]. JBossMQ provides both point to point messaging between two entities (JMS Queues) and a subscription based distribution mechanism (JMS Topics) for publishing messages to multiple subscribers. JMS provides reliable delivery of messages for all subscribers to a particular topic. SBML 2.3 provides a set of preconfigured JBossMQ Topics, which are used for the distribution of incoming orders and periodic reports to any interested subscribers. As BML messages are received they are processed by the appropriate script and written to the database. The successful completion of the transaction is an indication that there were no errors in incoming data and that the message can be forwarded to subscribers. There is an XPath [7] statement (see http://www.w3.org/TR/xpath) associated with each Topic which determines if a particular message should be written to that Topic. If application of the XPath statement to the message results in non-null result the message is written to that Topic. Note that a particular BML message may match more than one XPath statement and therefore could be transmitted to more than one Topic. A client then might receive the same message more than once. The publish/subscribe architecture is depicted in Figure 2 below. JMS is built for the Java environment and uses Java Remote Procedure Call (RPC). This presents an additional requirement for programs written in C++ (and other languages) clients. We provide an interface for C++ users, built under the Java Native Interface (JNI) framework. This interface works well, however it does separate the actual client code from a direct interface with the messaging service. 5. SBML in NATO MSG-048 The NATO Modeling and Simulation Group Technical Activity 48 (MSG-048) was chartered in 2006 to investigate the potential of a Coalition Battle Management Language for multinational and NATO interoperation of command and control systems with modeling and simulation. The 2009 experimentation phase of MSG-048, described in [5], was performed at George Mason University’s Manassas, Virginia Campus in November 2009 and included six C2 System and five M&S systems from eight NATO nations, as shown in Figure 3. This was the first large scale use of the SBML Publish/Subscribe service. The service performed well and enabled a much larger set of systems to interact as well as increasing the precision of reports by permitting a higher status update rate. BML messages were batched, to reduce the impact of Web service overhead. The processing time supported by our server for MSG-048 experiments was 50 ms per transaction. As shown in Figure 2, the publish/subscribe we implemented requires a client module to open a connection to the server, which is used to transmit Web service transactions matching the subscription. The C2 systems and simulations used by MSG-048 in 2009 were implemented in Java and C++ languages. In order to support publish/subscribe under the latter, we provided an interface module made on the Java Native Interface (JNI). 6. Publish/Subscribe Enhancements Topics. The current implementation, SBML 2.3, the Publish Subscribe service has the topics hard coded along with corresponding XPath statements used for matching messages with JMS Topics. While acceptable in a prototyping environment, environment this necessitates the rebuilding of the service as requirements change. We therefore plan that, at a minimum, in the next version of SBML the Topics will be configurable through an external file. A more sophisticated enhancement would be a dynamic topic capability such that clients could create a topic in an XML message by specifying the topic name and specifying an XPath statement, used to match against incoming messages. The topic would then be active until the next time the application server was restarted. Some planning is necessary to prevent name collisions and might be beneficial to provide for the publication of new topics are they are created to allow sharing between clients. Client Language. Release 5 of JBoss is in common use and, among other things, provides for a choice of protocols to be used with the messaging subsystem. This provides for a more direct interface for C++ clients. 7. Scripting Enhancements In the process of developing the scripts described above, we learned some lessons about how to make scripting more practical. 7.1 Nested if-then-else construct The logic required in scripts turns out to entail some decisions that are not easy to encode with the single level of if-then-else described in [3]. Therefore, we are adding a nested if to the XML scripting. Our nested ifs mimic the use of “curly braces” {} in programming languages such as Java. Thus a BO could contain: ```xml <BusinessObjectTransaction> <transactionName>transName</transactionName> [Other BOT header elements] <Block> <SBML elements> </Block> </BusinessObjectTransaction> ``` If statements within the top level <Block> appear as: ```xml <ifThenElse> <compare>someWV</compare> <relation>EQ</relation> <literalValue>xxx</literalValue> </ifThenElse> ``` ```xml <Block> <SBML elements executed if condition was true> </Block> <Block> <SBML elements executed if condition was false> </Block> ``` The condensed scripting language offers three ways to retrieve from the database depending upon whether to retrieve a row or a list of elements from a column or just one column entry: GetRow, GetList and Get. In all three commands, the first identifier is the table name, the second is the column name and the third is a set of columnReferences that constitute the where clause of the underlying SQL statement. A Put operation is defined as a combination of the table name and a set of columnReferences that define the columns that need to be updated. To invoke the BusinessObject (BO), a Call statement can be used to call another BusinessObjectTransaction by specifying the name of the BO, the anchorTag, and lists of parameters and optional return values. Conditional statements are defined as either an IfThen or an IfThenElse. Both statements make a logical comparison of the identifier with the variable and conditionally execute the statements. The Assign command can be used to assign a variable to an identifier. There can be multiple BOReturn statements inside a BO and each BOReturn can have an unbounded number of the following statements: HigherTagStart, HigherTagEnd, Tag. HigherTagStart creates a opening tag corresponding to the variable name that is specified and HigherTagEnd creates a closing tag. The Tag statement can be used to create a tag with the name specified after the first whitespace and the value specified after the second whitespace. This scheme allows for the creation of nested tags and also tags dynamically named using variables. 7.2 Condensed Scripting Language The XML-based script used by SBML2.3, while simple to implement in the Web service environment, is less than optimal for the human programmer since it suffers from the well-known verbosity of XML. We are investigating use of a front-end translator that can reduce the visual and cognitive burden on the script developer by reducing the script to a condensed representation. This is intended to be no more nor less powerful than the XML form, since it will translate directly into the XML form. It is intended to be more usable in that it is easier to write and to comprehend the working of a condensed BML script. We are developing a compiler that will accept the condensed BML scripting language as input and produce an XML script as output. Appendix 1 provides a Backus-Naur Form (BNF) representation of the condensed scripting language. The whole script is treated as a BusinessObjectInput that can contain multiple instances of BusinessObjectTransaction. Each BusinessObjectTransaction is a set of database operations which are intended to leave the Database in a consistent state at the end of the transaction if executed without interleaving of other BusinessObjectTransactions that operate on the same database tables. Each BusinessObject is identified by a unique identifier and may optionally include a definition of a multivalue workingVariable and the variable name that it should be assigned to at every iteration of the BusinessObjectTransaction. The definition is then followed by a declaration of the parameters and the Return values. The parameters are declared as an ordered list of variables where a variable is either a string literal enclosed in quotation marks or a String literal which maps to a workingVariable in the XML script. Every businessObjectTag is treated as workingVariable by the SBML engine. The BusinessObjectTransaction thus can contain any number of elements. Figure 4 illustrates this concept with a condensed-language script. Appendix 2 contains the XML version of the same script, which is more than four times as long. BOInput { BOTransaction WhatWhenPush(... //fragment from WhatWhenPush Call TaskeeWhoPush TaskeeWho (task_act_id) () ; ... } BOTransaction TaskeeWhoPush (task_act_id) () { GET unit unit_id (formal_abbrd_name_txt EQ UnitID); PUT act_res (task_act_id, act_res_index EQ act_res_index, cat_code EQ "RI", authorising_org_id EQ unit_id); PUT act_res_item (act_id EQ task_act_id, act_res_index EQ act_res_index, obj_item_id EQ unit_id); BOReturn { BOReturnElement { Tag Result "OK"; } } } Figure 4. Condensed script for SBML 8. Conclusions The SBML publish/subscribe capability worked well in a demanding environment that included a large variety of clients and development environments. Future enhancements of SBML should increase usability and performance. SBML will be available as open source. References Author Biographies DR. J. MARK PULLEN is Professor of Computer Science at George Mason University, where he serves as Director of the C4I Center and also heads the Center’s Networking and Simulation Laboratory. He has served as Principal Investigator of the XBML and JBML projects. DOUGLAS CORNER is a member of the staff of the George Mason University C4I Center. He is the lead software developer on the SBML scripting engine. SAMUEL SINGAPOGU is a member of the staff of the George Mason University C4I Center. He is the lead script developer on the SBML scripting engine. BHARGAVA BULUSU is a member of the staff of the George Mason University C4I Center. He is a script developer on the SBML scripting engine. Appendix 1: BNF Representation of Condensed Scripting Language <BOInput> ::= BOInput { <BOTransaction> [BOInput] } } <BOTransaction> ::= BOTransaction <identifier> [mvw=<identifier>,assignTo=<identifier>][iterator=<identifier>] {<parameterList>}{<parameterList}>{<BOTransactionElements>} <BOTransactionElements> ::= <BOTransactionElements><BOTransactionElement><BOReturnElements> ; <BOTransactionElement> ::= <getRow> | <getList> | <getColumn> | <put> | <call> | <conditional> | <assign> | <singleStatement> | <abort> | <BoReturn> | <comment> | Debug; | Commit; <columnReference> ::= <identifier> <relation> <variable> [,<columnReference>] <parameterList> ::= <variable> [, <parameterList>] | <literalValue> ::= "<identifier>" <relation> ::= EQ|NE|GT|LT|GE|LE|EQI <variable> ::= <literalValue>|<identifier> <getRow> ::= GetRow <identifier> <identifier> (<columnReference>) ; <getList> ::= GetList <identifier> <identifier> (<columnReference>) ; <getColumn> ::= Get <identifier> <identifier> (<columnReference>) ; <put> ::= Put <identifier> (<columnReference>) ; <call> ::= Call <identifier> <identifier> (<parameterList>) ([parameterList]) ; <conditional> ::= <ifThen> | <ifThenElse> <ifThen> ::= IfThen (<identifier><relation><variable>) { <BOTransactionElements> } <ifThenElse> ::= IfThenElse (<identifier><relation><variable>) { <BOTransactionElements> } <assign> ::= Assign <identifier> <variable> <abort> ::= Abort <literalValue> ; <BOReturn> ::= BOReturn { <multipleBOReturnElements> <multipleBOReturnElements> ::= <multipleBOReturnElements><BOReturnElement> <BOReturnElement> ::= BOReturnElement HigherTagStart <variable> ; | BOReturnElement HigherTagEnd <variable> ; | BOReturnElementTag <literalValue> <identifier> ; | ; IDENTIFIER ::= <lowerCaseAndOtherCharacters> [IDENTIFIER] | <upperCaseCharacter>[IDENTIFIER] <lowerCaseAndOtherCharacters> ::= a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z <upperCaseCharacter> ::= A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z <comment> ::= // "... text ... NOTE: Whitespace (any number of blanks and carriage returns) is the delimiter, unless other delimiter is indicated. Appendix 2: XML Script Example <?xml version="1.0" encoding="UTF-8"?> <BusinessObjectInput xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="BusinessObjectTransactionInterpreterSchema.v0.18.xsd"> <!-- Fragment of code from WhatWhenPush --> <call> <boName>TaskeeWhoPush</boName> <anchorTag>TaskeeWho</anchorTag> <parameter> <workingVariable>task_act_id</workingVariable> </parameter> </call> ...</BusinessObjectInput>
{"Source-Url": "http://c4i.gmu.edu/pdfs/BML_Arch/10S-SIW-046.pdf", "len_cl100k_base": 4452, "olmocr-version": "0.1.51", "pdf-total-pages": 7, "total-fallback-pages": 0, "total-input-tokens": 21438, "total-output-tokens": 5230, "length": "2e12", "weborganizer": {"__label__adult": 0.0003566741943359375, "__label__art_design": 0.00023066997528076172, "__label__crime_law": 0.0008640289306640625, "__label__education_jobs": 0.0007886886596679688, "__label__entertainment": 8.738040924072266e-05, "__label__fashion_beauty": 0.00014102458953857422, "__label__finance_business": 0.00033783912658691406, "__label__food_dining": 0.0003216266632080078, "__label__games": 0.0010051727294921875, "__label__hardware": 0.0012035369873046875, "__label__health": 0.00038242340087890625, "__label__history": 0.0003559589385986328, "__label__home_hobbies": 7.623434066772461e-05, "__label__industrial": 0.0008220672607421875, "__label__literature": 0.0001888275146484375, "__label__politics": 0.0005888938903808594, "__label__religion": 0.0002753734588623047, "__label__science_tech": 0.07391357421875, "__label__social_life": 0.00010436773300170898, "__label__software": 0.0159454345703125, "__label__software_dev": 0.900390625, "__label__sports_fitness": 0.0004165172576904297, "__label__transportation": 0.0010709762573242188, "__label__travel": 0.00020313262939453125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 21638, 0.01597]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 21638, 0.41411]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 21638, 0.86386]], "google_gemma-3-12b-it_contains_pii": [[0, 4024, false], [4024, 8628, null], [8628, 11748, null], [11748, 16124, null], [16124, 19012, null], [19012, 21157, null], [21157, 21638, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4024, true], [4024, 8628, null], [8628, 11748, null], [11748, 16124, null], [16124, 19012, null], [19012, 21157, null], [21157, 21638, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 21638, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 21638, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 21638, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 21638, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 21638, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 21638, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 21638, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 21638, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 21638, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 21638, null]], "pdf_page_numbers": [[0, 4024, 1], [4024, 8628, 2], [8628, 11748, 3], [11748, 16124, 4], [16124, 19012, 5], [19012, 21157, 6], [21157, 21638, 7]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 21638, 0.0]]}
olmocr_science_pdfs
2024-12-04
2024-12-04
0536952de5ea64ace129596806698443d677e710
As the relationship between research and computing evolves, new tools are required to not only treat numerical problems, but also to solve various problems that involve large datasets in different formats, new algorithms, and computational systems such as databases and Internet servers. Python can help develop these computational research tools by providing a balance of clarity and flexibility without sacrificing performance. Scientific Computing’s Changing Landscape For a long time, scientific computing was focused almost exclusively on raw performance for floating-point numerical tasks. It’s no accident that Fortran is an abbreviation of *formula translator*: for a long time, computing numerical formulas was a computer’s main purpose. Today, however, scientific computing’s algorithmic needs go far beyond floating-point numerics. Despite the lasting importance and usefulness of array-oriented libraries such as Lapack (and its many descendants), modern scientific codes routinely tackle problems that go beyond number crunching with arrays. Problems such as graph traversal, finite state machines, or branch and bound algorithms are now a staple of many scientific codes. They require data structures beyond simple arrays and use code full of logic and integer manipulations that is quite different from what tools like Lapack are good at. In addition, even today’s numerical work has needs beyond hardware floating point, as many current problems of interest require integrated access to arbitrary precision integers, rationals, and floating-point numbers, often in combination with symbolic manipulation. The Python tool stack doesn’t attempt to replace the many critical codes and algorithms with versions written in Python. Rather, the approach is to expose those codes through Python wrappers while providing rich data structures and programming paradigms to tackle problems not easily managed with high-performance computing’s traditional data structures. Although Python isn’t unique in possessing rich data structures (C++ has them as well), it’s particularly good at... interoperating with multiple languages’ structures and with a syntax accessible to scientists who aren’t programmers. Computing’s role in science and engineering has also exploded beyond strictly algorithmic needs. A range of factors has driven this transformation including the Internet, ever-improving hardware, online collaboration tools, the rise of “data driven” science, and open source software development models. As an integral part of their research efforts, scientists today develop computational tools to tackle tasks as varied as - accessing data and results over a network, often with custom protocols; - exposing codes and data via Web applications; - interacting with databases; - integrating components written in multiple programming languages, and integrating tools and libraries from multiple scientific disciplines; - providing graphical user interfaces (GUIs) to scientific codes; - working with data in a wide range of formats, including binary, XML, JavaScript Object Notation (JSON), and Hierarchical Data Format (HDF5); - controlling and interfacing with a range of hardware devices; - parallelizing programs to run on GPUs, clusters, multicore CPUs, and supercomputers; and - collaborating with large, geographically distributed teams of scientists, programmers, and engineers on computationally based research, software, and data. Originally, computational resources (cycles, memory, and storage) were scarce, and human development time was comparatively cheap. Over time, this balance inevitably shifted; ease of use and development have become increasingly important considerations, as evidenced by the rise in popularity of high-level computing environments. First, the 1980s brought the rise of systems—such as Matlab and IDL (the Interactive Data Language)—that effectively encapsulated Fortran libraries behind a friendly user interface with access to rich functionality, interactive exploration, and immediate data visualization. Later, systems with symbolic capabilities and arbitrary precision numerical support, such as Mathematica and Maple, became extremely popular. Such systems made entirely new kinds of computations possible that couldn’t be tackled with a reasonable programming effort in plain Fortran or C. All such systems provide interactive exploratory environments that make language features and libraries immediately available to scientists who can use them to explore a problem domain. This contrasts with the classical edit/compile/run cycle of C or Fortran programming, which typically requires separate computation and post-processing/visualization steps. An interactive environment offers much more flexibility in using the computer as an exploration tool; the code evolves as scientists better understand a problem by performing small, incremental computations that lead to a complete program. The challenges of modern scientific computing that we have discussed are hard to address purely with languages such as Fortran and C/C++. Indeed, they require computational expertise different from the scientist’s typical training in writing fast for loops, and some problems aren’t merely technical but have social aspects as well, such as developing tools collaboratively over the Internet. Although the high-level environments we’ve mentioned have proven extremely useful, the carefully conceived Python programming language combined with a flexible stack of components provides a comprehensive ecosystem in which even better solutions can be constructed. Building free and open source codes for scientific problems is also consistent with the research goals of transparency and reproducibility. **Python: A General Purpose Programming Language** Most tools that we’ve mentioned so far, from Fortran to Mathematica, have one thing in common: they were designed primarily with mathematical and technical computing in mind. Fortran has arrays and mathematical functions defined as first-class entities in the language; Matlab has native syntax to express common linear algebra operations; and Mathematica symbols are all valid entities without declarations, so expressions can involve arbitrary symbol sets. This design focus offers important benefits: many everyday mathematical tasks can be performed with a compact and familiar syntax; the tool’s abstractions can map well to many scientific domains; and there’s often considerable out-of-the-box functionality for doing nontrivial scientific computing. Writing sophisticated user interface applications that integrate numerics with visualization—while talking to databases and handling custom user input—is possible but difficult in some custom scientific languages (such Background and Overview In contrast, Python was designed as a general-purpose language. Python’s creator, Guido van Rossum, has written a detailed series of articles on the language’s history (see http://python-history.blogspot.com). Python was born in the early 1990s as a general-purpose “glue” language at the CWI (the Centrum voor Wiskunde and Informatica), the birthplace of ALGOL 68 (Algorithmic Language 68). Prior to this, van Rossum had worked on the ABC programming language, developed at the CWI as a teaching language that emphasized clarity. Although the ABC project was ultimately shut down, van Rossum took many lessons from it when he started to write Python as a tool for use in multimedia and operating systems research projects. He wanted Python to be high-level enough to be easy to read and write, while also—in sharp contrast to Java and key to our purposes—offering direct access to low-level capabilities, as well as offering easy portability and a well-defined error model based on exceptions. Python is a dynamically typed language with a rich set of native types. Its number hierarchy includes native arbitrary-length integers, hardware-precision floating-point and complex numbers, and library support for rational numbers and arbitrary precision floating point. It also has powerful strings, variable-size lists, sets, and very flexible associative arrays called dictionaries in Python. These types give Python a rich vocabulary in which to express many complex algorithmic questions with clarity and efficiency. We can illustrate this expressive power with a fully functional implementation of the classic QuickSort. QuickSort is one of the simplest sorting algorithms to achieve $O(n \log n)$ complexity with a divide-and-conquer approach. Although tedious to implement in C or Fortran; in Python, these six lines suffice. ```python def qsort(L): if not L: return L # exit recursion if input is empty pivot, rest = L[0], L[1:] less_than = [x for x in rest if x < pivot] greater_eq = [x for x in rest if x >= pivot] return qsort(less_than) + [pivot] + qsort(greater_eq) ``` Figure 1. Implementing the basic QuickSort algorithm in Python. QuickSort is one of the simplest sorting algorithms to achieve $O(n \log n)$ complexity with a divide-and-conquer approach. Although tedious to implement in C or Fortran; in Python, these six lines suffice. as Matlab) and practically impossible in others (such as R). shows, it can be implemented in Python in six lines. It’s interesting to note how similar this code example is to the pseudo-code that expresses the algorithm on Wikipedia; such clarity and simplicity of expression have caused some to refer to Python code as “executable pseudo-code.” Furthermore, Python is an object-oriented language that lets users redefine the meaning of most operators for their own types; the expression $a + b**2$ can thus call user-defined routines for addition and exponentiation on $a$ and $b$. The language maps most syntax operators to specially named methods; for example, to implement exponentiation for a type, you write a method, \_\_pow\_, which is then called whenever the ** operator is encountered. That Python is object oriented at its core helps users build complex codes that closely track the physical or mathematical entities they model; however, Python doesn’t force this programming paradigm on users who prefer more familiar procedural approaches. Python combines high-level flexibility, readability, and a well-defined interface with low-level capabilities, including an official C interface that lets you extend the language with C code and link to third-party libraries in C, C++, and Fortran. This generality is advantageous for modern scientific computing: it’s a productive everyday environment that also lets you optimize performance-critical bottlenecks. Further, it provides the flexibility to build tools with a precise balance of low- and high-level features so you can appropriately choose between performance and ease of development or use. This combination of semantic richness and flexibility makes Python well suited to solving many of the non-algorithmic computational issues we mentioned above, such as integrating with the Web, data formats, or low-level hardware. Python libraries—whether included in the language or from external projects—let you interface with Web servers, databases, and scientific storage formats such as HDF5 to process text and send data over raw network sockets, and so on. Such tasks often require a mix of fairly low-level machinery and high-level abstractions, such as the combination of managing binary data over raw sockets with objects to represent Web servers or open database connections. **Numerics and Data** Given its rich native types and a flexible object model, Python lets users not only easily express many complex, high-level tasks concisely, but also offers a good platform for developing more specialized objects that are directly suited to scientific work. The NumPy library—which Stéfan van der Walt and his colleagues describe in “The NumPy Array: A Structure for Efficient Numerical Computation” on page 22—provides a remarkably sophisticated multidimensional array object that can be accessed by low-level Fortran or C code for speed and provides a much richer Python-level interface. Here, we begin to see the benefit of layering scientific tools on top of Python’s general foundations: today’s NumPy arrays have evolved from fairly closely mimicking $n$-dimensional Fortran arrays to being objects with rich semantics that make them suitable for database-like processing of complex datasets. As a simple example, we’ll do a brief analysis with real financial data freely available on the Internet. As Figure 2 shows, working in the IPython interactive environment, we load the `urllib` module for manipulating URLs from Python’s standard library as well as the `matplotlib` package for data analysis and visualization. These components let us download stock trading data for IBM from the Internet using the Yahoo! historical financial data service, which provides files in comma-separated values (CSV) format typically read with spreadsheet software. ```python In [1]: import urllib, matplotlib.mlab In [2]: symbol = 'IBM' In [3]: stock_url = ('http://ichart.finance.yahoo.com/table.csv?s=%s' + ' &d=3&e=28&f=2010&g=d&a=0&b=2&c=1962&ignore=.csv') % symbol In [4]: filename, headers = urllib.urlretrieve(stock_url) ``` Next, we convert the CSV file to a database-like NumPy array using `matplotlib`’s `csv2rec()` function and then answer a few simple questions about the IBM stock. The `stock` variable is a NumPy array, but rather than being a simple 2D array of numbers, NumPy arrays can support named fields that correspond to the different CSV file columns. The array contains fields such as date, closing price, and trading volume, each with its own data type. The `stock` variable is thus functionally equivalent to an array of C structs, but much easier to work with. We can then compute the daily trading volume in dollars as the product of the volume (in number of shares) and the closing price (in dollars), and find both the peak trading volume and the day on which it occurred (see Figure 3). We can now find which days were above 90 percent of the maximum dollar volume. With these days, we can compute a Boolean mask to use as an indexing object to extract values from the daily volume array and the original stock price array’s date field (See Figure 4). Finally, we produce the plot in Figure 5 using just a few lines of code (omitted here for conciseness) and the `matplotlib` library. These simple operations show Python’s flexibility and ease of exploration; using them, we can combine Python’s own general-purpose modules (such as `urllib`), with libraries written for and by scientists, such as NumPy and `matplotlib`. And, while this example focuses on numerical operations with NumPy arrays, arbitrary precision numerics and symbolic tools also exist. Finally, because Python is an open source language, the extension path can be taken to an ultimate conclusion by going beyond Python itself. Where NumPy has added powerful arrays that can contain all numerical types supported by modern compilers, the Sage system (www.sagemath.org) Sage modifies the Python syntax to accept constructs that go beyond those valid in Python and redefines all of the language’s basic numerical types. The resulting integers are based on new C-level multiprecision integers whose division produces rational numbers, and all floating-point operations are done using extended precision types. In [5]: stock = matplotlib.mlab.csv2rec(filename) In [6]: daily_vol = stock.volume*stock.close In [7]: peak_vol = int(daily_vol.max()/1e6) # in Millions of dollars In [8]: peak_date = stock.date[daily_vol.argmax()] In [9]: print 'Peak volume $%s Million, on %s' % (peak_vol, peak_date) Peak volume: $7771 Million, on 1997-01-22 In [10]: mask = daily_vol > 0.9+daily_vol.max() In [11]: print 'Dates greater than 90% max volume', stock.date[mask] Dates greater than 90% max volume [1999-04-22 1997-01-22] In [12]: print 'Volume for these dates: $', daily_vol[mask]/1e6, 'Million' Volume for these dates: $ [7618.5261 7771.1984] Million Figure 3. Computing the daily trading volume in dollars as the product of the volume (in number of shares) and the closing price (in dollars) lets us find both the peak trading volume and the day on which it occurred. Figure 4. Using a Boolean mask to find the days with the largest trading volumes and then printing the dates and volumes for those days. Figure 5. A matplotlib-based display of IBM stock prices, starting in 1990. Dates in red are the upper 10 percent of the trading volume, which we found using the example code. instead of hardware floating point. This lets Sage design a language whose numerical behavior follows a strict mathematical model, while being largely compatible with Python itself. Sage’s Web-browser-based notebook interface also provides a good example of how to write custom interfaces to the Python interpreter. This level of flexibility is hard to achieve in languages such as Fortran/C/C++ or environments such as Matlab or Mathematica. Fortran arrays are fast, but nowhere as flexible or semantically rich as NumPy’s, and doing symbolic computing in C++ is tedious at best. Building efficient low-level machinery for proprietary systems is often a difficult task that requires custom build systems, producing a result that might not be portable or easy to maintain as vendor tool and interface versions change beyond the scientist’s control. Although Python also has portability issues—such as between multiple versions of Python or multiple versions of the Numpy application binary interface—the fact that Python is free and open source helps ease such transitions. For example, researchers can run multiple versions of Python at the same time to support old production codes, which can be prohibitively expensive under a proprietary licensing model. Researchers can also contribute to porting codes forward or backward, which is largely done on the Internet in an open, collaborative fashion. Although this might entail significant work, the key point is that the users—who can always access the entire tool stack—retain control. We’ve found clear benefits in having Python designed and maintained by an external community as a general-purpose language using the process of Python enhancement proposals (www.python.org/dev/peps/pep-0001). Not having what appears to be a fundamental type like the array rigidly defined in the language has actually allowed the scientific community to evolve its own array library over the years, fine-tuning it to become increasingly sophisticated. The scientific community maintains a dialog with the language designers, and the core Python team has been highly receptive to scientists’ needs, letting the language develop specifically requested features for NumPy and its predecessors while also balancing the competing demands of other Python user communities. This dialog and the vetting of a solid language design group ensures that the language remains balanced and consistent for all constituencies, even if it means that scientists occasionally don’t get a requested feature. ### Languages, Environments, and Distributions Until now, we’ve looked at Python mostly as a programming language. In practice, however, scientists use rich environments with lots of functionality, and integrating multiple tools is an attractive aspect of commercial technical computing systems. #### Tools As we now summarize, in the Python world, scientists have collaboratively developed an open ecosystem of foundational tools that provide the key functionality needed for everyday computing work. **Interactive, exploratory work.** IPython\(^1\) offers an end-user environment for interactive work, a component to embed in other systems to provide an interactive control interface, and an abstraction of these ideas over the network for interactive distributed and parallel computing. Customized versions of IPython are used in multiple systems—including Sage, which also provides a Web-based graphical notebook interface that lets users combine code, text, and graphics in a single environment. **Numerical arrays.** All Python numerical codes today are based on the NumPy library, and the NumPy array is the basic data structure that virtually all libraries understand as a common data interchange object. NumPy arrays have a rich Python interface, but they also can be readily accessed from C, C++, and Fortran, making it easy to optimize performance bottlenecks or reuse existing libraries that have no knowledge of Python. **Data visualization.** matplotlib is the most widely used library for high-quality plotting, with support for a wide array of 2D and 3D plot types, precise layout control, a built-in LaTeX typesetting engine for label equations, and publication-quality output in all major image formats.\(^4\) The Chaco library is often used for building graphical interactive interfaces that tightly couple 2D data visualization to user controls. For high-end data visualization in three dimensions, Mayavi\(^6\) provides both a rich GUI to the powerful Visualization ToolKit (VTK) libraries and an easy to use Python library. As Prabhu Ramachandran and Gaël Varoquaux describe in “Mayavi: 3D Visualization of Scientific Data” on page 40, Mayavi wraps much of VTK’s complexity in high-level objects that are easy to use for common tasks and directly support NumPy arrays. Finally, the VisIt (https://wci.llnl.gov/codes/visit) and ParaView (www.paraview.org) projects provide comprehensive visualization systems with parallel rendering support and rich feature sets that users can control and extend in Python. **Algorithms.** The SciPy package (www.scipy.org) provides a powerful collection of tools, both by wrapping existing libraries such as Lapack, FFTPack (a Fortran subroutine library of fast Fourier transforms), and the Arnoldi Package (ARPack), and with new code written for SciPy itself. SciPy has support for dense and sparse linear algebra, signal processing, optimization, numerical integration and ordinary differential equations, special functions, statistics, data fitting, and much more. The Scikits (http://scikits.appspot.com/scikits) project offers add-on packages for SciPy, developed by teams focused on a specific application domain; today there are Scikits for audio and image processing, time series analysis, statistical model description, environmental time series manipulation, machine learning, speech processing, and more. Also, many more projects are available on the Internet that provide specialized tools, including notable contributions from various US national laboratories such as Python bindings to the Portable, Extensible Toolkit for Scientific Computation (PETSc) and Trilinos solvers, and the Networkx graph theory package. **Performance.** Fortran codes (such as those included in SciPy) have been traditionally accessed via f2py, a tool that generates Python wrappers for Fortran libraries included with NumPy. As Stefan Behnel and his colleagues describe in “Cython: The Best of Both Worlds,” on page 31, the Cython project (www.cython.org) can be described as an extension to the Python language with type annotations. Cython source code is processed by the Cython compiler; this produces pure C code that can then be compiled into a Python extension module (.so, .dylib, or .dll dynamically linked library). Cython supports NumPy arrays and is an extremely powerful way to easily optimize existing Python code, as well as to link to C and C++ libraries (Sage uses Cython extensively in both ways). Recently, Cython has also added Fortran support. The Simplified Wrapper Interface Generator (SWIG) system can automatically wrap large C and C++ libraries after you manually write an initial set of interface descriptions. The ctypes module (included with Python itself) can call any dynamic library at runtime, making it possible to interface even with libraries that have no available source code; we know of many scientists who use this module to interface with hardware devices for which manufacturers only provide a Windows DLL and no source code. **Symbolic manipulation.** Python doesn’t have a native notion of symbols like languages such as Mathematica, but the Sympy package (www.syrmpy.org) offers basic symbolic objects and a growing collection of symbolic manipulation tools, from simple algebra to Gröbner bases. **Documentation.** Properly documenting scientific codes is a critical issue that is often (and unfortunately) given insufficient attention. In Python, the powerful Sphinx system (sphinx.pocoo.org) makes it easy to create well-formatted documentation in HTML and PDF formats, including mathematical markup with LaTeX support, figures, and code examples that can be executed for validation as part of the build process. The Python language itself is documented using Sphinx, and by now virtually all scientific projects have standardized on it as well; we therefore now have a set of uniform tools and extensions for producing documentation that we all benefit from. Although the responsibility of actually writing the documentation still falls on the code’s authors, an efficient and flexible toolchain makes the process much easier. Indeed, we’ve already seen that this leads to projects having more and better quality documents. The SciPy community has developed a Web-based system that allows anyone to easily contribute to NumPy and SciPy documentation. User contributions are peer-reviewed and improved until they meet the required quality standard for project incorporation. This system has greatly improved documentation quality and solved the common conundrum of having only the developers write documentation. It also offers a great way for newcomers to make contributions before they feel comfortable modifying the code. Because the Sphinx documentation system is written in Python itself, the scientific Python community has written several extensions. For example, users can embed source code including IPython constructs, NumPy, SciPy, and matplotlib directly into the document source; this ensures that example code, output, and figure generation are run at documentation build time. **Distributions** One of the main attractions of systems like Matlab and Mathematica is that—in addition to a programming language and libraries—they provide a complete working environment, or distribution, in a single download. Earlier, we described individual components for many tasks, but thanks to the hard work of numerous individuals, groups, and companies, there are now many distributions that provide this for the Python ecosystem, each with a different focus. This is akin to how many Linux distributions work, where the various packagers (such as RedHat, Debian, and Ubuntu) integrate the vast collection of open source software into a coherent environment that users can install and update. Each of the collections described below includes a different set of tools, but all ship the basic ones we listed earlier: - **Enthought Python Distribution (EPD)** is a large collection of packages available natively for OS X, various Unix systems, and Windows. The included software is all open source, but the bundled packaging, installer, and support are commercially licensed (similar to how RedHat Enterprise Linux works, for example). The 32-bit version is available for free download to academic users. - **PythonXY** is a collection for Windows that emphasizes support for the Qt libraries for GUI development. PythonXY is distributed under the terms of the GNU General Public License version 3. - **PyIMSL Studio** offers the basic set of tools along with the well-known IMSL (International Mathematics and Statistics Library) numerical libraries and their Python bindings, distributed under a commercial license from Visual Numerics. - **Sage** is a complete environment that integrates most of the packages we discuss here (and many more) into a self-contained system for mathematical computing based on Python but with its own language extensions. Because Sage’s GUI is via a Web browser, it doesn’t ship matplotlib or Mayavi GUI components, which require GUI toolkits such as WxWidgets and Qt. Sage is distributed under the terms of the GNU General Public License version 2. Finally, on modern Linux distributions, most of the individual open source Python libraries we’ve mentioned (including IPython, NumPy, SciPy, matplotlib, the Enthought tool suite, Cython, Sympy, and Networks) are available for installation via the built-in package management system. Some distributions also include older releases of Sage, but we prefer to use a more up-to-date Sage version downloaded directly from the project’s website. Just a few years ago, getting a complete set of Python tools for scientific computing installed on a system was a daunting effort. Now, thanks to the efforts of these projects, the situation is drastically different. We’ve successfully used EPD for teaching multiple scientific computing workshops, where students at the high school, college, and graduate level have self-installed the platform with “one-click” installers. This has made an enormous difference in the ease with which newcomers can get started with the language. Users have several options, depending on their specific needs. Some might want the convenience of an integrated, single-click installer like those in EPD, Sage, or PythonXY, while others might need customized installations. Sage fully supports building the entire system from source from a single makefile, so that users can adapt the project to their local needs. In special environments with custom hardware or limited storage, users can forgo integrated downloads and opt to use only those libraries that they need. This freedom can be invaluable and is something that can’t be done with large commercial systems that are only provided by the vendors for a limited number of architectures. **Getting Started** After installing one of the prepackaged distributions we described earlier, you can take advantage of the vast amount of documentation—both free and for pay, online and in print—to speed your way to using Python and the core tools discussed here. The official Python tutorial (http://docs.python.org/tutorial) provides a solid introduction to the language; for more depth, *The Python Essential Reference* provides an excellent treatment of the language and standard library. The SciPy documentation portal (http://scipy.org/doc) provides links to reference and user documentation for Numpy and SciPy, and the additional documentation section (http://scipy.org/Additional_Documentation) offers links to many helpful tutorials and overviews, such as a guide to transitioning from Matlab to Python and Numpy. In 2007, Travis Oliphant wrote an article in a previous CiSE special issue on Python detailing its strengths for scientific computing. At that point, many of the core pieces of the puzzle were only beginning to solidify, the documentation was scattered and incomplete, the Sage system was in its infancy, and systems like Cython, Sympy, and the SciPy scikits infrastructure didn’t yet exist. Today, although much work remains, we can safely say that the community has found a core set of effective tools and is busy developing new directions based on this foundation. Python still lags behind projects such as R in offering a full library of statistical and time-series functionality, but rapid progress is being made on this front in pystatsmodels and other related projects. We now have in Python a rich environment based on a solid and well-designed language and with increasingly high-quality tools. This ecosystem, which emerged from a fruitful and open collaboration of academics and industry partners, lets scientists, engineers, and educators find precisely the parts they need. Having well-documented, open source computational tools will be increasingly important as computing becomes an integral component of all scientific research and engineering work; fortunately, all the projects we have listed here continue to grow, and important new areas are being tackled. Python has now entered a phase where it’s clearly a valid choice for high-level scientific code development, and its use is rapidly growing. This growth is occurring thanks to the dedicated work of many contributors throughout the past two decades; we hope that many more will follow in kind, finding creative ways to solve many problems that remain. Acknowledgments We thank Guido van Rossum for comments regarding Python’s history, and Ariel Rokem, William Stein, Michael Trumpis, and Stéfan van der Walt for valuable feedback on the entire article. We also thank the anonymous reviewers for their careful reading and detailed comments. The US National Institutes of Health partially support Fernando Pérez’s work under grant SR01MH081909-02. References Fernando Pérez is an associate researcher at the University of California, Berkeley’s Helen Wills Neuroscience Institute. His research interests include developing methods and tools for analyzing neuroimaging data, using high-level languages for scientific computing, and exploring new approaches to distributed and parallel problems. He contributes to the scientific Python ecosystem as a developer and educator; he is the original author of the IPython interactive environment and leads its development in collaboration with Brian Granger. Pérez has a PhD in theoretical physics from the University of Colorado at Boulder. Contact him at Fernando.Perez@berkeley.edu. Brian Granger is an assistant professor in the Physics Department at Cal Poly State University, San Luis Obispo, California. His research interests include computational quantum mechanics and parallel and distributed computing in scientific computing. He leads the IPython development in collaboration with Fernando Pérez. Granger has a PhD in theoretical physics from the University of Colorado. Contact him at bgranger@calpoly.edu. John Hunter is senior quantitative analyst at TradeLink Securities. Hunter has a PhD in neurobiology at the University of Chicago, and is the author and lead developer of the matplotlib scientific visualization package. Contact him at jdh2358@gmail.com.
{"Source-Url": "http://fperez.org/papers/perez11_cise_python_ecosystem.pdf", "len_cl100k_base": 6692, "olmocr-version": "0.1.53", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 30840, "total-output-tokens": 7620, "length": "2e12", "weborganizer": {"__label__adult": 0.00035691261291503906, "__label__art_design": 0.0004868507385253906, "__label__crime_law": 0.00029921531677246094, "__label__education_jobs": 0.0033245086669921875, "__label__entertainment": 0.00016069412231445312, "__label__fashion_beauty": 0.0001901388168334961, "__label__finance_business": 0.0004808902740478515, "__label__food_dining": 0.0005674362182617188, "__label__games": 0.000492095947265625, "__label__hardware": 0.0011911392211914062, "__label__health": 0.0008130073547363281, "__label__history": 0.0005555152893066406, "__label__home_hobbies": 0.0001977682113647461, "__label__industrial": 0.0008416175842285156, "__label__literature": 0.0005035400390625, "__label__politics": 0.0003457069396972656, "__label__religion": 0.0006804466247558594, "__label__science_tech": 0.257568359375, "__label__social_life": 0.0002491474151611328, "__label__software": 0.0213470458984375, "__label__software_dev": 0.7080078125, "__label__sports_fitness": 0.0003178119659423828, "__label__transportation": 0.0007085800170898438, "__label__travel": 0.0002503395080566406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 35610, 0.02014]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 35610, 0.70546]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 35610, 0.90874]], "google_gemma-3-12b-it_contains_pii": [[0, 2096, false], [2096, 6787, null], [6787, 11280, null], [11280, 15139, null], [15139, 16648, null], [16648, 21330, null], [21330, 26117, null], [26117, 30870, null], [30870, 35610, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2096, true], [2096, 6787, null], [6787, 11280, null], [11280, 15139, null], [15139, 16648, null], [16648, 21330, null], [21330, 26117, null], [26117, 30870, null], [30870, 35610, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 35610, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 35610, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 35610, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 35610, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 35610, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 35610, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 35610, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 35610, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 35610, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 35610, null]], "pdf_page_numbers": [[0, 2096, 1], [2096, 6787, 2], [6787, 11280, 3], [11280, 15139, 4], [15139, 16648, 5], [16648, 21330, 6], [21330, 26117, 7], [26117, 30870, 8], [30870, 35610, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 35610, 0.0]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
35cd906ff311a04a29073d035b42ce6bf0286de6
# Table of Contents ASSEMBLY LANGUAGE PROGRAMMING ........................................................................................................ 2 1.0. INTRODUCTION- TERMINOLOGIES ........................................................................................................ 2 1.1. Programming Languages ......................................................................................................................... 2 1.1.1. Low Level Languages ....................................................................................................................... 2 1.1.2. High level languages: ....................................................................................................................... 8 1.2. Classification of instructions sets ............................................................................................................. 8 1.2.1. Instructions set ................................................................................................................................ 8 1.2.2. Instruction set architecture (ISA) ..................................................................................................... 9 1.2.2. The 8085 Instruction set .................................................................................................................. 10 1.2.3. Classification of 8085 instructions ..................................................................................................... 10 1.2.4. Hand Assembling (Assembly process using lookup tables) .............................................................. 12 1.3. Assembly Language Instruction Format .................................................................................................... 12 2.0. ADDRESSING MODES ............................................................................................................................ 15 2.1. Definition ................................................................................................................................................ 15 2.2. Register–Register Addressing ................................................................................................................. 15 2.3. Immediate Addressing ............................................................................................................................ 15 2.4. Direct Addressing .................................................................................................................................. 16 2.5. Indirect Addressing Mode ....................................................................................................................... 16 2.6. Implied Addressing ................................................................................................................................ 17 2.7. Indexed Addressing ................................................................................................................................. 17 2.8. Relative addressing ................................................................................................................................. 17 2.9. Page Zero Addressing Mode .................................................................................................................. 18 2.10. Modified Page Zero Addressing ........................................................................................................ 18 2.11. Base Register Addressing .................................................................................................................... 19 2.12. Page Addressing .................................................................................................................................... 19 2.13. Bit Addressing ..................................................................................................................................... 20 2.14. Combined Addressing Modes ............................................................................................................... 21 3.0. DATA TRANSFER INSTRUCTIONS ........................................................................................................ 22 3.1. Moving data between internal processor Registers ............................................................................... 22 3.2. Moving specified data into an internal register ....................................................................................... 23 3.3. Moving data between Accumulator and specified memory location, and between H-L pair and specified memory locations ........................................................................................................ 24 3.4. Moving data between any processor register and memory location without specifying the memory address directly .................................................................................................................................................. 25 4.0. Programming examples ........................................................................................................................... 27 References ......................................................................................................................................................... 28 **ASSEMBLY LANGUAGE PROGRAMMING** 1.0. INTRODUCTION - TERMINOLOGIES *Program* is a set of instructions written in a specific sequence for a computer to accomplish a given task. The process of developing a program is therefore referred to as *programming.* A Microcomputer may be described as a digital device that reads binary coded data from its inputs, manipulates this data according to a program stored within its memory, and subsequently produces information at its output. ![Diagram of Microprocessor and Input/Output Flow] 1.1. Programming Languages. There are basically TWO types of computer programming languages: 1.1.1. Low Level Languages This is a medium of communication with a computer that is machine-dependent (or specific to a given computer). The machine and Assembly languages of a computer are considered as low level languages. (i) *Machine Language* is the binary medium of communication with a microprocessor (computer) through a designed set of instruction (instruction set) specific to each microprocessor (CPU). Machine language is written using strings of 0’s and 1’s. For example, for 8085 CPU Microprocessor, <table> <thead> <tr> <th>Instruction</th> <th>Comments</th> </tr> </thead> <tbody> <tr> <td>(i) 01000101</td> <td>Is the instruction for move. It instructs the 8085 CPU to Move the data in the Register L to the Register B</td> </tr> <tr> <td>(ii) 0000011000011000</td> <td>Instructs the CPU to load 18H into Register B This replaces the original contents of the register.</td> </tr> </tbody> </table> Assembly Instruction format and Data Transfer Instructions (iii) 001100101000010000001010 Instructs the computer the CPU to store the contents of the accumulator to the memory location whose address is specified by byte 2 and byte 3. Programming directly in machine Languages is extremely tedious, time consuming and the process is error-prone since every bit must be perfect. **Instruction types** On traditional architectures, an instruction includes an opcode that specifies the operation to be performed, such as add contents of memory to register—and zero or more operands pecifiers, which may specify registers, memory locations, or literal data. A Machine instruction may be 1, 2, or 3 bytes in length for 8085 CPU or even 4 bytes for some other microprocessors like Z-80. In any of these types of instructions, the first byte indicates the operation to be performed (Always referred to as the *operation code or opcode*). The second and third byte, if present, contains either the operand or address of the operand on which the operation is to be performed. The opcode is referred to as the *instruction field* while the other bytes are referred to as *the Data/Address field*. **One Byte Instruction** This type of instruction has only op code part of one byte and no operand is given. The instruction length is only of one byte. It can be stored only in one memory location. For example MOV C,B ANO C RAR etc. If ‘MOV C,B’ instruction is to be stored in some location say 8400H, then its op code of one byte is to be fed in this memory location. i.e. 8400H 48H where 48H is the op code of the instruction ‘MOV C,B’. **Two Byte Instruction** In a two byte instruction, first byte of the instruction is its op code and second byte is the given data. Such instruction is stored in two consecutive memory locations. For example MVI A, 06H OUT 03H ANI 76H etc. ![2-byte instruction diagram](image) In order to store the instruction say ‘MVI A, 06 H’ in the memory locations of the computer, two consecutive memory locations should be used. In one memory location the op code of MVI A is to be stored and in the second location the data 06H is to be stored. This type of instruction to be stored in two locations say in 2101H and 2102H is given below: 2101H 3EH (op code of MVI A) 2102H 06H (given data) **Three Byte Instruction** In a three byte instruction, first byte is used for its op code and second and third bytes are used for 16 bit address. Such an instruction is stored in three consecutive memory locations. For example LDA 2100H STA 3000H JMP 2500H etc. ![3-byte instruction diagram](image) In order to store the instruction LDA 2100H three consecutive memory locations are to be used. In the first memory location op code of the instruction is stored, in second location lower byte of the address is to be stored and in the third byte upper byte of the address is to be stored. This instruction loaded in three consecutive memory location 2000H, 2001H and 2002H is given below: 2000H 3AH (op code of LDA) 2001H 00H (Lower byte of address 2100 H) 2002H 21H (Upper byte of address 2100 H) (ii) **Assembly Language**: is a medium of communication with a computer in which programs are written in mnemonics. An assembly language is specific to a given CPU—i.e. they are not transferable from one CPU to another except through a specifically designed translator. **Mnemonics** In general, a mnemonic is a memory aid/tool, such as an abbreviation, rhyme or mental image that helps to remember something or **Mnemonics are memory devices that help learners recall larger pieces of information, especially in the form of lists like characteristics, steps, stages, parts, phases, etc.** The technique of developing these remembering devices is called "mnemonics." Mnemonics can be used to remember phone numbers, names of workmates etc. In computer assembly language, a mnemonic is a symbolic name for a single executable machine language instruction (an opcode) and there is at least one opcode mnemonic defined for each machine language instruction. It's entered in the operation code field of each assembly language program instruction. **In other words, it is a symbol representing an opcode or symbolic opcode.** It is a combination of letters which suggests the operation of an instruction or it is a memory aid with a “sound” suggesting its meaning. E.g. LD might stand for LoaD LDA might stand for LoaD Accumulator. STA might stand for Store Accumulator. etc. Thus the mnemonics for a particular instruction consists of letters which suggest the operation to be performed by the instruction. INR A (INR = IIncRement, A=Accumulator) Programmers can write programs called *assembly language program* using these words. Before a program written in assembly language can be executed by a microprocessor, it needs to be translated into an equivalent machine language program. This translation could be done manually (hand assembly) or on a computer using software called An Assembler. An Assembler is a computer program that translates an assembly language program from mnemonics to the binary machine code of the microprocessor (computer). Each microprocessor has its own assembler because the mnemonics and machine codes are specific to the microprocessor being used. It accepts an assembly language program as data, converts the mnemonics codes into their numeric equivalent, assign symbolic address to memory location and produces, as output, the required machine code program. The assembly language program is termed as the Source Program and the Final Machine code program is called the Object Program. The assembler has three main functions: 1. Replacement of symbolic opcode (mnemonics) with binary code 2. Assign storage to instructions and output 3. Set the operand addresses. The assembler program performs the clerical task of translating symbolic code into object code which can be executed by the 8085 microprocessors. Assembler output consists of three possible files: - **i.** the object file containing source program translated into object code; - **ii.** the list file printout of the source code, the assembler generated object code, and the symbol table; the list file provides a permanent record of both the source program and the object code, The assembler’s list file also provides diagnostic messages for common programming errors in the program listing. - **iii.** and the symbol-c ras s-reference file, a listing of the symbol-cross-reference records. The symbol-c ras s-reference list file is another of the diagnostic tools provided by the assembler. Assume, for example, that the developed program manipulates a data field Assembly Instruction format and Data Transfer Instructions named DATE, and that testing reveals a program logic error in the handling of this data. The symbol-crass-reference listing simplifies debugging this error because it Points to each instruction that references the symbol DATE. Some assemblers generates only the object file and the list file *This is a source file (source program)* ```assembly PORT1 EQU 21H ;Input port address PORT2 EQU 22H ;Output port address PORTR EQU 20H ;Control register ORG 8400H ;Starting address for program ; assembling START: MVI A,05H ;Control word OUT PORTR ;Command register REPEAT: MVI A,00H ;Switch off all LEDs OUT PORT2 MVI A,0FFH ;Switch on all LEDs OUT PORT2 ;display on LEDs IN PORT1 ;Read state if input switches JMP REPEAT ;go back and repeat END 01H ;end of assembling process ``` This is a object file (object program) :108400003E05D3203E00D3223EFFD322DB21D322E0 :03841000C304841E :00000101FE This is a print file (or list file) <table> <thead> <tr> <th>LINE</th> <th>ADDR</th> <th>CODE</th> </tr> </thead> <tbody> <tr> <td>0001</td> <td>0021</td> <td>PORT1 EQU 21H ;Input port address</td> </tr> <tr> <td>0002</td> <td>0022</td> <td>PORT2 EQU 22H ;Output port address</td> </tr> <tr> <td>0003</td> <td>0020</td> <td>PORTR EQU 20H ;Control register</td> </tr> <tr> <td>0004</td> <td>8400</td> <td>ORG 8400H ;Starting address for</td> </tr> <tr> <td>0005</td> <td>; program assembling</td> <td></td> </tr> <tr> <td>0006</td> <td>8400 3E05</td> <td>START: MVI A,05H ;Control word</td> </tr> <tr> <td>0007</td> <td>8402 D320</td> <td>OUT PORTR ;Command register</td> </tr> <tr> <td>0008</td> <td>8404 3E00</td> <td>REPEAT: MVI A,00H</td> </tr> <tr> <td>0009</td> <td>8406 D322</td> <td>OUT PORT2 ;Switch off all LEDs</td> </tr> <tr> <td>0010</td> <td>8408 3EFF</td> <td>MVI A,0FFH</td> </tr> <tr> <td>0011</td> <td>840A D322</td> <td>OUT PORT2 ;Switch on all LEDs</td> </tr> <tr> <td>0012</td> <td>840C DB21</td> <td>IN PORT1 ;Read state if input switches</td> </tr> <tr> <td>0013</td> <td>840E D322</td> <td>OUT PORT2 ;display on LEDs</td> </tr> <tr> <td>0014</td> <td>8410 C30484</td> <td>JMP REPEAT ;go back and repeat</td> </tr> <tr> <td>0015</td> <td>8413</td> <td>END 01H</td> </tr> </tbody> </table> 1.1.2 High level languages: Is a medium of communication that is machine independent (is independent of a given computer). Programs are written in English-like words, and they can be executed on a computer after translation. Commonly used translators are compilers and interpreters. High level languages are problem oriented languages unlike low level languages which are machine oriented. 1.2 Classification of instructions sets 1.2.1 Instructions set These are also called a command set, the basic set of commands, or instructions, that a particular microprocessor understands. 1.2.2 Instruction set architecture (ISA) An instruction set, or instruction set architecture (ISA), is the part of the computer architecture related to programming, including the native data types, instructions, registers, addressing modes, memory architecture, interrupt and exception handling, and external I/O. An ISA includes a specification of the set of opcodes (machine language), and the native commands implemented by a particular processor. Two important factors in instruction set design are decoder simplicity and code density. The decoder reads the next instruction from memory, and then routes the component pieces of that instruction appropriately. The design of the instruction set can dramatically affect the complexity and, therefore, the speed of decoding the instructions. Code density is the combined size of the instructions needed to perform a particular task. Higher density improves memory utilization. There are generally two classification of the instruction set. One of the principal characteristics that separate the two ISAs is the size and complexity of the instruction set. (a) A complex instruction set computer (CISC) - has many specialized instructions, some of which may only be rarely used in practical programs. A computer microprocessor that is based on CISC architecture has many instructions built into the chip. This makes the processing time for work more efficient since the required instructions are available directly to the microprocessor and do not have to be loaded from the computer’s memory or RAM. Although the CISC architecture helps speed up the programs’ execution, the number of instructions loaded on the processor negatively impacts processor performance. As a result, more transistors are built into the microprocessor to improve performance, which can result in an increase in the unit’s cost and power consumption. CISC processors are most commonly used in personal computers (PCs) using Intel and AMD processors. (b) A reduced instruction set computer (RISC) – is a type of microprocessor architecture that utilizes a small, highly-optimized set of instructions, rather than a more specialized set of instructions. It simplifies the processor design by efficiently implementing only the instructions that are frequently used in programs, while the less common operations are implemented as subroutines, having their resulting additional processor execution time offset by infrequent use. The RISC architecture has limited instruction sets built into the processor, resulting in fewer transistors having to be used in processor construction. This saves space on the microprocessor and results in a lower overall cost for the unit. To do work that is equivalent to what a CISC processor can do, a greater amount of computer RAM or memory is required. RISC processors were initially favored for scientific purposes since these applications did not require as large of an instruction set as general purpose computers. They are also used in Apple computers and mobile devices. In recent years, however, an increasing number of general purpose PCs using RISC microprocessors have been produced. 1.2.2 The 8085 Instruction set Each microprocessor is designed to execute a particular instruction set. The 8085 has an instruction set containing 74 basic instructions. Many, however, have variations increasing the actual number of distinct operations to 246. Instructions for the 8085 are 1 to 3 bytes in length. The bit pattern of the first byte is the opcode. This bit pattern is decoded in the instruction register and provides information used by the timing and control sections to generate a sequence of elementary operations—microinstructions—that implement the instruction. The second and the third bytes, the instruction operands, are either addresses or constants. 1.2.3. Classification of 8085 instructions For convenience to programmers, the 8085 instructions have been classified into the following five groups: (a) Data Transfer Group. The instruction in this group move data between the various microprocessor registers or between a microprocessor register and a memory location. e.g. MOV H,E ; Causes the contents of register E to be transferred to register H. STA 8700H ; causes the contents of Accumulator to be stored at memory location 8700H. (b) Arithmetic Group. Instruction in the Arithmetic group performs arithmetic operations on data that are either in a specific processor register or in a memory location. e.g. ADD L; causes the contents of the accumulator to be added to the content of register L. The result (sum) is stored in the accumulator. c) **Logical Group.** Instruction in the Logical group performs logical operations on data that are either in a specific processor register or in a memory location. e.g. ORA B ; cause a bit-by-bit OR operation to be performed on the contents of the B register and the accumulator. The result is placed in the accumulator. Arithmetic and Logical group of instructions are normally called **data manipulation** instructions. (d). **Branch (Transfer of control) Group.** The transfer of control group of instructions provides the computer with the ability to transfer from one sequence of operation to another; based on a variety of conditions. When such an instruction is encountered, the PC is changed to the address of the location of the new sequence. The next machine cycle begins with the new sequence of instructions. Some of these transfers of control instructions always force a jump to the new sequence while others base the jump on the result of a previous operation. If the jump is always made, it is called **an unconditional** branch. If the jump is based on machine data, such as a specific flag status, it is called a **conditional branch**. E.g. JMP 2800H ; is an unconditional branch to the memory location 2800H. JNZ 4760H ; is a conditional branch to the memory location 4760H only if the previous arithmetic (or logical) operation has **NOT** resulted into a zero, i.e. Zero flag is not set. (e). **Stack, Input/Output and Machine control group.** Instructions in the **input/output group** move data between the various I/O ports of the system and an internal register, usually the accumulator. e.g. OUT 22H causes the contents of the accumulator to be transferred to the output port with address 22H. The instructions in the **machine control group** affect the state or mode of operation of the processor itself. A common machine control instruction available in most microprocessors is the NOP (no operation). This causes the machine to wait through an instruction cycle. Others are HLT (or HALT), RIM etc **Stack instructions** are used to perform stack related operation. E.g. PUSH B causes the content of the B-C register pair to be stored in the stack. **Refer to the attached Instruction set** 1.2.4 Hand Assembling (Assembly process using lookup tables) (a) *One byte instructions* i. Mnemonic ADD B Translated Machine code 80 ii. Mnemonic MOV D, C Translated Machine code 51 iii. Mnemonic DCR B Translated Machine code 05 (b) *Two bytes instructions* i. Mnemonic MVI A, 55H Translated Machine code 3E55 ii. Mnemonic ADI 44H Translated Machine code C644 iii. Mnemonic IN 21H Translated Machine code DB21 iv. Mnemonic OUT 45H Translated Machine code D345 (c) *Three bytes instructions* i. Mnemonic CALL 2244H Translated Machine code CD4422 ii. Mnemonic LXI H, 3388H Translated Machine code 218833 iii. Mnemonics STA 8200H Translated Machine code 320082 *1st Byte (bold) in each translated code is the opcode* 1.3 Assembly Language Instruction Format Each instruction in an assembly program has four fields: a label field, a mnemonic field (or the opcode field), an operand field and a comment field. These fields follow each other in the sequence specified. All fields are optional. Furthermore, the comment field is not translated by the assembler during translation of the assembly program into an equivalent machine language program. When it is desired to write only a comment, all other fields may be omitted. <table> <thead> <tr> <th>Label</th> <th>Mnemonic</th> <th>Operand(s)</th> <th>Comments</th> </tr> </thead> <tbody> <tr> <td>START</td> <td>MOV</td> <td>A,B</td> <td>; Moves contents of Reg. B to Reg. A</td> </tr> </tbody> </table> Assembly Instruction format and Data Transfer Instructions POO4 : LXI H,5699H ; Get address 5699H into register-pair HL etc. **Label** Labels are programming aids used with jumps and calls. When writing a program, we often have no idea what address to use in a Jump or Call instruction. By using labels instead of numerical addresses, program writing becomes easy and more flexible. The assembler keeps track of the labels and automatically assigns the correct address to them. Since labels are symbolic addresses, one can use them in the operand fields. e.g. JMP LOOP where LOOP represents the target address. The label field contains a label. A label could be any character string consisting of lower and upper case letters (A-Z or a-z), digits (0-9) and the $ sign. The first character of the label must be a letter or a $ sign. Some assemblers place an upper limit on the number of characters in a label. A label is separated from the mnemonic by a colon. Similarly, any operand is separated from the mnemonic by at least one space character. The comment is separated from any operand by a semicolon. **Operands.** An explicit operand required by an instruction could be specified in one of several ways: i) No operand CMC ; This complements the carry flag. ii) Registers MOV A,B ; Move contents of Reg. B to Reg. A iii) Label LDA TEMP ; Get the contents of memory location TEMP and ; load them into the accumulator. STA START+2 One may use simple arithmetic expressions in the operand if it is a label. e.g. MVI B, 68H ; Gets the constant 68H into Reg. B Only expressions of the type \( X \pm C \) are allowed as operands, where \( X \) denotes a label and \( C \) is a constant. i) Immediate Operands (address or data) e.g. MVI B, 68H ; Gets the constant 68H into Reg. B Assembly Instruction format and Data Transfer Instructions LDA 4000H; Gets the contents of memory location 4000H into Acc. Constants in Assembly Language Programs Constants without any suffix will be treated by the assembler as decimal constants. Thus 100, 496 etc are all decimal constants. Suffixes B, H and O are used to indicate that the constant is binary, hexadecimal and octal respectively. e.g. 100B - is a binary constant 100H - is a hexadecimal constant A hexadecimal constant must be preceded by a 0 (zero) if it starts with any of the letters A-F. The assembler will treat A3H as a label (symbol) and not a constant. To force the assembler to treat A3H as a constant, it should be written as 0A3H. 2.0 **ADDRESSING MODES** 2.1 Definition An addressing mode is a method of specifying the address of the operand in an instruction. 2.2 Register–Register Addressing This addressing mode is used for data transfer and manipulation instruction involving the internal registers. The source and the destination register are contained within the instruction itself. - **e.g.** - MOV A,B - ADD C ---8085 CPU or LD H,D ADD A,D ----Z80 With these instructions, the accumulator is at times implied as a second operand. For example, the instruction CMP E may be interpreted as 'compare the contents of the E register with the contents of the accumulator. Most of the instructions that use register addressing deal with 8-bit values. However, a few of these instructions deal with 16-bit register pairs. For example, the PCHL instruction exchanges the contents of the program counter with the contents of the H and L registers. Also XCHG instruction which exchanges the contents of H-L register pair with that of D-E register pair. 2.3 Immediate Addressing In Immediate addressing, the operand to be acted upon is specified within the instruction. It is the byte(s) following the opcode. - **e.g.** - MVI B, 45H - LXI H, 3475H ---8085 or LD B, 73H LD HL, 8756H ----Z80 The names of the immediate instructions indicate that they use immediate data. Thus, the Assembly Instruction format and Data Transfer Instructions name of an add instruction is ADD; the name of an add immediate instruction is ADI. All but two of the immediate instructions uses the accumulator as an implied operand, as in the CPI instruction. The MVI (move immediate) instruction can move its immediate data to any of the working registers including the accumulator or to memory. Thus, the instruction MVI D, 0FFH moves the hexadecimal value FF to the D register. The LXI instruction (load register pair immediate) has its immediate data as a 16-bit value. This instruction is commonly used to load addresses into a register pair. LXI instruction is normally used to initialize the stack pointer; For example, the instruction LXI SP,30FFH loads the stack pointer with the hexadecimal value 30FF. 2.4 Direct Addressing In this addressing mode, the address of the operand is specified within (as part of) the instruction. Sometimes it is called absolute addressing mode. It is used to access data and write data into system memory. e.g. LDA 8600H STA 3450H OUT 22H IN 21H -8085 or LD HL,(8400H) LD (7560H),A OUT (23H),A -Z80 Instructions that include a direct address require three bytes of storage: one for the instruction code, and two for the 16-bit address 2.5 Indirect Addressing Mode. In this mode, the address of the operand is NOT contained in the instruction. The instruction only contains a pointer that stores the address of the operand. e.g. MOV M, A STAX B or LD A, (BC) LD C, (HL) OUT (C), B Register indirect instructions reference memory via a register pair. 2.6 **Implied Addressing** In implied addressing mode, the location of the operand is contained within the opcode. In most cases, it is the accumulator. e.g. <table> <thead> <tr> <th>Instruction</th> <th>8085</th> <th>Z80</th> </tr> </thead> <tbody> <tr> <td>CMA</td> <td></td> <td></td> </tr> <tr> <td>RAL</td> <td>-805</td> <td></td> </tr> <tr> <td>NEG</td> <td></td> <td>-Z80</td> </tr> <tr> <td>CPL</td> <td></td> <td></td> </tr> </tbody> </table> **Advantages and Disadvantages** 1. Implied –are one byte instruction and hence are faster to execute, and occupies less memory. 2. Direct addressing-It is simple to use but since most are 3 byte instructions, it takes longer time to execute and occupies more memory space. 3. Indirect Addressing- allows convenient ways of accessing data stored in sequential memory block. Most are one byte instruction (8085) and hence occupies less memory. But they sometimes take longer to execute. Some microprocessors use other addressing modes that are not available via single instructions in the 8085. Some of these addressing modes are not supported by 8085 directly because of the nature of 8085’s internal architecture. However, these addressing modes can be synthesized by combining two or more8085 instructions. 2.7 **Indexed Addressing.** In Index addressing, the instruction specifies both an index register and an address displacement. The content of the register is added to the displacement to produce the final effective address of the operand. In this way, the address could be the beginning of a table in the memory. The index register would then be used to access all the elements of a memory block/table successively in an efficient way, just by incrementing or decrementing the displacement. e.g. LD A,(IY+d) - Load accumulator with data stored at address pointed by (IY index register + the displacement). 2.8 **Relative addressing.** This addressing mode is used to effectively and efficiently implement transfer of control. instructions (Jumps). The instruction under this addressing mode uses only two bytes. The first byte is the branch specification, (conditional or unconditional) and the second byte is the displacement. Since the displacement must be positive or negative (2’s complement), relative branching can be used to branch forward to 127 locations or to branch backward 128 locations. Because most loops tend to be short, relative branching can be used most of the time and results in significantly improved performance. e.g. JR NC, 04H - Jumps forward 4 locations JR Z, F2H - Jumps backward 14 locations \[ F2H = 11110010_{(2,C)} = -14_{(10)} \] 2.9 Page Zero Addressing Mode This is similar to direct addressing except that it requires two-byte instruction. The Least significant byte of the address containing the operand is contained in byte 2 of the instruction. Byte 1 is the opcode. It is then assumed that the most significant byte of the address are 00H. Using this mode, it is clear that the operand can only be stored within the address range 0000H-00FFH i.e. the first 256_{(10)} memory locations. 2.10 Modified Page Zero Addressing. It is provided with one instruction namely RST. The effect of this instruction is to cause a jump to a new address on page zero (0000-00FFH), defined by the value of ‘nnn’ after pushing the contents of the PC on to the stack. 2.11 Base Register Addressing Base register addressing conceptually, is almost identical to indexing and in several large computing machine, the same hardware is utilized to contain an address (base). The address displacement in the instruction is added to the contents of the base register to obtain the effect address of the operand. The displacement may be a signed binary number so that the operand may be found at an address above or below that contained in the base register. 2.12 Page Addressing This is a variant of the base register addressing. The main storage is divided into sectors or pages. Each page has a maximum size equal to the addressing range of the displacement. A page /sector address register is preloaded with the high order bits of the effective address. The full effective address is formed by **concanating** the high-order bits in the sector address register with the displacement bits; the displacement forms the least significant bits of the effective address. This technique is often called pagination or sectorization. 2.13 Bit Addressing This addressing mode is used to access specific bits in a register or memory location. E.g. Z80 CPU is equipped with special instruction for setting, resetting and testing specific bits in a memory location or a register. E.g. 1. BIT b,(HL) - Test bit b of indirectly address memory location. The specified bit of the memory location addressed by the HL register pair is tested and the Z flag is set according to the result. b may be 0,1,2,3,4,---7. BIT b,r - Test bit b of register r e.g. BIT 6,A - tests bit 6 of register A contents and zero flag is set according to the result. r=A,B,C,D,E,H,L,(HL) 2. RES b,s - Reset bit b of operand s b: 0,1,2,3……7 s: A, B,C,D,E,H,L, 3. SET b,s - set bit b of operand sb ← 1 s: A,B,C,…..H,L,(HL) b:0,1,2,…..7 The specified bit of the location determined by s is set. 2.14 Combined Addressing Modes Some instructions use a combination of addressing modes. A CALL instruction, for example, combines direct addressing and register indirect addressing. The direct address in a CALL instruction specifies the address of the desired subroutine; the register indirect address is the stack pointer. The CALL instruction pushes the current contents of the program counter into the memory location specified by the stack pointer. Timing Effects of Addressing Modes: Addressing modes affect both the amount of time required for executing an instruction and the amount of memory required for its storage. For example, instructions that use implied or register addressing, execute very quickly since they deal directly with the processor’s hardware or with data already present in hardware registers. Most important, however is that the entire instruction can be fetched with a single memory access. The number of memory accesses required is the single greatest factor in determining execution timing. More memory accesses therefore require more execution time. A CALL instruction for example, requires five memory accesses: three to access the entire instruction and two more to push the contents of the program counter onto the stack. The processor can access memory once during each processor cycle. Each cycle comprises a variable number of states. The length of a state depends on the clock frequency specified for the system, and may range from 480 nanoseconds to 2 microseconds. Thus, the timing for a four state instruction may range from 1.920 microseconds through 8 microseconds. (The 8085 have a maximum clock frequency of 5 MHz and therefore a minimum state length of 200 nanoseconds.) 3.0 DATA TRANSFER INSTRUCTIONS. Data Transfer Instructions move data (generally byte length data), from one location to another e.g. between various processor registers or between a processor register and a memory location. The source of the data is defined in the instruction. 3.1 Moving data between internal processor Registers. The instruction to move data between processor registers is the mnemonic MOV. (MOVe) This one-byte instruction’s operand defines the source and the destination. e.g. \[ \text{MOV } r_1, r_2 \] MOV is the operation mnemonics r₁ is the destination register r₂ is the source register MOV C, B -causes the contents of B-register to be transferred to the C-register. The contents of register B remain unchanged. \[ \text{(C) is the destination register} \text{(B) is the source register} \] For Z80 CPU LD r₁, r₂ Loads the contents of r₂ into r₁ The 8085 allow limited 16-bit data transfer operation. The instruction dealing with 16-bits is XCHG This instruction causes the contents of the combined D-E pair and H-L pair to be exchanged \[ \text{XCHG} \] These are one-byte instructions. For Z80 CPU EX DE, HL this instruction causes the contents of the combined D-E pair and H-L pair to be exchanged \[ \text{EX DE, HL} \] 3.2 Moving specified data into an internal register. I. The mnemonic (operand) that loads a specified 8-bit data into a register is MVI (MoVe Immediate) e.g. MVI r, data Specified data (byte) Destination register Operation MVI A, 44H -loads register A with 44H. (A) 44H MVI B, 6BH -loads register B with 6BH (B) 6BH. These are two byte instructions For Z80 CPU LD r1, n Loads n into register r1 II The mnemonic that loads a specified 16-bit data /Address into register B-C, D-C, H-L pair and SP is LXI (Load immediate) e.g. LXI H, 8635H 16-bit data/Address Destination register pair (H-L) Mnemonic (H-L) 8635H LXI SP, 8700H (SP) 8700H Loads SP with 8700H (Initialising the stack) These are 3 byte instructions. For Z80 CPU LD dd, nn Loads nn into registers pair dd; where dd may be BC, HL, DE, or SP 3.3 Moving data between Accumulator and specified memory location, and between H-L pair and specified memory locations. (These are three bytes instructions). I. Between accumulator and memory location -The Instruction used to load data into the Accumulator from specified memory location is LDA (Load Accumulator) e.g. LDA 8600H - This causes the A register to be loaded with the contents of the memory location whose address is 8600H. (A) ←→ (8600H) - The instruction used to store the contents of the accumulator into memory location is Store Accumulator, STA. e.g. STA 8500H causes the contents of the accumulator to be stored in the memory location with address 8500H. (A) → (8500H) For Z80 CPU LD A, (nn) this causes the A register to be loaded with the contents of the memory location whose address is nn H. LD (nn), A causes the contents of the accumulator to be stored in the memory location with address nn H II. Between the H-L pair and specified memory location -Instruction that loads H-L pair with data from specified memory location is LHLD. (Load H-L Direct) e.g. LHLD 6000H This loads the contents of memory location 6000H into register L while register H is loaded with the contents of the next consecutive location, 6001H. (L) ←→ (6000H) (H) ←→ (6001H) -Instruction that store the contents of H-L pair into specified memory location is Store H-L Direct, SHLD E.g. SHLD 2000H - Stores the contents of H-L pair into memory location with address 2000H and 2001H. For Z80 CPU **Assembly Instruction format and Data Transfer Instructions** - **LD HL, (nn)** this loads the contents of memory location nn into register L while register H is loaded with the contents of the next consecutive location, nn+1. - **LD (nn), HL** this loads the contents of register L into memory location nn while the contents of register H are loaded into the next consecutive location, nn+1. ### 3.4 Moving data between any processor register and memory location without specifying the memory address directly. (The memory address is assumed to be stored in a register pair). I. When the register pair holding the memory address is H-L, H-L is referenced using the single letter M (a) **Moving data between register and memory location:** E.g. MOV B, M The contents of memory location whose address is in the H-L register pair is moved to register B i.e. \( B \leftarrow ((H-L)) \) Also MOV M, B \( B \rightarrow ((H-L)) \) - **LD r, (HL)** the contents of memory location whose address is in the H-L register pair is moved to register r where r may be A, B, C, D, E (b) **Moving a specified data into memory location whose address is in the H-L pair register:** MVI M, data e.g. MVI M, 86H \( ((H-L)) \leftarrow 86H \) - **LD (HL), n** this loads n into the memory location whose address is in the H-L II. Moving data between accumulator and memory location whose address is stored in B-C or DE register pair. LDAX D - loads the accumulator with data from memory whose address is in the D-E pair registers. \( A \leftarrow ((D-E)) \) LDAX B - loads the accumulator with data from memory whose address is in the B-C register pair. \( A \leftarrow ((B-C)) \) STAX D - stores the contents of accumulator into memory whose address is in D-E register pair. (A) \rightarrow ((D-E)) STAX B - stores the contents of the accumulator into memory location whose address is in B-C register pair. (A) \rightarrow ((B-C)) For Z80 CPU LD (BC), A stores the contents of the accumulator into memory location whose address is in B-C register pair. For Z80 CPU LD A, (DE) loads the accumulator with data from memory whose address is in the D-E pair registers. For Z80 CPU Most data transfer operations, between registers, between register and memories are accomplished by the instruction LD. For example Between register A, D LD, D,A Immediate LD C,32H Indirect transfers LD (HL),56H Register pair loading LD BC,45E8H etc 4.0 Programming examples Q1. Outline, giving examples, the SIX groups of instructions under which the 8085 CPU instruction set may be classified. Q2. (a) Develop an 8085CPU assembly program to perform the following: i. Load 48H, F3H, 76H, and 40H into registers A, B, C and H respectively ii. transfer the contents of register B into register L iii. store the contents of Register A into memory location with address 3001H iv. store the contents of register C into memory location pointed by HL register pair. v. Stop Solutions i. MVI A,48H MVI B,F3H OR MVI B,0F3H MVI C,76H MVI H,40H ii. MOV L,B iii. STA 3001H iv. MOV M,C v. HLT (b) Draw a trace table for the program listing in Q2 (a) and fill in the contents <table> <thead> <tr> <th>Instructions</th> <th>A</th> <th>B</th> <th>C</th> <th>H</th> <th>L</th> <th>3001H</th> <th>(HL)-40F3H</th> </tr> </thead> <tbody> <tr> <td>Initial state</td> <td>X</td> <td>X</td> <td>X</td> <td>X</td> <td>X</td> <td>X</td> <td>X</td> </tr> <tr> <td>MVI A,48H</td> <td>48H</td> <td>X</td> <td>X</td> <td>X</td> <td>X</td> <td>X</td> <td>X</td> </tr> <tr> <td>MVI B,F3H</td> <td>48H</td> <td>F3H</td> <td>X</td> <td>X</td> <td>X</td> <td>X</td> <td>X</td> </tr> <tr> <td>MVI C,76H</td> <td>48H</td> <td>F3H</td> <td>76H</td> <td>X</td> <td>X</td> <td>X</td> <td>X</td> </tr> <tr> <td>MVI H,40H</td> <td>48H</td> <td>F3H</td> <td>76H</td> <td>40H</td> <td>X</td> <td>X</td> <td>X</td> </tr> <tr> <td>MOV L,B</td> <td>48H</td> <td>F3H</td> <td>76H</td> <td>40H</td> <td>F3H</td> <td>X</td> <td>X</td> </tr> <tr> <td>STA 3001H</td> <td>48H</td> <td>F3H</td> <td>76H</td> <td>40H</td> <td>F3H</td> <td>48H</td> <td>X</td> </tr> <tr> <td>MOV M,C</td> <td>48H</td> <td>F3H</td> <td>76H</td> <td>40H</td> <td>F3H</td> <td>48H</td> <td>76H</td> </tr> <tr> <td>HLT</td> <td>48H</td> <td>F3H</td> <td>76H</td> <td>40H</td> <td>F3H</td> <td>48H</td> <td>76H</td> </tr> </tbody> </table> (c) Hand-assemble the program in 2(b) and determine the memory capacity of the program in bits Solutions <table> <thead> <tr> <th>Mnemonics</th> <th>Machine code</th> </tr> </thead> <tbody> <tr> <td>i. MVI A,48H</td> <td>3E48</td> </tr> <tr> <td>MVI B,F3H OR MVI B,0F3H</td> <td>06F3</td> </tr> <tr> <td>MVI C,76H</td> <td>0E76</td> </tr> <tr> <td>MVI H,40H</td> <td>2640</td> </tr> <tr> <td>ii. MOV L,B</td> <td>68</td> </tr> <tr> <td>iii. STA 3001H</td> <td>320130</td> </tr> <tr> <td>iv. MOV M,C</td> <td>71</td> </tr> <tr> <td>v. HLT</td> <td>76</td> </tr> </tbody> </table> Memory capacity occupied by the program is **14 bytes** References 2. The MCS-80/85 Family User manual by Intel Corporation 5. Assorted websites Assembly Instruction format and Data Transfer Instructions
{"Source-Url": "http://elearning.tukenya.ac.ke/pluginfile.php/14949/mod_resource/content/2/Assembly_Language_Programming_with_data_transfer_notes.pdf", "len_cl100k_base": 10719, "olmocr-version": "0.1.53", "pdf-total-pages": 29, "total-fallback-pages": 0, "total-input-tokens": 59210, "total-output-tokens": 12079, "length": "2e13", "weborganizer": {"__label__adult": 0.0007557868957519531, "__label__art_design": 0.0011768341064453125, "__label__crime_law": 0.0006198883056640625, "__label__education_jobs": 0.0051422119140625, "__label__entertainment": 0.0001614093780517578, "__label__fashion_beauty": 0.0004651546478271485, "__label__finance_business": 0.0006432533264160156, "__label__food_dining": 0.0006527900695800781, "__label__games": 0.0023746490478515625, "__label__hardware": 0.1529541015625, "__label__health": 0.0009918212890625, "__label__history": 0.0007061958312988281, "__label__home_hobbies": 0.0007867813110351562, "__label__industrial": 0.004940032958984375, "__label__literature": 0.0004699230194091797, "__label__politics": 0.0004215240478515625, "__label__religion": 0.0009822845458984375, "__label__science_tech": 0.27783203125, "__label__social_life": 9.566545486450197e-05, "__label__software": 0.0215606689453125, "__label__software_dev": 0.5234375, "__label__sports_fitness": 0.0008497238159179688, "__label__transportation": 0.0017604827880859375, "__label__travel": 0.000270843505859375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 45283, 0.06145]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 45283, 0.82493]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 45283, 0.83231]], "google_gemma-3-12b-it_contains_pii": [[0, 5350, false], [5350, 6807, null], [6807, 8449, null], [8449, 9725, null], [9725, 11777, null], [11777, 13529, null], [13529, 14417, null], [14417, 15918, null], [15918, 18276, null], [18276, 20373, null], [20373, 22573, null], [22573, 24195, null], [24195, 26035, null], [26035, 26752, null], [26752, 28162, null], [28162, 29754, null], [29754, 31632, null], [31632, 32953, null], [32953, 34057, null], [34057, 34817, null], [34817, 36633, null], [36633, 37901, null], [37901, 38712, null], [38712, 40251, null], [40251, 41934, null], [41934, 42703, null], [42703, 44173, null], [44173, 45225, null], [45225, 45283, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5350, true], [5350, 6807, null], [6807, 8449, null], [8449, 9725, null], [9725, 11777, null], [11777, 13529, null], [13529, 14417, null], [14417, 15918, null], [15918, 18276, null], [18276, 20373, null], [20373, 22573, null], [22573, 24195, null], [24195, 26035, null], [26035, 26752, null], [26752, 28162, null], [28162, 29754, null], [29754, 31632, null], [31632, 32953, null], [32953, 34057, null], [34057, 34817, null], [34817, 36633, null], [36633, 37901, null], [37901, 38712, null], [38712, 40251, null], [40251, 41934, null], [41934, 42703, null], [42703, 44173, null], [44173, 45225, null], [45225, 45283, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 45283, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, true], [5000, 45283, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 45283, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 45283, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 45283, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 45283, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 45283, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 45283, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 45283, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, true], [5000, 45283, null]], "pdf_page_numbers": [[0, 5350, 1], [5350, 6807, 2], [6807, 8449, 3], [8449, 9725, 4], [9725, 11777, 5], [11777, 13529, 6], [13529, 14417, 7], [14417, 15918, 8], [15918, 18276, 9], [18276, 20373, 10], [20373, 22573, 11], [22573, 24195, 12], [24195, 26035, 13], [26035, 26752, 14], [26752, 28162, 15], [28162, 29754, 16], [29754, 31632, 17], [31632, 32953, 18], [32953, 34057, 19], [34057, 34817, 20], [34817, 36633, 21], [36633, 37901, 22], [37901, 38712, 23], [38712, 40251, 24], [40251, 41934, 25], [41934, 42703, 26], [42703, 44173, 27], [44173, 45225, 28], [45225, 45283, 29]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 45283, 0.09641]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
cbe34ccbcb8180c1d6d2150f7a8d82e46153c086
Copyright Warning & Restrictions The copyright law of the United States (Title 17, United States Code) governs the making of photocopies or other reproductions of copyrighted material. Under certain conditions specified in the law, libraries and archives are authorized to furnish a photocopy or other reproduction. One of these specified conditions is that the photocopy or reproduction is not to be “used for any purpose other than private study, scholarship, or research.” If a user makes a request for, or later uses, a photocopy or reproduction for purposes in excess of “fair use” that user may be liable for copyright infringement. This institution reserves the right to refuse to accept a copying order if, in its judgment, fulfillment of the order would involve violation of copyright law. Please Note: The author retains the copyright while the New Jersey Institute of Technology reserves the right to distribute this thesis or dissertation. Printing note: If you do not wish to print this page, then select “Pages from: first page # to: last page #” on the print dialog screen. The Van Houten library has removed some of the personal information and all signatures from the approval page and biographical sketches of theses and dissertations in order to protect the identity of NJIT graduates and faculty. ABSTRACT DIGITAL LIBRARIES AND MIDDLEWARE ARCHITECTURE by Muhammad Umar Qasim Digital libraries deliver personalized knowledge directly to their users, without being restricted to the contents of a physical library. In a digital library information from any online source can be managed and shared, making more knowledge available to users than before. The information sharing is achieved by integrating many autonomous heterogeneous systems available. The challenge is to provide users with the ability to transparently access digital library contents in spite of the heterogeneity among the information sources. Research communities have proposed several approaches to accomplish the system integration in digital libraries. In this thesis, the working of currently employed approaches was assessed and a new ontology based approach is proposed. This approach utilizes the semantic web enables web services to implement the middleware for digital library integration. Ontology based digital library integration will provide a machine processable mechanism and will overcome the shortcomings of earlier approaches. DIGITAL LIBRARIES AND MIDDLEWARE ARCHITECTURE by Muhammad Umar Qasim A Thesis Submitted to the Faculty of New Jersey Institute of Technology in Partial Fulfillment of the Requirements for the Degree of Master of Science in Information Systems Department of Information Systems January 2005 APPROVAL PAGE DIGITAL LIBRARIES AND MIDDLEWARE ARCHITECTURE Muhammad Umar Qasim Dr. Michael Bieber, Thesis Advisor Associate Professor of Information Systems, NJIT Dr. Stéphane Gagnon, Committee Member Assistant Professor of Management, NJIT Dr. Vincent Oria, Committee Member Assistant Professor of Computer Science, NJIT BIOGRAPHICAL SKETCH Author: Muhammad Umar Qasim Degree: Master of Science Date: January 2005 Undergraduate and Graduate Education: - Master of Science in Information Systems, New Jersey Institute of Technology, Newark, NJ, 2004 - Master of Business Administration, Hamdard University, Karachi, Pakistan, 1999 - Bachelor of Computer Science, Hamdard University, Karachi, Pakistan, 1998 Major: Information Systems This thesis is dedicated to my beloved family ACKNOWLEDGMENT With a deep sense of appreciation, I would like to express my sincere thanks to Dr. Michael Bieber for his immense help in planning and executing this work. His support, encouragement and reassurance are greatly acknowledged. His valuable suggestions guided me in completing this work. My sincere thanks to Dr. Vincent Oria and Dr. Stephane Gagnon for reviewing this work and providing me important suggestions. Special thanks are due to Anirban Bhaumik for his assistance in this work. I wish I would never forget the company I had from my friends at my home. I am thankful to Mumtaz, Qazi, Umar, Akhtar and Nadeem for their countless cooperation, help and encouragement. TABLE OF CONTENTS <table> <thead> <tr> <th>Chapter</th> <th>Page</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>INTRODUCTION .................................................. 1</td> </tr> <tr> <td></td> <td>1.1 Objective .................................................. 1</td> </tr> <tr> <td></td> <td>1.2 Background Information .................................. 1</td> </tr> <tr> <td>2</td> <td>SYSTEM INTEGRATION ............................................. 4</td> </tr> <tr> <td></td> <td>2.1 System Integration Overview ................................ 4</td> </tr> <tr> <td></td> <td>2.2 Middleware .................................................. 6</td> </tr> <tr> <td>3</td> <td>DIGITAL LIBRARY INTEGRATION APPROACHES ...................... 8</td> </tr> <tr> <td></td> <td>3.1 ORB Approach ................................................ 8</td> </tr> <tr> <td></td> <td>3.2 Mediated Approach .......................................... 11</td> </tr> <tr> <td></td> <td>3.3 Agent-Based Approach ..................................... 14</td> </tr> <tr> <td></td> <td>3.4 A Service-Oriented Agent Architecture .................. 17</td> </tr> <tr> <td>4</td> <td>DIGITAL LIBRARY SERVICE INTEGRATION AT NJIT .................. 20</td> </tr> <tr> <td></td> <td>4.1 DLSI Overview ............................................... 20</td> </tr> <tr> <td></td> <td>4.2 DLSI Architecture .......................................... 21</td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td>4.3 Implementation Details ..................................... 25</td> </tr> <tr> <td></td> <td>4.4 Advantages of DLSI ......................................... 26</td> </tr> <tr> <td>Chapter</td> <td>Page</td> </tr> <tr> <td>---------</td> <td>------</td> </tr> <tr> <td>4.5 Disadvantages of DLSI</td> <td>26</td> </tr> <tr> <td>5 A NEW APPROACH TO DIGITAL LIBRARY INTEGRATION</td> <td>28</td> </tr> <tr> <td>5.1 Semantic Web Overview</td> <td>32</td> </tr> <tr> <td>5.1.1 Semantic Web</td> <td>32</td> </tr> <tr> <td>5.1.2 Resource Description Framework</td> <td>33</td> </tr> <tr> <td>5.1.3 Uniform Resource Identifiers</td> <td>34</td> </tr> <tr> <td>5.1.4 Ontologies</td> <td>34</td> </tr> <tr> <td>5.1.5 Ontologies and Services</td> <td>35</td> </tr> <tr> <td>5.1.6 Ontologies and Agents</td> <td>37</td> </tr> <tr> <td>5.2 Ontologies Based Approach</td> <td>38</td> </tr> <tr> <td>5.2.1 Markup Language for Ontologies</td> <td>38</td> </tr> <tr> <td>5.2.2 Digital Library Web Services and Architecture</td> <td>40</td> </tr> <tr> <td>5.2.1 Implementation Details</td> <td>44</td> </tr> <tr> <td>6 CONCLUSION</td> <td>46</td> </tr> <tr> <td>REFERENCES</td> <td>48</td> </tr> </tbody> </table> ## LIST OF FIGURES <table> <thead> <tr> <th>Figure</th> <th>Description</th> <th>Page</th> </tr> </thead> <tbody> <tr> <td>2.1</td> <td>Digital library integration architecture</td> <td>6</td> </tr> <tr> <td>3.1</td> <td>CORBA architecture</td> <td>9</td> </tr> <tr> <td>3.2</td> <td>The InfoBus infrastructure</td> <td>11</td> </tr> <tr> <td>3.3</td> <td>Mediated approach architecture</td> <td>12</td> </tr> <tr> <td>3.4</td> <td>Architecture of digital library service integration at NJIT</td> <td>14</td> </tr> <tr> <td>3.5</td> <td>Agent-based approach architecture</td> <td>15</td> </tr> <tr> <td>3.6</td> <td>UMDL architecture</td> <td>16</td> </tr> <tr> <td>4.1</td> <td>DLSI architecture</td> <td>21</td> </tr> <tr> <td>4.2</td> <td>Message flow in the ME</td> <td>24</td> </tr> <tr> <td>5.1</td> <td>Layered approach to markup language development</td> <td>39</td> </tr> <tr> <td>5.2</td> <td>DAML-enabled agents, tasked by users or other agents</td> <td>42</td> </tr> <tr> <td>5.3</td> <td>NJIT digital library web services functional requirements</td> <td>43</td> </tr> </tbody> </table> CHAPTER 1 INTRODUCTION 1.1 Objective The objective of this paper is to explore the various middleware implementation approaches for the system integration in the context of digital library integration. Often information sources have been designed independently for autonomous applications, so they may present several kinds of heterogeneity making the integration complicated. The approaches discussed in this paper present architecture to overcome the problems in the digital library integration. A detailed architecture of one approach is presented, which is being implemented at New Jersey Institute of Technology. A new approach for the digital library integration has been suggested for the future implementation. This approach is based on the Semantic web and ontologies. 1.2 Background Information Information is power, and digital libraries are built to provide a unified infrastructure for supporting the creation of information sources, facilitating the movement of information across global networks and allowing effective and efficient interaction among knowledge producers, librarians, and information seekers (Adam et al. 2000). Digital libraries are becoming widely accepted as sources for knowledge in all the areas such as science, engineering, education and business. It is being expected that the move from printed documents to digital documents will soon be ubiquitous and digital libraries will become integral and critical infrastructure for the nations around the world. A digital library is a collection of objects stored and maintained by multiple information sources, including databases, file systems, email systems, the web, and other formats. These information sources are diverse and dynamic in nature. For these reasons digital libraries have countless technical and engineering issues associated with connecting together these networks, databases, and other computer-based systems. A fundamental issue for digital libraries is interoperability, the capability of digital libraries to exchange and share documents, queries, and services (Birmingham et al.). Interoperability is the mechanism through which different systems work together and exchange data. Interoperability between different systems is achieved by using common standards and specifications. Interoperability could also be viewed as an integration of multiple systems. System Integration is the process by which multiple software modules are made to cooperate (Barret et al., 1996). System integration in digital libraries is the ability to generate a virtual view on many different library components without changing their autonomy. Therefore the challenge is to provide users with the ability to seamlessly and transparently access digital library objects in spite of the diversity and vitality among the information sources and the varied nature of the objects. To accomplish this, an effective system integration methodology must be adopted. The goal of data integration in digital library network is to provide users with a uniform interface to access, relate, and combine data stored in multiple, autonomous, and possibly heterogeneous information sources (Fahmi et al., 2001). Nowadays, a central topic in database science is the need of an integrated access to large amounts of data provided by various information sources whose contents are strictly related. Although there is a continuous and dramatic growth of digital libraries and information sources, however this growth has made the task of finding, extracting and aggregating the relevant information harder. This is because most of the information systems underlying digital libraries are physically distributed, heterogeneous in the way how information is stored, organized and managed, and comprise heterogeneous software and hardware platforms on which they reside. Additionally, they are autonomous in the sense that the content and format of data are determined by the organization owning the data, not by the user (Ibrahim et al., 2001). We start with the introductory Chapter 2 about the system integration and way of implementing it through middleware approach. In Chapter 3 we will explain different middleware approaches that are currently being used to implement the digital library integration. One of these approaches will be discussed in detail in the Section 4. This is approach is used at New Jersey Institute of Technology to implement digital library integration. In Chapter 5 a new ontologies based approach has been proposed for the digital library integration and its architecture has been discussed. We conclude and suggest the future work in Chapter 6. CHAPTER 2 SYSTEM INTEGRATION 2.1 System Integration Overview System integration is the progressive linking and testing of system components to merge their functional and technical characteristics into a comprehensive, interoperable system. System integration allows data existing on different systems to be shared or accessed across functional or system boundaries. System integration is the process through which a number of products and services are specified and assembled into a complete system that will achieve the intended functionality (Sage, 1992). The goal of system integration is to utilize various autonomous systems in concert so that they support the organizational goal, by providing an integrated set of data and services. System integration is one of the main reasons for the innovation in the software industry nowadays. Isolated applications are being left behind. Currently new systems are designed to be integrated. But this integration has a lot of challenges and complexities. We believe that in the future complexity will be reduced, but the demand for engineering competence in design, development, integration and maintenance of complex systems will increase. Nowadays, a central topic in database science is the need of an integrated access to large amounts of data provided by various information sources whose contents are strictly related. Often information sources have been designed independently for autonomous applications, so they may present several kinds of heterogeneity (Greco et al., 2002). Many practitioners are not able to repetitively carry out systems integration across different systems and vendor claims on integration packages are not always true (Nilsson et al., 1990). The candidate systems for integration can be considered to be composed of three architectural layers: business architecture layer, application architecture layer and technology architecture layer. The business architecture layer defines organizational structure and workflows. The application architecture layer defines the implementation of business logic in enterprise applications. The technology architecture layer defines the information and communication infrastructure (Hasselbring, 2000). System integration problem could be seen in three-dimensions with each dimension having its own objectives (Sikora et al., 1998). 1. Integration of heterogeneous information systems to facilitate the flow of data and make the overall system more robust. 2. Integration of business processes to improve performance. 3. Integration of subsystems into well-coordinated, networked system. Traditional systems integration is concerned with integration at the architecture and technology layer of heterogeneous systems. This represents system integration solutions commonly referred to as enterprise application integration or middleware technologies. The literature is not specific about the clear distinction between the two and many times both terms are used interchangeably. Software vendors provide various solutions for enterprise application integration, based either on metadata-, process-, service-, or portal-oriented integration technologies (Linthicum, 2004). In this report, we focus on the Service Oriented Architecture (SOA) as the primary middleware solution (Papazoglou & Georgakopoulos, 2003). 2.2 Middleware Middleware services sit in a layer above the operating system and network software but below the industry specific applications. They provide standard programming interfaces and protocols that mask the complexity of networks and lower level protocols (Bernstein, 1996). Middleware facilitates the communication and coordination of components that are distributed across several networked hosts. It aims at providing application engineers with high-level primitives that simplify distributed system construction (Emmerich, 2000). Figure 2.1 shows how a digital library interacts with the sources of information through middleware. Middleware is a layer between database resources and the client applications like digital library applications that want to use the database resources. Middleware programs provide messaging services so that different applications can communicate. ![Figure 2.1 Digital library integration architecture.](image) The main purpose of middleware services is to help solve many application connectivity and interoperability problems. The objective is seamless, large scale integration of heterogeneous components that will provide digital libraries the capability to communicate with heterogeneous sources. Middleware can take on the following different forms (Bray). - Transaction processing monitors provide tools and an environment for developing and deploying distributed applications. - Remote Procedure Call enables the logic of an application to be distributed across the network. Program logic on remote systems can be executed as simply as calling a local routine. - Message-Oriented Middleware provides program-to-program data exchange, enabling the creation of distributed applications. MOM is analogous to email in the sense it is asynchronous and requires the recipients of messages to interpret their meaning and to take appropriate action. - Object Request Brokers enables the objects that comprise an application to be distributed and shared across heterogeneous networks. For the implementation of Digital Libraries we will discuss different Middleware software architectures which are currently being used in the industry and academia. We will also discuss one of these approaches in detail which is being implemented at New Jersey Institute of Technology’s DLSI (Digital Library Service Integration) project. Also in the Section 5 of this paper introduces a new approach which can provide effective and efficient middleware architecture. (Adam et al. 2000) in his paper described three approaches, Object Request Brokers (e.g. CORBA), Mediated, and Agent-based, used for purpose of System Integration in the Digital Libraries. These three approaches are not orthogonal in the sense that a mediator approach may also use ORB architecture and an agent-based may use mediators. CHAPTER 3 DIGITAL LIBRARY INTEGRATION APPROACHES Middleware used for Digital Libraries is currently developed on the approaches described in this section. These approaches provide the architecture to access the information of heterogeneous nature. 3.1 ORB Approach Nowadays software integration projects are addressed by using object-based Web technologies. Object Request Broker (ORB) approach incorporates a standards-based framework to support the integration of many software applications. Architectures such as Common Object Request Broker Architecture (CORBA), Component Object Model (COM) and Enterprise JavaBeans (EJBs) support this approach. The utilization of such technologies enables the system to quickly evolve into an assembly of functional components, managed by an inter-object communications protocol and extending to the boundaries of the Internet. In ORB approach the client object must have an object reference to the server. The ORB approach is enjoying a rapid expansion due to three factors: - A more rigorous formalization of the approach. - A greater ease in mastering the development of system integration. - The rapid emergence of new technologies such as J2EE and .Net, which integrate fundamentally the idea of components. CORBA is one of the architectures being used to implement this approach. CORBA is an acronym for Common Object Request Broker Architecture. The Object Management Group (OMG) was formed in 1989 to develop standards for application development within heterogeneous environments. CORBA enables the creation of distributed object architectures. CORBA consists of ORB Core, Interface Definition Language (IDL), Stubs, Skeletons, and others. ORB Core is responsible for delivering requests to object implementation and responses from objects to the client requesting the service. CORBA provides the IDL as a mechanism for specifying the interface to an object. If a developer desires to make use of a service, the IDL specification is the only information required. The specification is compiled by an IDL processor that creates a stub which is linked into the client. The IDL compiler also generates a skeleton file that is used to connect the implementation of a service into CORBA's distributed object architecture. Figure 3.1 shows the CORBA architecture. ![Figure 3.1 CORBA architecture.](image) For system integration, object implementation can be used to define interfaces for communicating with the data sources. The Stanford Digital Library Project is aimed at resolving the issues of heterogeneity of information and services have implemented this approach. Based on CORBA technology, the Information Bus (InfoBus) is the core system of the project that provides uniform access to heterogeneous information sources and services. This project, based at Stanford University, developed a modular Testbed infrastructure known as an information bus (or InfoBus) based on CORBA that enabled the integration of a variety of different digital library functions (Paepke et al., 1996). The InfoBus provides plug-in integration for repositories, information processing services, and user interfaces. It is implemented with CORBA distributed object technology. Heterogeneous repositories are wrapped with Library Service Proxy (LSP) objects that shield client programs from as much heterogeneity as technically feasible and appropriate from an end-user perspective. Library services (LS) built into the InfoBus provide the necessary support functions, such as query translation, metadata facilities, and rights management. Documents are modeled as objects. Their instance variables contain document fields, such as author or title. They are materialized from the underlying collections, which may or may not be object-oriented (Paepcke et al., 1998). The architecture of InfoBus is shown in Figure 3.2. The question of compliance is very important in ORB. Even though ORB approach provides abstraction of the implementation of services at the object implementation, the task of data integration from multiple objects is done by the client. In order to do this object implementation the client application should know the metadata of the responses. ORBs developed by different vendors may have significantly different features and capabilities. Thus, developers of the client applications must learn a specification, the way vendors implement the specification, and their features. Also changes to the services provided by the data source require changes to the object application and propagation of the updated stub and skeleton. The mediated approach, discussed next, attempts to overcome these issues and limitations. ### 3.2 Mediated Approach The mediated approach utilizes a component called mediator to perform integration. In this approach, the client sends the request. The integration system accepts the request, determine which set of information sources is capable to answer the request and generate the appropriate query plans for each information source. On obtaining the results from the information sources, the data integration system performs the appropriate translation, filtering and merging of the information and returns the final answer to the user or application (Fahmi et al., 2001). This process is referred to as a mediated approach, since the part that decomposes queries and combines results is often called the mediator. The general architecture of mediated approach has the information sources, the wrappers, the mediators, and the user interface as shown in Figure 3.3. A wrapper is conceptually similar to a mediator, except that it only needs to translate between one native component and one mediator. ![Figure 3.3 Mediated approach architecture.](image) The function of the wrapper is to interact with its corresponding information source, converting mediator queries represented in the common language into queries native to the sources and vice versa. To perform its task, a wrapper must have the knowledge of the underlying source. A wrapper connects the data sources with the mediator. The complexity of the wrappers depends on the amount of cooperation from the source itself. For example, a source can be cooperative by performing many of the processing tasks of answering the wrapper query. At the other extreme, a source may be non-cooperative, in which case, upon receiving an answer to a query from the source, the wrapper has to perform additional processing before sending it to the mediator. The function of the mediator is to accept incoming requests and transform them into the appropriate format. Each request is subdivided into smaller requests and sent to the appropriate source through the wrapper. Upon receiving answers to sub-queries, the mediator combines and integrates these answers to form the complete answer and presents it to the users. To perform its task, the mediator must have the knowledge of the sources and their schema to determine which sources provide what information. The Digital Library Service Integration (DLSI) infrastructure at NJIT provides a systematic approach for integrating digital library collections and services. Users can see a totally integrated environment by using the DLSI. They can use their digital library system just as before. But in addition, they will see additional link anchors, and when they click on one, they will be presented with a list of relevant links. The architecture of the system is composed of Integration Manger which acts as the mediator, wrappers or enginelet, user interface and repositories. Figure 3.4 shows the architecture of DLSI. We will discuss this architecture in detail in the next section. One drawback with the mediated approach is that the mediator component does not have the capability to search for new sources or discover potential sources that should be included in the integration. For this reason, agent technology has been introduced to overcome this limitation. ### 3.3 Agent-Based Approach The approach is based on the idea of a software agent. An agent represents an element of the digital library (collection or service), and has the following special properties (Birmingham, 1995). - **Autonomy**: the agent represents both the capabilities (ability to compute something) and the preferences over how that capability is used. Thus, agents have the ability to reason about how they use their resources. In other words, an agent does not have to fulfill every request for service, only those consistent with its preferences. A traditional computer program does not have this reasoning ability. - **Negotiation**: since the agents are autonomous, they must negotiate with other agents to gain access to other resources or capabilities. The process of negotiation can be, but is not required to be, stateful and will often consist of a "conversation sequence", where multiple messages are exchanged according to some prescribed protocol, which itself can be negotiated. An agent is a component having decision making capabilities for performing different tasks. Agents can interact with the end users, with other related agents, and with the information sources. There are in general three types of agents which are used in the Agent-based approach. User agents, Provider agents (Back-end) and brokers (mediators). Architecture of agent-based approach is shown in Figure 3.5. Brokers or mediator agents interact with user agents, provider agents and other brokers. There are many types of mediator agents in which each type performs specific intermediate tasks, including accepting user queries, evaluating user profiles if any, locating the appropriate source agents based on user queries, sending queries to appropriate source agents, monitoring the query progress, formatting and integrating responses from source agents, and communicating and working together with other mediator agents to accomplish a task (Wiederhold, 1992). The brokers get the requests from the user agents and then locate the appropriate provider agents and pass the request to them. Brokers communicate with other brokers, monitor the progress, and integrate the responses from the providers to accomplish the request. To locate the appropriate agents, their description and services information is maintained in the repository. So when some service is needed, agents look in the repository. Also agents send their description to each other when ever requested. Upon receiving a response to the query, the original agent needs to update its knowledge base. This way, when it submits the same type of query for processing the next time, it can direct the query to the appropriate agent (Fahmi et al., 2001). User agents get the requests from the users. They forward this request to the brokers along with the user profiles so that brokers can locate the user preferences. User agents also change the requests into proper format which is being used within the system. Provider agents work just like wrappers as mentioned in the mediated approach. ![Figure 3.6 UMDL Architecture.](image) The UMDL is populated by three classes of agents (Birmingham, 1995). • UIAs (User Interface Agents) provide a communication wrapper around a user interface. This wrapper performs two functions. First, it encapsulates user queries in the proper form for the UMDL protocols. Second, it publishes a profile of the user to appropriate agents, which is used by mediator agents to guide the search process. • Mediator agents, of which there are many types, perform a variety of functions: essentially, all tasks that are required to refer a query from a UIA to a collection, monitor the progress of the query, transmit the results of a query, and perform all manner of translation and bookkeeping. Presently, two types of mediators populate the UMDL. Registry agents capture the address and contents of each collection. Query-planning agents receive queries and route them to collections, possibly consulting other sources of information to establish the route. Another special class of mediators currently being developed, called facilitators, mediate negotiation among agents. • CIAs (Collection Interface Agents) provide a communication wrapper for a collection of information. While performing translation tasks similar to those performed by the UIA for a user interface, the CIA also publishes the contents and capabilities of a collection in the conspectus language. 3.4 A Service-Oriented Agent Architecture We propose to implement the agent based approach using web services. A Web service is an abstract notion that must be implemented by a concrete agent. The agent is the concrete piece of software or hardware that sends and receives messages, while the service is the resource characterized by the abstract set of functionality that is provided. To illustrate this distinction, one might implement a particular Web service using one agent one day, and a different agent the next day with the same functionality. Although the agent may have changed, the Web service remains the same. A web service is Web-based application that can dynamically interact with other Web applications using an XML message protocol such as SOAP, XML-RPC or XMLP. Examples of emerging standards for describing, promoting and discovering these services are ebXML, UDDI and WSDL, and Microsoft’s .NET and Sun’s Sun ONE are major implementations of the concept. The goal is to enable one application to find another on the Internet that provides a needed service and to seamlessly exchange data with it. Web services are utilized when you cannot or would not implement the logic yourself. A web service is defined by its messages, which must be self-sufficient referencing information necessary to understand the message. When using HTTP, the service reply is interpreted as responsive to the request sent on the same connection. XML is used for the self-describing interfaces and messages of web services. SOAP is used to define message structure and supports the creation of complex self-contained messages. WSDL allows a service to define its interface that is basically the messages it will accept. UDDI supports design-time and run-time discovery of web services. The document-centric approach abstracts away the system architectures, creating loosely coupled connectedness that withstands changes to the underlying implementations (Burner, 2003). A web service is an encapsulated chunk of behavior that is a self-contained and modular, self-describing using XML standards, programmatically and dynamically accessible over networks using standardized mechanisms such as SOAP, and capable of being dynamically composed with other Web services. By making its legacy data available via XML-based Web services, a business can greatly extends its reach to customers. The network economy is driving the evolution of e-business from rigid to flexible application design, from static to dynamic interaction between partners and from technology integration to business integration (Smith, 2001). Although web services could be used in the agent-based approach to serve the purpose of integration, but the developer of the client applications has to use it manually, first searching the service and then finding the communication protocols. Developers of these services design registries like UDDI to be searched by the developers of the client systems. In order to overcome this manual process, a new approach has been proposed in this thesis to accomplish the task of integration in digital libraries. CHAPTER 4 DIGITAL LIBRARY SERVICE INTEGRATION AT NJIT Digital Library Service Integration (DLSI) project at New Jersey Institute of Technology is aimed at forming the core of vibrant virtual educational communities by supporting a broad range of community support services, beyond what most digital library researchers currently are developing. The DLSI infrastructure will provide the first step towards this vision. The middleware of DLSI is based on the mediated approach as described in this section. 4.1 DLSI Overview The purpose of the Digital Library Service Integration project (DLSI) is to automatically generate links for digital library collections to related collections and services. Collections are libraries of computerized documents, which can include photographs, teaching modules, in addition to traditional types of documents. Services include searching, providing annotations and peer review. DLSI supplements collections by linking them automatically to relevant services and related collections. DLSI supplements services by automatically giving relevant objects in collections (and other services) direct access to these services. Users see a totally integrated environment, using their digital library system just as before. However, they will see additional link anchors, and when clicking on one, DLSI will present a list of supplemental links. DLSI will filter and rank order this set of generated links to user preferences and tasks”. The DLSI infrastructure provides a systematic approach for integrating digital library collections and services. Digital libraries will be able to share relevant services within a seamless, integrated interface. Services and collections generally require minimal or no changes to plug into the DLSI infrastructure. 4.2 DLSI Architecture DLSI architecture is based on the mediated approach. The DLSI infrastructure consists of four levels: an independent user interface, the Integration Manager, collection and service wrappers, and independent collections and services. The DLSI architecture is shown in the Figure 4.1. Figure 4.1 DLSI architecture showing wrappers, collections and integration manager. 4.2.1 Wrappers A wrapper or enginelet must be developed for a collection or service to plug into the DLSI infrastructure. The wrapper's main task is to parse the display screens that appear on the user's Web browser to identify the "elements of interest" that DLSI will make into link anchors. First, wrappers will parse the display based on an understanding of the structure of its content. Second, DLSI will parse the display content using lexical analysis to identify additional elements of interest. If a service can operate on an element, DLSI will generate a link anchor over the element. Among the links generated for that anchor will be a link leading directly to that service's feature. Relationship rules specify which links DLSI will generate when the user clicks on a link anchor. The NSSDC enginelet is the wrapper for National Space Science Data Center online system. This wrapper communicate with the integration engine which serves as the mediator as discussed in the mediated approach. The NSSDC enginelet is responsible for: 1. Intercepting the users search request to ensure that the results pass through the Metainformation Engine(ME). 2. Parsing the result screen and marking up elements of interest. 3. Dynamically generating links and commands associated with those links for all elements of interest. The wrapper developer must focus on providing the parsing routines and mapping rules. These will not change as long as the application does not change. The routines and rules will apply to all instances of the user's screen (Bhaumik, 2003). 4.2.2 Collection and Services Services and collections generally will require minimal or no changes to plug into the DLSI infrastructure. To integrate a collection or service with DLSI, an analyst must write a wrapper, initiate communications between the collection or service and the wrapper, and define relationship rules. The DLSI Integration Manager module manages relationship rules. Note that collections and services will continue to function as before. DLSI will supplement them for users who access them through DLSI's framework. All other users will use the services directly as before, and not see any of DLSI’s supplemental features. 4.2.3 Integration Manager In the DLSI architecture the Integration manager and wrappers together constitutes the Metainformation Engine (ME). The Metainformation Engine (ME) is a loosely coupled system, where various engine components communicate with each other via messages that conform to a well-defined standardized internal protocol. This approach allows new engine components to be developed and added without affecting existing engine components and functionality. The ME’s goal is to supplement the output of most computer applications with link anchors and lists of links for each anchor, all with minimal or no changes to them (Bhaumik, 2003). The ME v 1.0 has three primary components: - The Engine Desktop translates the ME’s internal messages, from the standard internal XML format to a format that can be displayed to a user via a web browser and vice versa. - The ME Broker facilitates the communication between the Engine modules and works as the router for all the internal messages. - The Mapping Rules Engine maps the data and relationships to hyperlinks at run-time. It maps the element instances in the application’s output to the global element types (classes), and finds the links for them. Once the links are produced they are sent through to the engine desktop to be displayed in an appropriate interface to the user. Message flow through the Metainformation engine illustrated below in Figure 4.2. Figure 4.2 Message flow in the ME The following events occur in generating an interface to display to the user (Bhaumik, 2003). - When a user follows a link to execute an engine command, the user's browser issues an HTTP request. - The Engine Desktop generates a Virtual Document modeling the user's request. Virtual Document is the communication protocol among the various engine components. - The MEB (Metainformation Engine Broker) reads the source of the document (i.e., Engine Desktop) and the destination (the enginelet that will execute the command) and looks up the traversal path for that message through the Traversal Path Manager (TPM). MEB manages the communication between different components. The document is then routed through all intermediate enginelets in the order that they are listed in the traversal path. TPM. determines the intermediate enginelets that must process the document before reaching to final enginelet. - The intermediate enginelets create/edit new Frames (and/or FrameGroups) or process the Virtual Document in some manner. - After all enginelets in the traversal path have processed the message the message is sent to the destination enginelet - the MAW(Metainformation Application Wrappers). MAW is the component which communicates with the underlying application to identify the elements of interest. The MAW executes the command by communicating with the application via its native API. It then marks up the elements of interest in the application’s output and adds the output document to a Frame and FrameGroup. - This Virtual Document is then sent back to the MEB. The MEB again looks up the traversal path for this document, using the MAW as the source and the Desktop as the destination. The Virtual Document is again processed by all intermediate enginelets. - After all enginelets in the traversal path have processed the message, the MEB passes the message on to the Mapping Rules Engine. The document contains the marked up “elements of interest” that the MAW located. - The MEMRE(ME Mapping Rules Engine) looks up the mapping rules for “each element of interest” and generates the list of links. These list of links are added as Relationship objects in the Metainformation nodes of the Frames being manipulated. - The Virtual Document is returned to the MEB, which then returns it back to its source desktop. - The desktop uses the specified lens to translate each Frame and display embedded inside a FrameGroup for the user. ### 4.3 Implementation Details XML (eXtensible Markup Language) and XSL (eXtensible Style Sheet Language) is a powerful technology that is currently being used to develop the system. XML/XSL is the functional backbone of the system’s internal structure. The objects passed, as well as those that are regenerated, are delivered in the XML format. JAVA is used in developing Integration Manager. It is used to process the XML objects that are passed between system modules. Using the JAVA platform, the XML documents are parsed for critical information. The current JAVA DLSI classes are used to gather the set of relational mapping rules that will be required to generate the newly implemented information links. JAVA is then again used to regenerate or create the resulting XML documents, which are then passed onto an XSLT document for transformation. 4.4 Advantages of DLSI Collections and services will gain several benefits from integrating with DLSI: - Users will have direct access to related collections and services, which in effect, enlarges the feature set of a given collection or service; - Collections and services will gain much wider use, because DLSI linking will lead other users to them; - Users will become aware of a service or collection from seeing its links included in DLSI's list of links when using other collections and services; - DLSI will give the user direct, context-sensitive access to the features that a particular service or collection provides. 4.5 Disadvantages of DLSI Disadvantage of the DLSI is that the component does not have the capability to search for new sources or discover potential sources that should be included in the integration. In order to integrate, developer must write a wrapper and the code to initiate the communication between the service and the wrapper. Also this wrapper or enginelet has to be registered with ME Broker. To avoid all this manual processing we are proposing a new approach for the middleware to achieve seamless integration. This approach proposes the architecture to integrate the information on the web automatically (machine processable). Detailed architecture is explained in the next chapter. CHAPTER 5 A NEW APPROACH TO DIGITAL LIBRARY INTEGRATION This paper proposes a new approach to implement the current digital library service integration project to integrate NSSDC (National Space Science Data Center), AskNSDL and other repositories. It also introduces a new service to be used for the integration of a library database, ProQuest with any client application over the web. This approach will enable DLSI on the Semantic Web and will allow the use of metadata by the client applications and agents through the Semantic Web. The Semantic Web is a foresight for the future where information is given explicit meaning, which will help machines to automatically process and integrate information available on the Web. There are various reasons that we propose semantic web services to be used as middleware to implement the integration in our new approach. By using the web services, DLSI will be available to client applications through a web service interface. Web services are lightweight components and by their use application developers can avoid the object models and programming language requirements. Moreover, ongoing Web services standardization efforts free them from the proprietary stigma of enterprise application integration systems (Vinoski, 2003). Web services are the evolutionary step in object-oriented programming for business-to-business and e-commerce applications. Tasks like real time auctions to get prices and performing multiple tasks like making traveling plan are not easily possible in Common Object Request Broker Architecture and Distributed Component Object Model and electronic data interchange (EDI) was too expensive and specialized to perform such kind of tasks. Another reason for using this approach is that integration is the heart of web services (Fontana, 2001). Semantic web enabled web services provide most promising way to provide application to application integration. Ontologies are used to develop semantic web and are significant for applications that need to search and merge information from different resources. Ontologies provide automated reasoning ability which in turn is helpful in advanced services to intelligent applications such as semantic search and retrieval, software agents and intelligent databases. Ontologies are developed in a logic based language which helps to provide detailed, precise, steady, sound, and meaningful differences among the classes, properties, and relations. Ontologies will provide many benefits for the digital library integration project. This new approach will allow more intelligent syndication. For example on the ProQuest website a simple list of subject areas may not provide the users sufficient ability to search for the contents they want. Ontologies are used to describe content and axioms that define terms. By using these definitions other facts which are necessarily true could be inferred. These inferences can allow users to obtain search results, which are impossible to obtain through conventional retrieval systems. But this approach depends on digital resource providers annotating their pages with the ontologies. Ontologies could also be used to provide semantic definitions of multimedia collections. Multimedia ontologies can be media specific or content specific. Media specific ontologies provide taxonomies of the media types and to explain properties for example scene breaks and length of clips. Content specific ontologies describe the subject of media like participants. In the retrieval process this information will be used to get the semantics from the multimedia collection which is not possible in current integration project. Another benefit of this approach is that the semantic web can provide agents with the capability to understand and integrate diverse information resources (Mikhalenko, 2003). Intelligent agents take instructions from users for example “make a complete traveling plan in January” and search the internet to produce optimum results. When completing the task the information may come from various sources such as service specific sites, reservation sites etc. By using the web services, client applications will seamlessly interoperate with them without concerning about their location. Semantic web enable web services will make the integration process much easier and automated as these services will be machine searchable and processable. In this way this new approach will be able to overcome the short comings of other approaches. In ORB approach question of compliance is a big issue the client must know how the vendor has implemented the architecture. Also in mediated approach, the mediator component does not have the capability to search for the new sources. In the DLSI architecture every new wrapper must be developed and registered when client applications want to integrate through DLSI. Also the generated list of links is very limited and non inferable. In order to add links for more digital resources, wrappers must be modified. With this new approach all the integration will be machine processable and no extra coding will be required for new applications to be integrated. Once the digital resource pages will be semantic web enabled and web services will be developed, any application can integrate itself automatically. The most difficult and important part in this approach is to annotate the contents of digital resources into web ontology language. Once the content is converted any client application can access it using the proposed semantic web enabled web services. These web services will provide the mechanism to be used automatically by other machines. In regular web services the client application developers must know how to communicate with the services through their interface but with the semantic web enabled web services applications can directly communicate with them without the involvement of any human. In this way once the setup is complete, any application over the internet can use this mechanism to integrate itself with the digital resources. The only limitation in this approach is that the conversion of digital resources into web ontology language is very time consuming and slow process. But once the large amount of information will be converted into ontologies, this approach will provide the most effective and efficient way of digital integration. Basic architecture of the new approach is similar to that of Agent-Based approach implemented through web services. Although web services serve the purpose of integration, but this is a manual process as registries like UDDI are designed to be searched by the developers of the client systems. In contrast, this new approach uses semantic relations to find services described using Semantic Web languages. This approach is conceptually based on the Semantic Web and Ontologies. Semantic web concept is still in its early stages but soon it will dominate the current technology. This thesis proposes the architecture for two integration projects. DLSI will be implemented as semantic web services using ontology languages. Ontologies are significant for applications that need to search or merge information from different resources. In case of DLSI web service, the repositories like NSSDC and AskNSDL will communicate with the digital resources through this service. Once these repositories will pass the pages to DLSI web service, links will be created which connects to the available digital resources. In first phase the NJIT library contents will be written in the web ontology language like DAML-S. So for example whenever a user will be looking for extra information from NSSDC page, ontologies will be employed to infer and get the related information. The ProQuest web service will enable the programmatical access to the full text document discovery from the collection. All the contents will be converted to web ontology language. So in result any web application can use this web service to integrate the information on their pages with the information in the ProQuest digital resources. Detailed proposed architecture has been discussed latter in this chapter. 5.1 Semantic Web Overview 5.1.1 Semantic Web The Semantic Web is a network of information linked up in such a way as that it could be easily accessible globally. This information is machine useable and associated with more meaning. The Semantic Web is an extension of the current web in which information is given well-defined meaning, better enabling computers and people to work in cooperation (Berners-Lee et al., 2001). The Semantic Web provides a common framework that allows data to be shared and reused across application, enterprise, and community boundaries. Semantic web could be seen as a huge engineering solution. Semantic Web vision of a machine-readable web has possibilities for application in most web technology. Today's web was designed for human use. The current Web supports documents, pages of text and figures designed for humans. But there is an increased automation in terms of direct operation between machines, mostly in B2B, B2C and information services applications. Currently this is done by APIs which needs hand coded information retrieval code on the client side. Fundamental to having computer programs or agents implement reliable, large-scale interoperation of Web services is the need to make such services computer interpretable, to create a Semantic Web of services whose properties, capabilities, interfaces, and effects are encoded in an unambiguous, machine-understandable form (McIlraith et al., 2001). The Semantic web adds support for databases, vast collections of information organized to be processed by machines. Machines can parse HTML but cannot reliably infer any semantic information from this attempt. The Semantic Web aims at bringing meaningful content out of Web pages. Machine usable content means that the machine knows what to do with information on the Web. 5.1.2 Resource Description Framework W3C has hailed RDF (Resource Description Framework) as a Semantic Web language to implement the concept of Semantic web. The information representation on the semantic web is done by Extensible Markup Language (XML) and the Resource Description Framework (RDF). XML allows users to add structures to their documents, but the developer should know these structures, in order for programs to use these. XML does not capture information about what the structures mean. On the other hand RDF enables users to use Metadata to describe data on the Web. RDF gives you a way to make statements that are machine-processable. Machines can infer relationships between resources on the basis of metadata. The Semantic Web will develop on XML's ability to define customized schemes and RDF's flexible approach to represent data. 5.1.3 Uniform Resource Identifier Identifiers are used to identify items on the web. As we use uniform system of identifiers, and because each item identified is considered a "resource," we call these identifiers "Uniform Resource Identifiers" or URIs. RDF statements are composed of URIs. All the information on the web and in the databases will have a URI and can be accessed through RDF. 5.1.4 Ontologies The Semantic Web requires a language which can formally describe the semantics of classes/sub-classes and properties used in web documents. To perform useful reasoning tasks on these documents, the language must go beyond the basic semantics of RDF Schema. Web Ontology language is used for this purpose. In order for the semantic web to succeed, programs must be able to compare or combine information across different systems. A well-known problem with the web of today is finding the many web services currently available on line. Ontologies are used for this purpose. Ontologies are collection of information which describes common meanings and relationships between resources on the Web. Ontologies include machine usable definitions of basic concepts and the relationships among them. One of the most powerful uses of the web Ontologies is in the area of web services. The Semantic Web needs ontologies with a structure to provide description about things in the different domains, relationships among them and attributes of those things. Ontologies are very important for digital library applications that want to search across or merge information from diverse communities. The standard W3C ontology language is OWL, which stands for Web Ontology Language. The RdfSchema is one such language which provides a means for formalizing ontologies. RdfSchema extends the Resource Description Framework model by enabling a collection of resources to be described according to a simple class hierarchy. However, RdfSchema is a simple ontology language and in order to achieve interoperation between autonomously developed and managed schemas, richer semantic language is required. A DAML Ontology (DAML-O) is a document that describes a vocabulary of terms for communication between human and automated agents. Ontologies can be used in an integration task to describe the semantics of the information sources and to make the content explicit. With respect to the integration of data sources, they can be used for the identification and association of semantically corresponding information concepts (Wache et al., 2001). 5.1.5 Ontologies and Services Web ontologies most useful application is in the area of web services. Semantic Web Services are used to implement the concept of semantic web. In many B2B and E-Commerce applications the web services utilize APIs to locate and extract content from the pages. But if the page changes then the web service must be rewritten. In addition, all programs that wish to utilize it must understand the interface description of web services. Also problem with the web of today is the difficulty in finding the many web services currently available. What is needed is semantic web service whose properties, capabilities, interfaces, and effects are encoded in an unambiguous machine-readable form (McHraith et al, 2001). The Semantic Web is an extension of the current Web in which information is given well-defined meaning, better enabling computers and people to work in cooperation. It is the idea of having data on the Web defined and linked in a way that it can be used for more effective discovery, automation, integration, and reuse across various applications. The Web can reach its full potential if it becomes a place where data can be shared and processed by automated tools as well as by people (Miller, 2004). Any world wide web application could be converted to web service by providing an Application Programming Interface (API) to that service, an access protocol such as SOAP and a layer describing the service such as WSDL. The transition from a Web-Service to a Semantic Web Service requires expressing the processes that comprise that Web-Service using the Ontology Web Language for Services and any supporting ontology encoded using the Ontology Web Language (Bechhofer et al., 2004). To implement Semantic Web services, a markup language must be descriptive enough that a computer can automatically determine its meaning. That language must perform the following tasks. - **Discovery**: A software must first be able to automatically discover, an appropriate Web service for the task in hand. A Semantic Web service describes its properties and capabilities so that software can automatically determine its purpose. - **Invocation**: Software must be able automatically to determine how to invoke or execute the service. A Semantic Web service provides a descriptive list of what a requester needs to do to be able to execute and fulfill the service. This includes defining the inputs and outputs of the service. - **Composition**: Software must be able to select and combine a number of Web services to complete the task in hand. The services have to interoperate with each other seamlessly so that the integrated results provide the solution. Ontologies should be used to create the services in any ontological language. Client applications can use the hierarchy to find matches via the class/subclass properties or other semantic links. For example, someone looking for any specific information about the planet Mars might find NSSDC (collects information about planets) even if there were no exact match for that specific information about Mars. This is possible due to the expressiveness of web ontology languages like DAML to develop semantic web enabled web services. DAML is used to describe the structure in terms of classes and properties and this structure is then used for inference and reasoning. Also by using description logic and other inferential ways user can find information that was not explicit. We can also include machine readable description of a service and some explicit description of the consequences of using the service. In this way we can integrate ontologies and agents. 5.1.6 Ontologies and Agents The real power of the Semantic Web will be realized when independent computer programs called agents are created that collect and reason over Web content from varied sources, exchanging data and working cooperatively with other agents. The exchange of proofs is an important aspect of agents functioning, and agents will be able to convert their internal reasoning into a common representation language (such as RdfSchema) so that other agents can check their reasoning. Ontologies allow explicit organization of knowledge in agent-based applications, and unambiguous description of characteristics and properties of agents (Zini et al., 1999). 5.2 Ontologies Based Approach Standard Web Service technology provides limited support in automated service recognition and combination, service comparison, and automated negotiation. In digital libraries there is a need for automatic cooperation between available services. Any system interaction with another application needs automatic discovery and selection of the optimal Web Services. This thesis proposes a new architecture for the middleware implementation. This new architecture, named Ontologies Based Approach, is primarily based on Web Services and Semantic Web. By using web services the service interface will be published on the web using XML and will be invoked by the client applications using HTTP and SOAP. Through semantic web will provide the web published and accessible semantic description through dynamically linked and shared ontologies. Interoperability is a key application of Ontologies and many ontology based approaches has been developed for information integration in order to achieve interoperability (Uschold et al., 1996). In order to design a self-regulating Web Service Ontology, it is necessary to understand how it will automatically work. Designing a Semantic Web Service requires detailed analysis that exposes and eliminates semantic logic conflicts and indeterminacies. 5.2.1 Markup Language for Ontologies Management of resources in Semantic Web is impossible without use of ontologies, which can be considered as high-level metadata about semantics of Web resources (Fensel et al., 2002). DAML-S is an upper ontology markup language for describing properties and capabilities of Web Services. DAML-S provides an unambiguous, computer interpretable markup language, which enables automation of service use by agents and reasoning about service properties and capabilities (Ankolenkar et al., 2001). The basic requirements to service description language in (Trastour et al., 2001), formulated as: - High degree of flexibility and expressiveness; - Ability to express semi-structured data - Support for types and categorization; - Ability to express constraints. Considering these requirements and comparing proposed by Semantic Web ontological descriptions (e.g. DAML-S) with other layers as shown in Figure 5.1. In DAML-S: RDF layer provides the flexibility, expressiveness and semi-structure data, RdfSchema layer provides the support for the types, whereas DAML layer meets the constraint requirement. 5.2.2 Digital Library Web Services and Architecture We will use DAML-S to develop the web services. Ontologies will be used to facilitate information retrieval services to the clients. When users will follow a hyperlink generated by our web service or search for some information, these ontologies will be used to direct the users to related information providers domains over the internet. When the client applications look for some information through agent brokers, they will use the inference and reasoning capabilities of ontologies and direct to related digital documents. Agent brokers are used to carry out requests in an open market way from the distributed collection of digital documents. The DAML-S ontology is conceptually divided into three subcategories. Profile ontology describes what a service does and provides the way for its discovery. Process specifies the working of the service including the internal process and dataflow. Grounding provides the information about the implementation of the service. Accordingly, each DAML-S description has three major parts. The two specific Semantic based web services that are being proposed are as follows. 1. **DLSI web service**: This web service will provide all the services that are currently available in the DLSI architecture. Web service will produce hyperlinks in the web pages for related information. Requesting application will provide the document to the web service. DLSI web service will process the document and will generate the augmented links and send it back to the requesting application. DLSI web service will be implemented using DAML-S. In the profile part of the ontology, information about the service provider, inputs(documents types), outputs(augmented documents) and other preconditions will be explained. The process part of the ontology will explain the process model and internal process and dataflows. The documents processing implementation(parsing and augmentation) will be in this part of the ontology. Finally the grounding will explain the operation level details. It will provide the details about the message exchange formats and network protocol and hence will enable the automatic invocation of the service by other machines. In this way this web service will be machine processable. In the first phase NJIT library digital resources will be converted to semantic web enabled and hyperlinks will look for the related information in these resources. Latter on more digital resources will be added for this service. Ontologies will allow reasoning for the search of related information. 2. **ProQuest web service:** This paper also proposes a web service to allow the integration of ProQuest services in the semantic web. This web service will allow other web based applications to programmatically access the ProQuest services in a same way as human user can access through ProQuest web interface. ProQuest web resources will be annotated as web ontology language which will make it semantic web enabled. This can be taken advantage by the brokers on the semantic web. ProQuest webservice provides the facility to lookup the articles from the ProQuest data library and show it in an integrated way. The requesting applications will invoke the service by sending a string of text and in return will get the related articles. The string could be sent by following the hyperlinks or by querying the specific text from the client applications. ProQuest webservice will get the string and in return will provide the construct. ProQuest webservice will be developed using DAML-S. The layered description will be used including profile, process and grounding. Requesting applications will inspect the profile to see if the service has the desired capability and how to interact. Process Model will provide detailed information about how the service works. If the requesting application sees that the service conforms to the requirements, the grounding will specify the implementation details needed for executing the service. The service will be automatically invoked by applications or agents. Similar to agent based approach, in ontologies based approach different tasks will be accomplished by Semantic Web agents (service providers, requesters, and middle agents). Our architecture will assume the following capabilities of agents: - Semantic web agents should be able to interpret published ontologies and can send and understand messages with content represented as published ontologies. - Requester agents, could be web services or clients, must be able to send requests to servers in terms of their published and semantic interfaces. - Service provider agents must publish their semantic descriptions about the interaction procedure and capabilities. Through this information requester agents will interact with these services. Ontologies will be used for these descriptions. DLSI web service and ProQuest web service as discussed earlier will serve as service provider agents and will be used for three purposes. - To describe collection content and inference rules to support powerful user queries. In case of DLSI web service these queries means to find the related contents in the digital resources and applying inference rules. In ProQuest web service the articles will be searched using inference rules from the ProQuest database. - To enable agent brokers to use the service. - For the Copy right material, licensing mechanism will be implemented. The two web services must allow the three basic tasks of automatic discovery, automatic composition and automatic invocation to make the services semantic web enabled. The functional requirements of these tasks will be met using ontologies. The architecture is shown in the Figure 5.3. 1. **Automatic Discovery:** Web services present the service profile. Service profile contains the service provider information, and also specifies the inputs, outputs and preconditions of the service. This information is used by the client applications and agents to use the service automatically, without manually finding the service. Automatic discovery is the process by which a client, interacting with other clients or middle agents, identifies candidate services to achieve the client’s objectives. Any web service must provide this mechanism in order to become semantic web enabled. The DLSI web service and ProQuest web service profiles will provide all the necessary information and could be discovered automatically by the client applications who wants to integrate their applications using these services. 2. **Automatic Composition:** Service model is described by the services and is used for the automatic composition or execution of the web service. It describes how the subsystems in the service work. The task is accomplished by the automatic selection, composition, and interoperation of Web services to perform some complex task provided a high level description of an objective. Automatic composition comes into picture when multiple services are utilized to achieve an objective. Suppose someone wants to make all the travel arrangements to a conference. Conference registration, airline ticket, hotel reservation and other related activities will be carried automatically rather than going to the individual websites. 3. **Automatic Invocation:** Service grounding will also be supported by the services. It is used for automatic invocation or interoperation. Automatic invocation is used by the computer program or agents, given only a declarative description of that service. This is used in the semantic web enabled web services as opposed to the regular web services where agents are pre-programmed to be able to call that particular service. The agent will be able to understand what input is necessary to invoke the service and what will be the output from the service. For example, a user can request the purchase of an article from a specific journal using ProQuest web service, from any other website located by searching and then selected by that user. 5.3 Implementation Details Web Services Description Language (WSDL) provides an encoding and protocol independent mechanism to describe the means of interacting with offered services. WSDL is an XML-formatted language used to describe a Web service's capabilities as collections of communication endpoints capable of exchanging messages. WSDL is an integral part of UDDI, an XML-based worldwide business registry. WSDL is the language that UDDI uses. WSDL separates the abstract definition of service and messages from their concrete binding to a network port and message format. The current WSDL specification describes concrete bindings for SOAP, HTTP, and MIME. In DAML-S Service Profile is used for the description of a Web service which tells the service locators about what the service does. A Service Model tells about how the service works, and Grounding tells the requestors how to access the service. The Service Profile and Service Model are abstract specifications as they do not specify the details about message formats, protocols, and network addresses by which a Web service is instantiated. On the other hand the Service Grounding provides these more concrete details. The Web Services Description Language (WSDL) provides a well defined means of specify these kinds of details. Therefore, in the proposed ontology based approach, WSDL will be used to ground DAML-S services. DAML-S is an XML-based language, and its process declarations and input/output types fit with WSDL. Therefore it is much easier to extend WSDL bindings to use with DAML-S, like the SOAP binding. For this new approach DAML-S specified arbitrary atomic process can be given a grounding using WSDL and SOAP, and HTTP could be used as transport mechanism. In order for Grounding DAML-S with WSDL and SOAP the construction of a WSDL service description will be used with all the parts (message, operation, port type, constructs, and binding). This new approach as discussed in this section will serve a middleware. World Wide Web users will access the web applications, these applications will communicate with the semantic web agents to accomplish the tasks. Semantic web enabled web services will serve as a middleware to do the seamless integration between the applications. CHAPTER 6 CONCLUSION The goal of this thesis is to assess the working of currently employed middleware used for digital library integration, and propose a new architecture which overcomes the limitations of earlier approaches. This new ontologies-based approach utilizes the semantic web-enabled web services to implement the middleware for digital library integration. Paper provides the details to convert the mediated based DLSI architecture at NJIT into ontologies based DLSI. It also envisions a new service to do the seamless integration of applications with ProQuest data repositories. This new approach will make it easier for machines to automatically process and integrate information available on the web. In this way the new approach provides a more natural and flexible way of integrating the applications. The Semantic web is an opportunity for web services to reflect their organization and show their value-added. We believe that the approach proposed here for migrating the DLSI into semantic service could be used as a model for other integration projects. The main challenge in using this approach is converting the pages to semantic web enabled. There are over one million pages over the web and are potential resources for any digital library. In order for successful and effective digital libraries more and more contents should be written in the web ontology languages so that the full benefit of semantic web could be achieved. We encourage the further research to use these guidelines to develop and implement this system. This will enhance the capabilities and functionalities of currently used DLSI project and will be helpful in overcoming the shortcomings of the current middleware approach. REFERENCES
{"Source-Url": "http://archives.njit.edu/vol01/etd/2000s/2005/njit-etd2005-008/njit-etd2005-008.pdf", "len_cl100k_base": 14869, "olmocr-version": "0.1.47", "pdf-total-pages": 63, "total-fallback-pages": 0, "total-input-tokens": 100672, "total-output-tokens": 18888, "length": "2e13", "weborganizer": {"__label__adult": 0.0004630088806152344, "__label__art_design": 0.0014543533325195312, "__label__crime_law": 0.0006546974182128906, "__label__education_jobs": 0.01898193359375, "__label__entertainment": 0.00029397010803222656, "__label__fashion_beauty": 0.0002923011779785156, "__label__finance_business": 0.0010023117065429688, "__label__food_dining": 0.0004549026489257813, "__label__games": 0.0008349418640136719, "__label__hardware": 0.0009713172912597656, "__label__health": 0.000713348388671875, "__label__history": 0.0008816719055175781, "__label__home_hobbies": 0.00015103816986083984, "__label__industrial": 0.000537872314453125, "__label__literature": 0.0016088485717773438, "__label__politics": 0.0004818439483642578, "__label__religion": 0.000667572021484375, "__label__science_tech": 0.1837158203125, "__label__social_life": 0.000316619873046875, "__label__software": 0.043365478515625, "__label__software_dev": 0.74072265625, "__label__sports_fitness": 0.00023031234741210935, "__label__transportation": 0.0007419586181640625, "__label__travel": 0.0003361701965332031}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 82986, 0.03042]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 82986, 0.32354]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 82986, 0.89317]], "google_gemma-3-12b-it_contains_pii": [[0, 1094, false], [1094, 1322, null], [1322, 2442, null], [2442, 2736, null], [2736, 2736, null], [2736, 3064, null], [3064, 3490, null], [3490, 3536, null], [3536, 4227, null], [4227, 5680, null], [5680, 6291, null], [6291, 7664, null], [7664, 9163, null], [9163, 11134, null], [11134, 12313, null], [12313, 13915, null], [13915, 15647, null], [15647, 16896, null], [16896, 18488, null], [18488, 19746, null], [19746, 21013, null], [21013, 22344, null], [22344, 23364, null], [23364, 24729, null], [24729, 26168, null], [26168, 27245, null], [27245, 28427, null], [28427, 29629, null], [29629, 31876, null], [31876, 33712, null], [33712, 34049, null], [34049, 35601, null], [35601, 36589, null], [36589, 38337, null], [38337, 39871, null], [39871, 40709, null], [40709, 42707, null], [42707, 44252, null], [44252, 44545, null], [44545, 46258, null], [46258, 48112, null], [48112, 49905, null], [49905, 51831, null], [51831, 53432, null], [53432, 55217, null], [55217, 56854, null], [56854, 58542, null], [58542, 60375, null], [60375, 62243, null], [62243, 63920, null], [63920, 64703, null], [64703, 66920, null], [66920, 69591, null], [69591, 70458, null], [70458, 72746, null], [72746, 74538, null], [74538, 75016, null], [75016, 76637, null], [76637, 76742, null], [76742, 78731, null], [78731, 80611, null], [80611, 82657, null], [82657, 82986, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1094, false], [1094, 1322, null], [1322, 2442, null], [2442, 2736, null], [2736, 2736, null], [2736, 3064, null], [3064, 3490, null], [3490, 3536, null], [3536, 4227, null], [4227, 5680, null], [5680, 6291, null], [6291, 7664, null], [7664, 9163, null], [9163, 11134, null], [11134, 12313, null], [12313, 13915, null], [13915, 15647, null], [15647, 16896, null], [16896, 18488, null], [18488, 19746, null], [19746, 21013, null], [21013, 22344, null], [22344, 23364, null], [23364, 24729, null], [24729, 26168, null], [26168, 27245, null], [27245, 28427, null], [28427, 29629, null], [29629, 31876, null], [31876, 33712, null], [33712, 34049, null], [34049, 35601, null], [35601, 36589, null], [36589, 38337, null], [38337, 39871, null], [39871, 40709, null], [40709, 42707, null], [42707, 44252, null], [44252, 44545, null], [44545, 46258, null], [46258, 48112, null], [48112, 49905, null], [49905, 51831, null], [51831, 53432, null], [53432, 55217, null], [55217, 56854, null], [56854, 58542, null], [58542, 60375, null], [60375, 62243, null], [62243, 63920, null], [63920, 64703, null], [64703, 66920, null], [66920, 69591, null], [69591, 70458, null], [70458, 72746, null], [72746, 74538, null], [74538, 75016, null], [75016, 76637, null], [76637, 76742, null], [76742, 78731, null], [78731, 80611, null], [80611, 82657, null], [82657, 82986, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 82986, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 82986, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 82986, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 82986, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 82986, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 82986, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 82986, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 82986, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 82986, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 82986, null]], "pdf_page_numbers": [[0, 1094, 1], [1094, 1322, 2], [1322, 2442, 3], [2442, 2736, 4], [2736, 2736, 5], [2736, 3064, 6], [3064, 3490, 7], [3490, 3536, 8], [3536, 4227, 9], [4227, 5680, 10], [5680, 6291, 11], [6291, 7664, 12], [7664, 9163, 13], [9163, 11134, 14], [11134, 12313, 15], [12313, 13915, 16], [13915, 15647, 17], [15647, 16896, 18], [16896, 18488, 19], [18488, 19746, 20], [19746, 21013, 21], [21013, 22344, 22], [22344, 23364, 23], [23364, 24729, 24], [24729, 26168, 25], [26168, 27245, 26], [27245, 28427, 27], [28427, 29629, 28], [29629, 31876, 29], [31876, 33712, 30], [33712, 34049, 31], [34049, 35601, 32], [35601, 36589, 33], [36589, 38337, 34], [38337, 39871, 35], [39871, 40709, 36], [40709, 42707, 37], [42707, 44252, 38], [44252, 44545, 39], [44545, 46258, 40], [46258, 48112, 41], [48112, 49905, 42], [49905, 51831, 43], [51831, 53432, 44], [53432, 55217, 45], [55217, 56854, 46], [56854, 58542, 47], [58542, 60375, 48], [60375, 62243, 49], [62243, 63920, 50], [63920, 64703, 51], [64703, 66920, 52], [66920, 69591, 53], [69591, 70458, 54], [70458, 72746, 55], [72746, 74538, 56], [74538, 75016, 57], [75016, 76637, 58], [76637, 76742, 59], [76742, 78731, 60], [78731, 80611, 61], [80611, 82657, 62], [82657, 82986, 63]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 82986, 0.14286]]}
olmocr_science_pdfs
2024-11-23
2024-11-23
d2270bf3f83d3c4ec80207852de0bfc4e33b8973
Wearable Device Control Platform Technology for Network Application Development Heejung Kim, Misun Ahn, Seunghyun Hong, SeungGwan Lee, and Sungwon Lee 1 Korea Telecom, 206 Jungja-dong, Bundang-gu, Seongnam-si, Gyeonggi-do 463-711, Republic of Korea 2 Department of Computer Engineering, Kyung Hee University, 1 Seocheon-dong, Giheung-gu, Yongin-si, Gyeonggi-do 446-701, Republic of Korea 3 Humanitas College, Kyung Hee University, 1 Seocheon-dong, Giheung-gu, Yongin-si, Gyeonggi-do 446-701, Republic of Korea Correspondence should be addressed to Sungwon Lee; drsungwon@khu.ac.kr Received 4 August 2015; Revised 24 November 2015; Accepted 6 January 2016 Copyright © 2016 Heejung Kim et al. This is an open access article distributed under the Creative Commons Attribution License, which permits unrestricted use, distribution, and reproduction in any medium, provided the original work is properly cited. Application development platform is the most important environment in IT industry. There are a variety of platforms. Although the native development enables application to optimize, various languages and software development kits need to be acquired according to the device. The coexistence of smart devices and platforms has rendered the native development approach time and cost consuming. Cross-platform development emerged as a response to these issues. These platforms generate applications for multiple devices based on web languages. Nevertheless, development requires additional implementation based on a native language because of the coverage and functions of supported application programming interfaces (APIs). Wearable devices have recently attracted considerable attention. These devices only support Bluetooth-based interdevice communication, thereby making communication and device control impossible beyond a certain range. We propose Network Application Agent (NetApp-Agent) in order to overcome issues. NetApp-Agent based on the Cordova is a wearable device control platform for the development of network applications, controls input/output functions of smartphones and wearable/IoT through the Cordova and Native API, and enables device control and information exchange by external users by offering a self-defined API. We confirmed the efficiency of the proposed platform through experiments and a qualitative assessment of its implementation. 1. Introduction The market for smartphones has experienced explosive growth since the development of Apple’s iPhone and Samsung’s Omnia2 to the extent that smart devices have now become vital to daily life. Furthermore, wearable devices have attracted considerable attention as the next generation of mobile technology that will replace smartphones. The research service BI Intelligence has predicted that the market for wearable devices will grow to approximately $12 billion by 2018 [1]. A “wearable device” refers to a small electronic device that can be worn on the body so that a user can freely use it even when moving. Google Glass, Samsung Galaxy Gear, and Sony SmartWatch belong to this category. Furthermore, even sports equipment companies such as Nike and Adidas have lately begun introducing innovative products and services in the wearable device market [2]. The Internet of Things (IoT) is a recent technology for collecting data and transferring data through sensors and adding a communication function to every object. The market size of IoT was estimated to be $203.1 in 2013 and is expected to reach $1 trillion, with an average annual growth of 21.8%, by 2022 [3]. In December 2013, subscribers of smartphones exceeded 37.5 million in Korea [4]. Along with the popularity of smartphones and wearable devices, the market for mobile applications is steadily growing as well [5]. Cross-Platform Development. Due to the emergence of smartphones and the existence of multiple platforms, developers in the stage of application development have to build platform-specific environments, use multiple programming languages, and learn the relevant supporting application programming interfaces (APIs). These constraints lead to wasted time and effort and increase the cost of application development. In order to solve such problems, mobile programming is in the process of standardization. Cross-platform development frameworks, such as Cordova [6] and Titanium [7], have garnered considerable attention as a solution. The Association for Computing Machinery (ACM), the Institute of Electrical and Electronics Engineers (IEEE), and related organizations are publishing an increasing number of studies on platform research that analyze the characteristics of cross-platform development frameworks. This suggests that application development on a single, unified platform will become possible in the near future [8, 9]. Research Challenges and Contributions. Cross-platform development is an attribute that assists the development of applications using web languages such as HyperText Markup Language 5 (HTML5), Cascading Style Sheets (CSS), and JavaScript. Its greatest benefit is that it provides an application with a single source that is feasible on multiple mobile platforms, which increases development productivity. However, the range of APIs in Cordova and Titanium is not sufficiently wide, especially with regard to supporting wearable devices and IoT devices, since they are still in their developmental stages. Developers are thus inevitably required to learn the native language supported by the platform of the relevant device and initiate follow-up development because cross-platform development alone is insufficient for application development. Furthermore, wearable/IoT devices support Bluetooth technology for communication among them. Bluetooth is a communication technology over short distances, due to which it is impossible to communicate with wearable/IoT devices beyond a limited range [10]. In this regard, we propose a “Network Application Agent” (NetApp-Agent) platform that integrates a development environment for wearable devices and supports Internet Protocol (IP)-based communication. NetApp-Agent is a smart device platform for network application development that allows outside users to control input/output (I/O) functions and exchange data. This is because it is based on the Apache Cordova platform and uses Cordova API and a Native API that enable the I/O function in smartphones and wearable devices as well as the I/O function control of IoT devices by providing a self-defined API. The potential benefits of our proposed platform are as follows. First, it eases application development by supporting integrated development environments that supply essential APIs or facilitate device development. Second, it enables wearable devices that use Bluetooth to communicate with the outside by supporting IP communication based on WebSocket. The outline of the remainder of this paper is as follows. Section 2 examines the benefits and drawbacks of the existing development platforms. In Section 3, we introduce NetApp-Agent, our proposed integrated development platform, together with its structure and features. Section 4 presents the results of our experiments involving NetApp-Agent as well as a qualitative assessment of its implementation. Finally, we offer our conclusions and recommendations for further research in Section 5. 2. Review of Existing Approaches and Issues Approaches to mobile application development can be divided into three major categories: native applications (native apps), web applications (web apps), and hybrid applications (hybrid apps). Native apps involve application development on the platform of each device, whereas web apps utilize HTML, JavaScript, and CSS. Hybrid apps assume the form of native apps, but all or part of its internal configuration is developed in a web app environment [11–13]. In this section, we examine the development of native and hybrid apps together with the features and challenges of a network application development system that provides an IoT development platform and cloud service. 2.1. Native Development Platform. A native development platform involves developing applications on the platform of each device, such as the iPhone, the Android phone, and the Windows Phone, which utilize the machine language code. It ensures optimized application performance. However, it has a few major disadvantages: it builds a different development environment for each platform, and the developer needs to learn the relevant development language and software development kit (SDK). We examine the native development environments for both the Sony and the Pebble SmartWatch, which are representative of wearable devices. 2.1.1. Sony SmartWatch. Sony SmartWatch is based on Android 4.0 operating system, and Java is used as its development language. A developer cannot check his/her developed app on the actual device, but on a computer with a separate emulator. The procedure for developing applications for the Sony SmartWatch is as follows [14]. A development environment must first be constructed. Sony SmartWatch provides the Sony Add-on SDK as an additional installation to the existing Android SDK. Therefore, the Android’s development environment needs to be built in advance for SmartWatch development. The Java Development Kit (JDK) and the integrated development tool Eclipse are installed in order to create the Java Runtime Environment. Following this, the Android Development Tools (ADT) plugin is installed on Eclipse to support the Android system together with the Android SDK. The Android development environment is then constructed [15]. The development environment for the SmartWatch is finally constructed after downloading the Add-on SDK from Sony’s developers’ website and installing it on Eclipse. Furthermore, the system structure and the API supporting the development need to be learned. The system architecture of Sony SmartWatch is shown in Figure 1 and can be divided into three major components: Smart Extension, Host Application, and Accessory. Smart Extension refers to the application to perform in wearable device. Table 1: Smart Extension API of Sony SmartWatch. <table> <thead> <tr> <th>API</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>Registration and</td> <td>Provide API data of SmartWatch/Smart Extension</td> </tr> <tr> <td>Capabilities API</td> <td></td> </tr> <tr> <td>Notification API</td> <td>Notify the event that occurred in smartphone to</td> </tr> <tr> <td>Control API</td> <td>Control the display of device</td> </tr> <tr> <td>Sensor API</td> <td>Transmit sensor data</td> </tr> <tr> <td>Widget API</td> <td>Preview contents</td> </tr> </tbody> </table> This application utilizes the Smart Extension API to communicate with the Host Application of the wearable device. The Host Application is installed in smartphones and connected to the wearable device using Bluetooth technology. The Smart Extension API for the development of Sony SmartWatch must be learned in sequence. Table 1 lists various supporting APIs. The Registration API and the Capabilities API are employed when the Host Application provides data for the API of the SmartWatch or Smart Extension provides its data on the API to the Host Application. The Notification API is used when the Host Application notifies the event occurred in smartphones to device, whereas the Control API enables Smart Extension application to the control display of the device. Control API in particular is crucial to controlling the display or the light-emitting diode (LED) of the device and to processing key events or touching events that require close attention. The Sensor API transmits data from the accelerometer and the illumination sensor of the device to the Smart Extension application. The Widget API affords content preview. First, the application development environment must be constructed. Pebble SDK can be installed on Mac OS X and Linux. We assume the construction of a development environment conducted on Mac OS X. The Pebble SDK is downloaded from the Pebble developers’ website and the Pebble ARM Toolchain is installed after the installation of Xcode Command Line Tools [16], which is a developers’ command line tool. Development environment construction is completed after building in Python library because Pebble SDK is based on Python. Pebble is compatible with smartphones that use Android and iOS platforms. Therefore, the development environment of a smartphone application should be built and an SDK called PebbleKit should then be installed to create an application that is in sync with the smartphone [17]. Second, a development support API must be learned. The Pebble API consists of Pebble Watch App SDK (for SmartWatch applications), PebbleKit Android (for Android), and PebbleKit iOS (for iOS). In order to develop an application that is compatible with smartphones that use Android OS, one needs to learn Watch App SDK and PebbleKit for Android. The scope of the supporting SDK is presented in Table 2. When developing a Pebble application, two issues need careful scrutiny in addition to the construction of the development environment and the examination of the supporting APIs. First, the Pebble SmartWatch does not support Korean characters. Hence, expressions in Korean need to be considered when developing an application that sends text messages or notifications for Social Network Services (SNS) to Pebble devices in Korean. Second, the image format of Pebble is problematic. Pebble uses its own image format, called Pebble Binary Image (PBI), when displaying an image on the screen. PBI represents each pixel using one bit that contains image information in the header file. Thus, a developer must create a tool for image conversion to enable images in Pebble Watch. The relevant Pebble Watch application is then installed on a computer terminal by the way of inputting build and install command. Pebble Watch should be connected to a smartphone through Bluetooth for application installation, following which the computer and the smartphone that have already progressed in development should be connected to the same Wi-Fi network. Therefore, developers should pay particular attention to network configuration when installing the application. 2.1.3. Problems with Native Development Platforms. In the current mobile market, several mobile platforms exist, for example, Android, iOS, and Windows Mobile. Thus, manufacturers produce smartphones on a variety of platforms. The coexistence of different platforms has led developers to establish suitable development environments for each platform when creating applications and learn the relevant development languages, the SDK, and the API. Table 3 shows diverse development environments according to types of wearable device. As shown in the table, a developer needs to learn ten programming languages and seven APIs for an application adaptable to four devices. With the growing trend of wearable devices, more and more devices are expected to be introduced. Moreover, time spent on application development will increase in proportion to the number of devices. To solve these kinds of problems, an integrated development platform is required. 2.2. Cross-Platform Mobile Development Framework. Table 4 shows that the development of mobile applications can be divided into three types: native app, web app, and hybrid app. As shown in Section 2.1, native apps guarantee optimized application performance. However, they have a few constraints given that they require building a different development environment for each platform and that the developer needs to learn the relevant development language and the SDK. Application development in web apps is based on widespread Internet technologies, such as HTML, JavaScript, and CSS. The advantage of web apps is that they can attract and train developers, since learning a development language is relatively easy. On the other hand, difficulty in hardware control, slow speed of applications, and vulnerability on networks are the major weaknesses of web apps. Applications developed by hybrid apps assume the form of native apps, but all or part of their internal configuration is developed in web app. The final form of the application is a binary file, which has the same file extension but is developed using web technologies, such as HTML5, CSS, and JavaScript. Hybrid apps improve development productivity because they can be operated in various mobile platform using a single source. Hardware control is also possible. The appropriate incorporation of two apps’ advantages brings forth a new development strategy. Cross-platform is applied as a development tool for hybrid apps. In this section, we discuss Cordova and Titanium, two typical instances of cross-platform development. 2.2.1. Cordova. Cordova is an open-source framework that enables hybrid application development. It was first developed as "Phone Gap" by Nitobi and was subsequently taken over by Adobe in October 2011. Following the takeover, it reinforced the open-source policy with the development of the Apache license, and then he changed the name of the application to Cordova from version 1.4 onward. Additional functions for Cordova are developed as plug-ins that are shared in open-source communities. Moreover, Cordova supports seven smartphone platforms, Android, BlackBerry, Firefox OS, iOS, Windows Phone, Windows 8, and Tizen, with high product quality that renders it the most competitive among cross-platforms [18, 19]. The structure of Cordova’s applications is shown in Figure 2. The developer creates applications using HTML5, CSS, and JavaScript. The completed codes are then packaged through the Cordova library. The application in packaging is distributed to the device in which web-kit provided browser is equipped. Cordova provides APIs shown in Table 5. The APIs are called by JavaScript, whereas the JavaScript engine exchanges data with the native engine using string type. However, Cordova has a limited range of APIs because of its incomplete platform. With regard to network APIs, it only checks the status of the connection to Wi-Fi or cellular data. APIs related to Bluetooth are not yet available. As a consequence, implementation through the native language is inevitable in order to call particular functions, even though the application is developed using the Cordova platform [6]. 2.2.2. Titanium. Titanium is a cross-platform development framework created by Appcelerator. Unlike Cordova which concentrates on the mobile application development, it is possible to develop desktop applications using Titanium Studio in addition to mobile applications. We focus on cross-platform mobile application development in this paper. Figure 3 shows the mobile application development process using Titanium Studio. Titanium delivers a development tool called Titanium Studio. Therefore, application Table 3: Development environments for each wearable device. <table> <thead> <tr> <th>Types of device</th> <th>Operating system</th> <th>Supporting languages</th> <th>SDK/API</th> </tr> </thead> <tbody> <tr> <td>Google Glass</td> <td>Android 4.0.4</td> <td>Go, Java, .NET, PHP, Python, Ruby</td> <td>Google Mirror API</td> </tr> <tr> <td>Sony SmartWatch</td> <td>Android 4.0</td> <td>Java</td> <td>Sony Add-on SDK/Smart Extension API</td> </tr> <tr> <td>Pebble SmartWatch</td> <td>Pebble OS</td> <td>C, JavaScript (Objective-C/Java)</td> <td>Pebble SDK/PebbleKit</td> </tr> <tr> <td>Samsung Gear</td> <td>Tizen OS</td> <td>Java, HTML, JavaScript</td> <td>Tizen SDK/Samsung Mobile SDK</td> </tr> <tr> <td><strong>Total</strong></td> <td><strong>4</strong></td> <td><strong>10</strong></td> <td><strong>7</strong></td> </tr> </tbody> </table> Nonetheless, the spectrum of the supporting platform is quite narrow because it is difficult to format a JavaScript engine for the substitution of the development language into each platform [7, 20]. Table 6 presents the list of Titanium mobile APIs. Titanium has a limited domain of supporting APIs, like Cordova. From a communication aspect, it only supplies APIs for socket and HTTP client production and communication. The range of the hardware module control is restricted to camera, audio, and video control [21]. 2.3. Internet of Things (IoT) Development Platform. IoT refers to a technology that collects and transfers data by installing sensors and adding network connectivity to every object. To satisfy rising user demand, it generates massive amounts of information through smart sensors installed in smart devices such as smartphones, tablet PCs, and smart TVs. The development of mobile devices of every kind together with built-in sensors has ushered in the age of IoT [22]. Smart devices, such as smart TVs, smartphones, and wearable devices, communicate by forming a network structure in IoT environment. Bluetooth, Wi-Fi, ZigBee [23], and Near Field Communication (NFC) [24] are typical close-range wireless communication technologies used for communication among IoT devices. Bluetooth Smart, widely known as Bluetooth Low Energy (BLE), is particularly widely used. Table 5: Cordova plug-in API. <table> <thead> <tr> <th>API</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>Battery Status</td> <td>Check battery status of device</td> </tr> <tr> <td>Camera</td> <td>Take picture and browse gallery</td> </tr> <tr> <td>Contacts</td> <td>Search contacts and add/edit contacts</td> </tr> <tr> <td>Device</td> <td>Provide information about device</td> </tr> <tr> <td>Device Motion</td> <td>Provide information on accelerometer sensor</td> </tr> <tr> <td>Device Orientation</td> <td>Provide information on compass sensor</td> </tr> <tr> <td>Dialogs</td> <td>Show notification of device</td> </tr> <tr> <td>FileSystem</td> <td>Access file system of device</td> </tr> <tr> <td>File Transfer</td> <td>Receive and transfer file</td> </tr> <tr> <td>Geolocation</td> <td>Provide information on location</td> </tr> <tr> <td>Globalization</td> <td>Provide international expressions</td> </tr> <tr> <td>InAppBrowser</td> <td>Run new application browser</td> </tr> <tr> <td>Media</td> <td>Record and play voice file</td> </tr> <tr> <td>Media Capture</td> <td>Capture media files</td> </tr> <tr> <td>Network Information (Connection)</td> <td>Provide information on network status and connectivity to cellular data and Wi-Fi</td> </tr> <tr> <td>Splashscreen</td> <td>Show/hide start screen of application program</td> </tr> <tr> <td>Vibration</td> <td>Generate vibration on device</td> </tr> <tr> <td>StatusBar</td> <td>Hide/configure status bar background</td> </tr> <tr> <td>Whitelist</td> <td>Whitelist network requests</td> </tr> <tr> <td>Legacy Whitelist</td> <td>Use the old style of whitelist</td> </tr> </tbody> </table> Table 6: Titanium mobile API. <table> <thead> <tr> <th>API</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>App</td> <td>Provide information on application and system event</td> </tr> <tr> <td>Calendar</td> <td>Access native calendar</td> </tr> <tr> <td>Cloud</td> <td>Access ACS (Appcelerator Cloud Services)</td> </tr> <tr> <td>Contacts</td> <td>Search contacts and add/edit contacts</td> </tr> <tr> <td>Database</td> <td>Access to SQLite DB within application and produce DB</td> </tr> <tr> <td>Facebook</td> <td>Support application connection to Facebook</td> </tr> <tr> <td>Filesystem</td> <td>Access device’s file and folder</td> </tr> <tr> <td>Geolocation</td> <td>Provide information on device’s location</td> </tr> <tr> <td>Map</td> <td>Produce native map</td> </tr> <tr> <td>Media</td> <td>Call out media-related function of device (Audio, Video, ImageView, Camera, and Photo Gallery API)</td> </tr> <tr> <td>Network</td> <td>Produce Socket, HTTPClient, TCPSocket, and support communication</td> </tr> <tr> <td>Platform</td> <td>Access function per device’s platform (check battery status)</td> </tr> <tr> <td>UI</td> <td>Form UI of application</td> </tr> <tr> <td>XML</td> <td>XML-based content parsing</td> </tr> </tbody> </table> The structure of Bluetooth Smart consists of traditional Bluetooth, Bluetooth Smart Ready, and Bluetooth Smart, as shown in Figure 4. Bluetooth Smart Ready is in the form of a hub device that can be connected to both traditional Bluetooth and Bluetooth Smart devices. Yet, Bluetooth communicates through Mac addresses when a device does not have an IP. This leads to a problem where deviating from the given range renders communication among devices impossible. 2.4. Network Application Development. Cloud computing refers to a structure of computing systems where I/O operations are carried out through a user’s device, but information analysis, process, storage, management, and distribution are accomplished in another space called a “cloud.” Figure 5 shows an outline of this structure [25]. Cloud technology can be divided into three parts, Infrastructure as a Service (IaaS), Platform as a Service (PaaS), and Software as a Service (SaaS), from the perspective of service provision. A representative service of IaaS is Amazon’s EC2, which provides server computation and hardware storage online [26]. PaaS represents platform supply for host and enterprise services. PaaS makes use of resources of IaaS to support certain platforms, including Microsoft’s Azure and Google’s App Engine [27, 28]. SaaS is a basic technology that supplies user-driven service. It can be divided into applied software service, web-based service, and component-based service. The sole function of several SaaS companies that research maps, images, videos, documents, mail, and so forth is service, and they distribute representational state transfer- (REST-) based Open APIs, numerous platforms, and development languages supporting SDK. IT companies, such as Google, Facebook, Baidu, Kakao, and NAVER, cater to many types of Open APIs for developers [29, 30]. For cloud service development, Amazon offers smartphone platforms for Android and SDKs for different programming languages (Java, .NET, PHP, Ruby, etc.) at the same time [31]. The Azure platform also provides program APIs in the structure of .NET, Node.js, Java, and PHP [32]. SaaS companies distribute REST-based Open APIs and development languages supporting SDK. However, most SDKs and Figure 3: Mobile application development process using Titanium Studio. APIs focus on establishing cloud servers. Thus, the client application needs to be separately implemented on each platform of a service-providing device where a native app is used. This implies that a network application that provides cloud service must construct a development environment for each platform and learn the development language to create an application, in a similar manner to the native app development process. 3. Proposal Sections 1 and 2 examined the characteristics of and challenges faced by the existing development platforms. In Section 3, we suggest a solution for the foregoing problems and discuss the detailed structure of our proposed platform, followed by a discussion of scenarios to which the technique is applicable. 3.1. Wearable Device Control Platform 3.1.1. Network Application Agent (NetApp-Agent). In this paper, we propose a wearable device control platform called Network Application Agent (NetApp-Agent) for network application development. Figure 6 shows our proposed platform diagram. NetApp-Agent, in the form of a smartphone application, controls the I/O function of the smartphones, its connected wearable devices, and IoT devices by following commands from a remote controller. In order to do this, a self-defined JavaScript Object Notation- (JSON-) based NetApp-Agent API equipped with WebSocket is provided to the user for remote control. 3.1.2. Network Application Agent API (NetApp-Agent API). The user connects to NetApp-Agent through an IP. NetApp-Agent controls the I/O functions of smart devices or linked wearable devices and requests the necessary information through supporting APIs. Therefore, the proposed platform allows the developer to easily create a device without background knowledge of wearable or IoT devices. Outside users can be any programmable device that wants to communicate through IP-based cloud server, tablet PC, or smartphone using a supporting API. 3.1.3. Structure of Proposed Platform. Figure 7 shows the detailed structure of our proposed platform. NetApp-Agent aims to be a cross-platform development framework that can run applications regardless of the type of mobile platform in question. However, as mentioned before, Cordova’s API is limited in its range of support. Our proposed platform amplifies the range of APIs by the binary use of Cordova and Native device wrappers. Functions such as battery check, vibration, and acquisition of global positioning system (GPS) information are developed with the API, whereas I/O functions such as sensors and display are developed with the Native API. For network connection control, Cordova provides an API for receiving cellular and Wi-Fi connection information. Thus, cellular communication and Wi-Fi connection information is implemented using Cordova API, and connection control, such as obtaining Bluetooth connection information and simple On/Off functions of the network, is implemented by using Native API. Wearable devices and IoT devices do not support Cordova API, and thus related functions are established through the Native API. The established functions are controllable by a self-defined JSON-based NetApp-Agent API, where NetApp-Agent provides its implemented API to the outside user. The WebSocket in NetApp-Agent allows IP-based communication between the device and the user. The outside user thus has remote access to control I/O functions of the device. The inventory database saves the device’s connectivity and specification information related to the smartphone. If remotely requested to connect, NetApp-Agent provides its stored information to the outside user. The user then confirms the desired device to control. An intelligence-processing module supports the establishment of intelligible operations in the device. Pebble’s SmartWatch does not support Korean characters and uses a self-defined Perceptual-Backdrop Image (PBI) format for images. As a consequence, if an outside user sends a message containing Korean characters, NetApp-Agent automatically transmits it after translating it into an image. NetApp-Agent does not simply read or write the information of the device connected to the smartphone, but it provides intelligent service through the intelligence-processing module. 3.2. Cloud Service Application Scenario for Proposed Platform. Figure 8 shows the interface of interaction between NetApp-Agent and the cloud server. There is a network application in the cloud server for communication with NetApp-Agent. The network application uses the NetApp-Agent API for the cloud server to supply the service demanded by the user without modification. We examine here the application of the proposed platform to a cloud service scenario. Possible scenarios are divided into three parts according to their function. 3.2.1. Acquisition of QR Code Information Using Cloud Server. Figure 9 shows a scenario concerning the analysis of Quick Response (QR) code spotted in the camera of a wearable device. The code is processed in the cloud server, and the extracted information is sent back to the wearable device for display. The video containing the QR code is sent to the cloud server. Images are extracted from the video and form the basis of QR code recognition. The cloud server simultaneously runs various code extraction methods to improve QR code recognition rate. There are three methods to recognize QR code: the traditional method, recognition using the image of the object itself, and an analysis of the similarity of images. In the analysis of similarity, information related to previously stored QR images and location information on the product by beacon are used together. The information extracted from the QR code goes through a series of processes to be displayed on the screen of the wearable device. In this scenario, the wearable device is only used as a tool for I/O, while the extraction and processing of information from the QR code are carried out in the cloud server. The cloud server can implement an application that displays the information on the wearable device using the NetApp-Agent API without having to develop a native app. 3.2.2. Voice and Video-Sharing Scenario Involving Smart Device and Cloud Server. Figure 10 shows a scenario for voice and video sharing between a smart device and the cloud. Figure 8: The NetApp-Agent interface. Figure 9: QR code analysis scenario using cloud server. Figure 10: Voice and video-sharing scenario involving smart device and cloud server. server. A user wearing Google Glass transmits information in real time to the cloud server, which shares the transferred video with the user again and issues an order. An order can be issued by pointing at the transferred video. The cloud server once again utilizes the NetApp-Agent API to implement an application to display information on the wearable device. Thus, modification of the wearable device is unnecessary. 3.2.3. Voice and Video Data Sharing among Smart Devices. Figure 11 shows a more detailed scenario than the previous one. Two smart devices capable of IP-based communication share video, voice, and image through a camera in real time with the cloud server acting as mediator. The realization of this scenario can lead to innovative services in the market. For instance, suppose User A shares his/her location with User B through an image as User B guides User A through vocal instructions or ostensive guides using the shared image. 4. Experiment and Qualitative Assessment In this section, we report an experiment to show the feasibility of the suggested platform and discuss the results. The efficiency of the proposed platform is also confirmed through a comparative analysis with the existing development platforms. 4.1. Empirical Research of the Proposed Platform 4.1.1. NetApp-Agent Implementation by Utilizing Native Development Method. The proposed platform was implemented in order to demonstrate how proposal works as the prototype. The setup consisted of a smartphone equipped with NetApp-Agent, another smartphone with a network application communicating with NetApp-Agent, and controllable wearable devices, as shown in Figure 12. NetApp-Agent was implemented in Android 4.1.2, and a web server function was added to support Hypertext Transfer Protocol (HTTP) communication based on IP. The two wearable devices used were a Sony SmartWatch and a Pebble SmartWatch. Sony Add-on SDK 2.1 and Pebble SDK 2.0 were installed to develop the SmartWatch application. The user application was implemented in Android 4.1.0 version and the HTTPClient class in Android was used to support HTTP communication. Both NetApp-Agent and the user application exchanged JSON data using a self-defined NetApp-Agent API and sending HTTP communication based on IP. Table 7 lists the NetApp-Agent APIs. NetApp-Agent enabled the transmission of texts and images to wearable devices. Accordingly, the four former APIs were used, ConnectedDeviceList (which offered the list of connected wearable devices and detailed information regarding each device), Select Device (which selected the messaging terminals), Send Text (to send texts), and Send Image (to send images to devices). The four latter APIs will soon be added to NetApp-Agent APIs. The detailed working structure of the implemented platform is shown through a sequence diagram. Figure 13 shows the process of acquiring information related to the detailed specifications and connections of wearable devices using the network application. The network applications transmit an HTTP GET method to set connections with NetApp-Agent. Upon receiving requests, the NetApp-Agent sends messages containing information regarding connected wearable devices and detailed specifications of each device to the network application, which follows a JSON type. On receiving In JSON messages through HTTP POST. On receiving the messages, NetApp-Agent sends texts to the selected wearable devices and prints it on the screen. Depending on the context, NetApp-Agent supports intelligent tasks. In case of the Pebble SmartWatch, it used to show the issue of incompatibility with Korean language. Thus, if text has to be transmitted through Pebble SmartWatch, NetApp-Agent senses the Korean characters in the messages before sending messages to wearable devices. While messages containing no Korean characters are transmitted as text, those containing Korean characters are transformed into PBI images and then transmitted to Pebble SmartWatch and vice versa. Figures 16 and 17 show the process of sending images to wearable devices via NetApp-Agent and the results obtained on the screen. As in the case of sending texts, device information regarding the data and the images is sent to NetApp-Agent using HTTP POST. The images may need to be converted depending on the types of targeted devices when sending images. Sony SmartWatch displays images by temporarily saving them on the smartphone and sending uniform resource identifier (URI) information. By utilizing its self-defined image format, the Pebble SmartWatch converts the received bitmap images to PBI format and then sends it. ### Table 7: List of NetApp-Agent APIs. <table> <thead> <tr> <th>API</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>Connected Device List</td> <td>Provide detailed information on each device and the list of wearable devices connected to smartphone through Bluetooth</td> </tr> <tr> <td>Select Device</td> <td>Select the kinds of wearable devices to control</td> </tr> <tr> <td>Send Text</td> <td>Make the text appear on the screen by sending it to wearable devices</td> </tr> <tr> <td>Send Image</td> <td>Make the image appear on the screen by sending it to wearable devices</td> </tr> <tr> <td>Send Voice</td> <td>Make the voice and sound appear at speaker by sending it to wearable devices</td> </tr> <tr> <td>Cellular</td> <td>Monitor cellular state and make cellular state enabled or disabled</td> </tr> <tr> <td>Wi-Fi</td> <td>Monitor Wi-Fi state and make Wi-Fi enabled or disabled</td> </tr> <tr> <td>Bluetooth</td> <td>Monitor Bluetooth state and make Bluetooth enabled or disabled</td> </tr> </tbody> </table> information about wearable devices, the network application adds the device information to the ListView so that users can select devices after checking related information. Figure 14 shows the process of sending texts to wearable devices via NetApp-Agent, and Figure 15 shows the implementation of the platform. Information on devices for submission and text values selected by users are transmitted in JSON messages through HTTP POST. On receiving the messages, NetApp-Agent sends texts to the selected wearable devices and prints it on the screen. Depending on the context, NetApp-Agent supports intelligent tasks. In case of the Pebble SmartWatch, it used to show the issue of incompatibility with Korean language. Thus, if text has to be transmitted through Pebble SmartWatch, NetApp-Agent senses the Korean characters in the messages before sending messages to wearable devices. While messages containing no Korean characters are transmitted as text, those containing Korean characters are transformed into PBI images and then transmitted to Pebble SmartWatch and vice versa. Figures 16 and 17 show the process of sending images to wearable devices via NetApp-Agent and the results obtained on the screen. As in the case of sending texts, device information regarding the data and the images is sent to NetApp-Agent using HTTP POST. The images may need to be converted depending on the types of targeted devices when sending images. Sony SmartWatch displays images by temporarily saving them on the smartphone and sending uniform resource identifier (URI) information. By utilizing its self-defined image format, the Pebble SmartWatch converts the received bitmap images to PBI format and then sends it. 4.1.2. NetApp-Agent Implementation Utilizing Cordova Platform. NetApp-Agent aspires to be a cross-platform development framework that implements applications regardless of the type of mobile platform at hand and expands the coverage of API support by adding Native API functions to the Cordova API. Cordova supports the acquisition of the location information of devices and an API that provides status information regarding cellular connected to devices or to Wi-Fi networks. Figure 18 shows sequence of Acquiring GPS and network information. Consequently, when the location information of a smartphone and a network is requested to NetApp-Agent by network application, NetApp-Agent responds to a call in a way of acquiring information by calling Cordova API. 4.2. Qualitative Assessment of the Proposed Method. In this subsection, we conduct a functional analysis of the existing development platforms as well as our proposed NetApp-Agent and use this qualitative assessment to identify the pros and cons of the proposed platform. The efficiency of the proposed platform is tested throughout this process. 4.2.1. Provision of Integrated Development Environment for Devices. The current mobile market has several mobile platforms, such as Android, iOS, and Windows Mobile. Owing to the diversity of platforms, developers need to construct development environments according to platform and learn several programming languages, which slows down the pace of development. Mobile programming is gradually becoming standardized to cope with such issues, and cross-platforms such as Cordova and Titanium are welcome as a result. Nevertheless, cross-platforms are limited in their scope of API coverage and are still in the process of developing APIs to control wearable devices. All of this underscores the necessity of the acquisition and development of native languages. In other words, cross-platform by itself is inadequate for developing applications for wearable devices. A comprehension and development of applications that take into account unfamiliar development environments and API assistance for wearable devices would be extremely time-consuming. Table 8 shows the development environment of the Cordova development platform. When developing wearable devices outside Cordova’s stipulated coverage, the native development approach is preferred. Hence, the development of applications necessitates the construction of development environments depending on target devices as well as knowledge of compatible APIs. In the case of applications for Google Glass, for instance, developers need to learn both the development language, such as Python and Java, and the Google Mirror API after installing the relevant development tools. Developing applications for Pebble SmartWatch requires that developers construct suitable development environments and learn specific languages such as Pebble SDK and PebbleKit SDK, which are built-in functions of a smartphone. Even when developing different applications for the same purpose, a considerable amount of time needs to be spent on creating different development environments and learning unfamiliar languages. The table shows development environments for four different devices, where developers had to learn 10 programming languages and 7 APIs. As the number of devices supplying applications increases, the workload and time spent on development increase proportionately. Table 8: Development environment of Cordova platform. <table> <thead> <tr> <th>Types of devices</th> <th>Operating system</th> <th>Supporting languages</th> <th>Under Cordova platform</th> </tr> </thead> <tbody> <tr> <td>Total</td> <td>4</td> <td>Go, Java, .NET, PHP, Python, and Ruby</td> <td>10</td> </tr> <tr> <td>Google Glass</td> <td>Android 4.0.4</td> <td>Google Mirror API</td> <td></td> </tr> <tr> <td>Sony SmartWatch</td> <td>Android 4.0</td> <td>Java</td> <td></td> </tr> <tr> <td>Pebble SmartWatch</td> <td>Pebble OS</td> <td>C, JavaScript, and so forth (Objective-C/Java)</td> <td></td> </tr> <tr> <td>Samsung Gear</td> <td>Tizen OS</td> <td>Java, HTML, JavaScript, and so forth</td> <td></td> </tr> </tbody> </table> Table 9: Development environment of NetApp-Agent. <table> <thead> <tr> <th>Types of device</th> <th>Operating system</th> <th>Supporting languages</th> <th>Under NetApp-Agent</th> </tr> </thead> <tbody> <tr> <td>Total</td> <td>1</td> <td>No limitations</td> <td>1</td> </tr> <tr> <td>NetApp-Agent supporting devices (extendable)</td> <td>No limitations</td> <td>No limitations</td> <td>NetApp-Agent API (WebSocket/JSON-based)</td> </tr> </tbody> </table> Table 9 shows the application development environment based on NetApp-Agent. If developers are aware of the specific features of JSON-based NetApp-Agent APIs and the implementation of WebSocket for communication with a platform, other applications can be easily developed using programming languages with which developers are, presumably, already familiar. Thus, procedural redundancies, such as constructing a separate development environment for each platform and learning both the relevant languages and the API, can be effectively avoided. This approach can downsize the time and cost needed to develop applications, and developers can easily expand the selection of devices compatible with the applications. 4.2.2. Expansion of API Supply Coverage of Platform. Cross-platform development frameworks such as Titanium and Cordova are still in the process of development and hitherto have failed to guarantee wide API coverage. The proposed platform widens the coverage of serviceable APIs by adding a native device wrapper to the Cordova wrapper. Table 10 lists the kinds of APIs per development platform. We see that NetApp-Agent supports wider API coverage than the in wearable devices as most functions are usually dependent on smartphones. Connections between smartphones and wearable devices are needed to guarantee the practical use of devices, and Bluetooth-based interdevice communication is utilized at this stage. Bluetooth as a communication system for short distances is implemented by referring to the Mac addresses of the paired devices. Accordingly, it is virtually limited for a wearable device that only supports Bluetooth communication to communicate with external devices or users as it is the same issue of IoT devices. Our proposed platform forms Bluetooth connections with wearable/IoT devices and supports WebSocket-based IP communication. It creates a network by grouping together Bluetooth-based devices and enables IP communication with the outside. Thus, outside users can communicate with and control wearable/IoT devices using IP without having to form Bluetooth connections. Figure 19 shows the differences between the existing platform and the proposed one. In case of the existing method, wearable/IoT devices only support Bluetooth communication. To use and control devices, smartphones connected to them need to be carried to within the coverage range of Bluetooth communication. The proposed platform supports remote access to devices without IP. Accordingly, devices can be controlled from outside using IP communication. 4.2.3. **IP-Based Communication Service for Bluetooth Communication Devices.** It is rare to find stand-alone functions in wearable devices as most functions are usually dependent on smartphones. Connections between smartphones and wearable devices are needed to guarantee the practical use of devices, and Bluetooth-based interdevice communication is utilized at this stage. Bluetooth as a communication system for short distances is implemented by referring to the Mac addresses of the paired devices. Accordingly, it is virtually limited for a wearable device that only supports Bluetooth communication to communicate with external devices or users as it is the same issue of IoT devices. Our proposed platform forms Bluetooth connections with wearable/IoT devices and supports WebSocket-based IP communication. It creates a network by grouping together Bluetooth-based devices and enables IP communication with the outside. Thus, outside users can communicate with and control wearable/IoT devices using IP without having to form Bluetooth connections. Figure 19 shows the differences between the existing platform and the proposed one. In case of the existing method, wearable/IoT devices only support Bluetooth communication. To use and control devices, smartphones connected to them need to be carried to within the coverage range of Bluetooth communication. The proposed platform supports remote access to devices without IP. Accordingly, devices can be controlled from outside using IP communication. 4.2.4. **Provision of Network Application Development Environment.** SDKs and APIs being offered to implement cloud services mostly focus on building the cloud server. Consequently, client applications need independent implementation for each platform in order to service devices. The proposed NetApp-Agent platform supports the development of network applications for cloud services. Network applications carry out IP-based communication with NetApp-Agent and use NetApp-Agent APIs to provide services using cloud servers to users without the need for further implementation or revision of smart devices. Considering that smart devices are only implemented through the API offered, the revision of smart device programs is unnecessary even if the function of the native application is extended or a brand-new network application is developed. Furthermore, smart devices can support intelligent functions by connecting to the cloud server, which was hitherto unavailable for smart devices. This enables the provision of advanced services to users as a result. 4.3. Experimental Implementation of the Proposed Method 4.3.1. Expandable Cross-Platform for QR Code Recognition Using the Pregenerated Image Matching Method. QR code is two-dimensional code developed in 1994, and the amount of a QR code is rapidly increasing [33]. It can handle more information than barcode about several hundreds of times and anyone can make and use it easily. Also, it enables the user to access website through recognizing code without entering URL [34]. The important key of QR code recognition is caught “Finder Pattern” of QR code. QR code can be recognized only if camera catches these three patterns. When angle bends largely, camera cannot catch three patterns so that it becomes impossible to recognize QR code [35]. The QR code recognition method is “pregenerated image matching” that finds original QR code through similarity test of shooting photograph and database’s images in the server. We suggest the composition of server-device environment and operational process. Figure 20 shows the entire operating process of QR code recognition method. At this method, wireless device sends shooting QR code image without any processing to the cloud server. After receiving QR code image, cloud server performs whole operating process. It is a contrast to traditional technology where shooting device performs whole operating process. Before the recognition, cloud server must store QR code images in the database. This process includes transform QR code image in four directions with every single angle. Once wireless device takes a picture of QR code image, device sends image to server. Server performs similarity test among input image and images stored into the database. Server finds an original image with the largest similarity coefficient. Finally, it sends detecting QR code image and decoding information to the wireless device. Figures 21 and 22 show the process of QR code recognition based NetApp-Agent. We create a NetApp-Agent application using Cordova wrapper, which supports “pregenerated image matching” on various devices. A device made of web... application communicates with the server made of Node.js using WebSocket. Because different operating system can use the same web application, the service can be provided to various devices with separate operating system [36]. We used Google’s reference phone, which is Nexus 4 installed Android 4.4 Kitkat. In addition, we had a test in Lumia 920 installed Windows Phone 8.0 and Samsung Galaxy Tab 10.1 installed Android 4.0 Ice Cream Sandwich. Figure 23 shows that application of the QR code recognition is portable to other operating systems. 4.3.2. Performance Evaluation of the Pregenerated Image Matching Method. This paper’s experiment is verifying the recognition of QR code in the angle where it cannot be recognized in traditional QR code applications. First, we implement an experiment to find the maximum recognition angle of traditional applications. We measure the maximum recognition angle with four smartphones using NAVER and SCANY application. Tables 11 and 12 are the test result of using 1.8 cm * 1.8 cm QR code. Those two applications display the maximum recognition angle at 55° so we experiment the possibility whether our proposed method can recognize the image at 60°. Figure 24 is 1.8 cm * 1.8 cm 10 QR code images for recognition. These images of the database were taken at a distance of 20 cm by using the phone camera directly. Setting the maximum angle of the QR code to 70 degrees, the images were taken 5 degrees from 0 degrees by incrementing. The images are stored in binary. We saved 15 images per QR code, and the 150 images were set as the comparison of the experiment. We examined by comparing the similarity between the 150 QR code images and we saved the 10 QR code inclined at 60 degrees. After checking the similarity, the similarity of each QR code was output in descending rank from first to third rankings. Figure 25 is a graph using a QR code 01 taken at 60-degree angles, representing the similarity of the 150 QR code images. It is expressed by a line of a different color for each QR code, the horizontal axis represents the value of the angle, and the vertical axis represents the degree of similarity (%). The most significant similarity is the image at 60 degrees of QR code 01, because the QR code image has high similarity with itself. Other QR codes can be matched with target of experiment, having relatively low similarity. These experimental results show that the proposed method is superior to the traditional method, which is used by NAVER and SCANY application; this paper presents recognition of QR code over other applications’ maximum limit angle. 5. Conclusion and Future Research In this paper, we proposed a wearable device control platform to develop network applications. We also carried out an experiment to confirm the feasibility and efficiency of the proposed platform. The advantages of the proposed platform Figure 24: 10 QR code images for experiment. Figure 25: The graph of the experimental results. were tested through a comparative analysis with the existing platform. There are two main advantages of our proposed platform. First, it reduces the time and cost needed to develop applications by providing a single API to developers. In past development approaches, developers needed to construct development environments for each platform and had to learn several programming languages and APIs when developing applications. For the development of applications working on a Sony SmartWatch, an Android-based development environment had to be constructed, and, in order to install the Sony Add-on SDK, learning about Java and API had to be gone through. Furthermore, the development of applications with the same features for Pebble SmartWatch required that developers acquire relevant knowledge of the programming languages, such as C and Pebble SDK. The increase in the number of platforms led to a rise in the time and resources required to develop applications, which are falling behind the current trends in which a variety of wearable devices are consistently launched. By integrating development environments and offering a JSON-based API, our proposed platform eases the burden of application development regardless of environment and type of platform. Moreover, the issue of limited API coverage in the Cordova platform was addressed by using a Cordova device wrapper and a native wrapper together. The proposed platform enables the development of a wide variety of applications by extending API coverage to software/hardware module control of devices. Second, wearable devices that support Bluetooth communication can communicate with the external environment in our platform using IP. Existing wearable devices support Bluetooth communication and are heavily dependent on smartphones. However, in the existing platform, a smartphone needs to be carried to control and utilize wearable devices, which need to be located within the range of Bluetooth coverage. The proposed platform allows the control of devices through remote access as well as the exchange of relevant information. Due to rising demand for IoT, the era of wider communication even with blub, TV, remote control, and vehicles is coming. The application of the proposed platform to IoT will make it possible to form an interdevice network where outside users can control devices. At this point, in technological development, when the need for a standardized mobile programming method is pressing on account of the growing number of smart devices on a variety of platforms, our proposed platform shows advantages by unveiling its unique features which are incorporating the development methods of applications and supporting IP-based communications to external devices. Thus, since our platform facilitates the development of service applications without additional implementation or revision, the widespread adoption of this approach is expected in developing network applications that service smart devices. An issue to consider is that consistent attention and updates to the platform will be required for new smart devices and platforms in order to guarantee the continual use and development of NetApp-Agent. The experiment described here shows the feasibility of NetApp-Agent, which adds some limitations on the coverage of serviceable API. Hence, the proposed NetApp-Agent is in need of further implementations. Conflict of Interests The researchers claim no conflict of interests. Acknowledgments This research was supported by the MSIP (Ministry of Science, ICT and Future Planning), Republic of Korea, under the ITRC (Information Technology Research Center) support program (IITP-2015-(H8501-15-1015)) supervised by the IITP (Institute for Information & Communications Technology Promotion); the Institute for Information & Communications Technology Promotion (IITP) Grant funded by the Korea government (MSIP) (B0190-15-2013, Development of Access Technology Agnostic Next-Generation Networking Technology for Wired-Wireless Converged Networks); and the ICT R&D Program of MSIP/IITP, Republic of Korea (B0101-15-1366, Development of Core Technology for Autonomous Network Control and Management). References
{"Source-Url": "http://downloads.hindawi.com/journals/misy/2016/3038515.pdf", "len_cl100k_base": 11832, "olmocr-version": "0.1.53", "pdf-total-pages": 21, "total-fallback-pages": 0, "total-input-tokens": 59086, "total-output-tokens": 13919, "length": "2e13", "weborganizer": {"__label__adult": 0.0007333755493164062, "__label__art_design": 0.0006623268127441406, "__label__crime_law": 0.0004405975341796875, "__label__education_jobs": 0.0010776519775390625, "__label__entertainment": 0.00015652179718017578, "__label__fashion_beauty": 0.0004606246948242187, "__label__finance_business": 0.0005903244018554688, "__label__food_dining": 0.000453948974609375, "__label__games": 0.0013303756713867188, "__label__hardware": 0.018035888671875, "__label__health": 0.0009317398071289062, "__label__history": 0.0005044937133789062, "__label__home_hobbies": 0.00015676021575927734, "__label__industrial": 0.0006513595581054688, "__label__literature": 0.0003664493560791016, "__label__politics": 0.00026416778564453125, "__label__religion": 0.0005893707275390625, "__label__science_tech": 0.0958251953125, "__label__social_life": 8.386373519897461e-05, "__label__software": 0.01081085205078125, "__label__software_dev": 0.86376953125, "__label__sports_fitness": 0.0004973411560058594, "__label__transportation": 0.001190185546875, "__label__travel": 0.00027298927307128906}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 66289, 0.01752]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 66289, 0.38334]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 66289, 0.8985]], "google_gemma-3-12b-it_contains_pii": [[0, 4018, false], [4018, 10148, null], [10148, 14448, null], [14448, 19110, null], [19110, 21411, null], [21411, 26872, null], [26872, 30685, null], [30685, 33186, null], [33186, 33367, null], [33367, 36694, null], [36694, 41122, null], [41122, 42509, null], [42509, 44249, null], [44249, 47305, null], [47305, 51056, null], [51056, 53373, null], [53373, 56265, null], [56265, 59235, null], [59235, 65122, null], [65122, 66289, null], [66289, 66289, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4018, true], [4018, 10148, null], [10148, 14448, null], [14448, 19110, null], [19110, 21411, null], [21411, 26872, null], [26872, 30685, null], [30685, 33186, null], [33186, 33367, null], [33367, 36694, null], [36694, 41122, null], [41122, 42509, null], [42509, 44249, null], [44249, 47305, null], [47305, 51056, null], [51056, 53373, null], [53373, 56265, null], [56265, 59235, null], [59235, 65122, null], [65122, 66289, null], [66289, 66289, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 66289, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 66289, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 66289, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 66289, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 66289, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 66289, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 66289, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 66289, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 66289, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 66289, null]], "pdf_page_numbers": [[0, 4018, 1], [4018, 10148, 2], [10148, 14448, 3], [14448, 19110, 4], [19110, 21411, 5], [21411, 26872, 6], [26872, 30685, 7], [30685, 33186, 8], [33186, 33367, 9], [33367, 36694, 10], [36694, 41122, 11], [41122, 42509, 12], [42509, 44249, 13], [44249, 47305, 14], [47305, 51056, 15], [51056, 53373, 16], [53373, 56265, 17], [56265, 59235, 18], [59235, 65122, 19], [65122, 66289, 20], [66289, 66289, 21]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 66289, 0.29365]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
e6882dda6a23557c5aa5395c61bc0a05161aa57f
OODB Bulk Loading Revisited: The Partitioned-List Approach Janet L. Wiener Jeffrey F. Naughton Department of Computer Sciences University of Wisconsin-Madison 1210 W. Dayton St., Madison, WI 53706 {wiener,naughton}@cs.wisc.edu Abstract Object-oriented and object-relational databases (OODB) need to be able to load the vast quantities of data that OODB users bring to them. Loading OODB data is significantly more complicated than loading relational data due to the presence of relationships, or references, in the data; the presence of these relationships means that naive loading algorithms are slow to the point of being unusable. In our previous work, we presented the late-invsort algorithm, which performed significantly better than naive algorithms on all the data sets we tested. Unfortunately, further experimentation with the late-invsort algorithm revealed that for large data sets (ones in which a critical data structure of the load algorithm does not fit in memory), the performance of late-invsort rapidly degrades to where it, too, is unusable. In this paper we propose a new algorithm, the partitioned-list algorithm, whose performance almost matches that of late-invsort for smaller data sets but does not degrade for large data sets. We present a performance study of an implementation within the Shore persistent object repository showing that the partitioned-list algorithm is at least an order of magnitude better than previous algorithms on large data sets. In addition, because loading gigabytes and terabytes of data can take hours, we describe how to checkpoint the partitioned-list algorithm and resume a long-running load after a system crash or other interruption. 1 Introduction As object-oriented and object-relational databases (OODB) attract more and more users, the problem of loading the users’ data into the OODB becomes more and more important. The current methods of loading create only one object at a time. These methods, i.e., insert statements in a data manipulation language, or new statements in a database programming language, are more appropriate for loading tens and hundreds of objects than for loading millions of objects. Loading large amounts of data is currently a bottleneck in many OODB applications [CMR92, CMR+94]. Relational database systems provide a load utility to bypass the individual language statements. The load utility takes an ASCII description of all of the data to be loaded and returns when it has loaded it. For these relational systems, a load utility significantly improves performance even when loading only a small number of objects, because it is based in the database server [Moh93b]. The load utility can therefore dramatically reduce the amount of client-server interaction, and hence both the layers of software traversed and the communication overhead to create each new object. There are many commercial object-oriented database products today, including Ontos [Ont94], O2 [Den90], Objectivity [Obj92], ObjectStore [LLOW91], Versant [Ver93], and Gemstone [MS90]. Yet to our knowledge no commercial OODB has a load utility. Why not? Relative to loading relational data, loading object-oriented (and object-relational) data is complicated by the presence of relationships among the objects; these relationships prevent using a relational load utility for an OODB. - Relationships between objects are represented by object identifiers (OIDs) in the database. These OIDs are created and maintained by the database and are usually not visible to the user. Furthermore, these OIDs are not available at all when the load file is written, because the corresponding objects have not yet been created. Relationships must therefore be represented by some other means in the load file, which we call a surrogate identifier. We use a data structure called an id map to map each surrogate to its corresponding OID as the objects are loaded. - Relationships may be forward references in the data file. The surrogate used to represent a relationship may belong to an object described later in the data file. It may not be possible to resolve the surrogate into an OID when it is first seen in the data file. - Relationships may have system-maintained inverse relationships, so that the description of one object in the data file may cause another object (its inverse for a given relationship) to be updated as well. Inverse relationships are sometimes called bidirectional relationships, and are part of the ODMG standard [Cat93]. Ontos, Objectivity, ObjectStore, and Versant all support inverse relationships [Ont94, Obj92, LLOW91, Ver93]. In addition to dealing with relationships, a good load utility must be able to load data sets of widely varying sizes. As the size of the data set increases, an increasing degree of care and cleverness is required to load the data quickly. We categorize data sets into three classes of sizes, relative to the amount of physical memory available for the load, as follows: 1. *All of the data to be loaded fits in physical memory.* Naive algorithms suffice to load this class. However, a good load algorithm can achieve a 20-30% performance gain [WN94]. Also, as we mentioned above, a load utility can decrease client-server interaction to speed up --- 1 Objectivity has something it calls a load utility, however, it can only load data that already contains system-specific object identifiers (OIDs) [Obj92]. Similarly, Ontos's bulk load facility is really just an option to turn off logging while running user code that creates large amounts of data [Ont94]. loading, which individual **new** and **insert** statements can not. 2. **The data itself is too large for memory, but the id map does fit.** (The size of the id map is a function of the number of objects regardless of their size.) For this class of load sizes, our previously proposed algorithms [WN94] work well, improving performance by one to two orders of magnitude over naive algorithms. 3. **Neither the data nor the id map fits in memory.** As a followup to [WN94], we ran experiments with loads in this range and found that our previously proposed algorithms exhibited terrible performance due to thrashing (excessive paging of the id map) on id map lookups. Unfortunately, it is for these large loads that a fast load algorithm is most needed. In this paper we propose the partitioned-list algorithm, which, unlike our previous algorithms, provides good performance even for this range of problem sizes. The third class is not only the most challenging, it is also the class in which many data sets fall. We give two examples of such data sets from the scientific community. In both cases, the scientists involved are using or planning to use an OODB to store their data. - The Human Genome Database [Cam95, CPea93] is currently just over 1 gigabyte of 50-200 byte objects, containing 3-15 bidirectional relationships each. Loading this database when it moves to an OODB (which is planned for sometime in 1995) will require an id map of at least 160 megabytes. - The climate modeling project at Lawrence Livermore National Laboratory generates up to 20,000 time points, each a complex object (i.e., many interconnected objects), in a simulation history. In the range of 40 gigabytes to 3 terabytes of data is produced in a single simulation history [DLP+93]! An id map for a single data set requires upwards of 200 megabytes. We note that the physical memory available for a load is not necessarily the total physical memory of the machine, but rather the memory not being used by other concurrent queries or utilities. Additionally, because loading hundreds of megabytes takes hours, it is desirable not to lose all of the data loaded when a system crash occurs. Resuming a load (or any other transaction) after a crash is non-trivial, however. We show both what to save in a **restart checkpoint** of the partitioned-list algorithm and how to resume from one of these checkpoints. We show that only minimal information need be saved in the restart checkpoints for partitioned-list, the checkpoints can be taken relatively frequently, and only the work done after the last restart checkpoint is lost if the system crashes. 1.1 Related work Several published techniques are available for loading complex data structures with relationships from an ASCII file, but they all assume the smallest class of data sets. That is, they assume that all of the data can fit in memory and are unsuitable when it cannot. Both Snodgrass’s Interface Description Language [Sno89] and Pkl for Modula 3 [Nel91] fall in this category. Our previous work focused on loading data sets in the second class of sizes [WN94]. We presented alternative strategies for handling forward references in the data file and for handling updates due to inverse relationships. We recommended one clearly superior algorithm to use for a load utility, and we will revisit its performance for loading data sets of all sizes in this paper. There has been no work, however, on loading very large data sets, i.e., data sets so large that they fall in the third class of sizes and the id map does not fit in physical memory. Teradata provides a resumable load for their relational database [WCK93] as does DB2 [RZ89]. Mohan and Narang provide an algorithm for what to checkpoint for a resumable sort [MN92], which was the original inspiration for what to checkpoint during a load to make it resumable. 1.2 Structure of the paper The remainder of the paper is structured as follows: In Section 2 we present an example database schema and data file. In Section 3 we review the best of our previous algorithms, describe adaptations of it for large data sets, and present our new algorithm. Section 4 describes our implementation of the algorithms and in Section 5 we present our performance tests and results. We specify how to make our new load algorithm resumable in Section 6. In Section 7 we conclude and outline our future work. 2 Loading example We use an example database schema and data file to illustrate the loading algorithms, which we will describe in the next section. 2.1 Example database schema The example schema describes the data for a simplified soil science experiment. In this schema, each Experiment object has a many-to-one relationship with an Input object and a one-to-one relationship with an Output object. Figure 1 defines the schema in the Object Definition Language proposed by ODMG [Cat93]. interface Experiment { attribute char scientist[16]; relationship Ref<Input> input inverse Input::expts; relationship Ref<Output> output inverse Output::expt; }; interface Input { attribute double temperature; attribute long humidity; relationship Set<Experiment> expts inverse Experiment::input; }; interface Output { attribute double plant_growth; relationship Ref<Experiment> expt inverse Experiment::output; }; Figure 2: Example schema definition in ODL. 2.2 Example data file Figure 2 shows a sample ASCII data file for the schema in Figure 1. Within the data file, objects are grouped together by class, although the classes may appear in any order and a given class may appear more than once. Each class is described by its name, attributes, and relationships. If a relationship of the class is not specified, then objects get a null value for that relationship. Next, each object in the class is described by a surrogate identifier and a list of its values. In this example, the surrogates are integers, and they are unique in the data file. In general, however, the surrogates may be strings or numbers; if the class has a key they may be part of the object’s data [PG88]. Wherever one object references another object, the data file entry for the referencing object contains the surrogate for the referenced object. The process of loading includes translating each surrogates into the OID assigned to the corresponding object. To facilitate this translation, we use an id map. When an OID is assigned to an object, an entry is made in the id map containing the surrogate and OID for that object. Whenever a surrogate is seen as part of the description of an object, a lookup in the id map yields the corresponding OID to store in the object. 3 Load algorithms We first present the naive algorithm for comparison purposes. Then we present our best previous algorithm (formerly called late-insert for loading the database when there is enough memory to store the id map. We also describe two simple modifications to the id map data structure which allow it to exceed memory size. Input(temperature, humidity) { 101: 27.2, 14; 102: 14.8, 87; 103: 21.5, 66; } Experiment(scientist, input, output) { 1: "Lisa", 101, 201; 2: "Alex", 103, 202; 3: "Alex", 101, 203; 4: "Jill", 102, 202; } Output(plant_growth) { 201: 2.1; 202: 1.75; 203: 2.0; } Figure 2: Sample data file for the Experiment schema. but do not alter the basic load algorithm. Finally, we introduce our new algorithm, *partitioned-list*, which is optimized for the case when the id map is significantly larger than the amount of memory available. ### 3.1 Naive algorithm The naive algorithm reads the data file twice, so that forward references in the data file can be handled correctly. The id map is stored as an in-memory open addressing hash table hashed on surrogate. It is kept separate from the database buffer pool. The algorithm has 2 steps. 1. **Read the data file.** - For each object, read its surrogate, create an empty object, and store the surrogate and returned OID in the id map. Ignore all attribute and relationship descriptions. At the end of this step, the id map is complete, and all of the objects have been created and initialized, although their contents are blank. Figure 3 shows the id map for the example data file. 2. **Read the data file again and create the database.** - For each object, look up its surrogate in the id map and find out its OID. - Read the object from the database. - For each relationship described with the object, look up its surrogate in the id map. Store the corresponding OID in the object. Note that all valid surrogates will be found in the id map, since it was completed in step 1. - If the relationship has an inverse, read the inverse object from the database and store this object’s OID in it. - For each other attribute of the object, store it in the object. - Write the updated object back to the database. In this algorithm, each inverse relationship will cause another object to be updated, probably changing the size of that object. Sometimes the inverse object will be described later in the data file, and sometimes earlier. It is necessary to create empty objects in step 1 so that the inverse object always exists in step 2, even if it is described later in the data file. Similarly, it is necessary to read the object from the database in step 2 because it may already contain OIDs for its inverse relationships, stored there by inverse updates to this object. One additional step is necessary before pronouncing the load complete. If an archive copy of the database is maintained in case of media failure, a full archive copy of the newly loaded data must be made before the data is read or written [MN93]. Otherwise, the data might be lost due to media failure, since there is no log record of the loaded data. This step will be necessary for all of the algorithms although we do not mention it again. 3.2 Basic algorithm: id map is an in-memory hash table In this algorithm, the data file is also read twice to handle forward references, and the id map is also an in-memory hash table. Unlike in the naive algorithm, OIDs are pre-assigned to objects. Pre-assigning an OID involves requesting an unused OID from the database without creating the corresponding object on disk. In general, pre-assignment is only possible with logical OIDs, since the future location and size of the object are not known when its OID is pre-assigned. If the database only provides physical OIDs, the algorithm may be modified to create the object in order to get its OID. We believe that any OODB that provides logical OIDs can also provide pre-assignment of OIDs; we know it is possible at the buffer manager level in GemStone [Mai94] and in Ontos, as well as in Shore [CDF+94]. Using logical OIDs does require the database to store an extra index that maps logical to physical OIDs. However, we found previously that the advantages of using logical OIDs (such as having smaller OIDs) outweigh the costs of maintaining and using this index [WN94]. The algorithm has 3 steps. 1. Read the data file. - For each object, pre-assign an OID, and make an entry in the id map. Figure 3: Id map built by the load algorithm. <table> <thead> <tr> <th>Surrogate for object to update</th> <th>OID to store</th> <th>Update offset</th> </tr> </thead> <tbody> <tr> <td>101</td> <td>OID4</td> <td>12</td> </tr> <tr> <td>201</td> <td>OID4</td> <td>8</td> </tr> <tr> <td>103</td> <td>OID5</td> <td>12</td> </tr> <tr> <td>202</td> <td>OID5</td> <td>8</td> </tr> <tr> <td>102</td> <td>OID6</td> <td>12</td> </tr> <tr> <td>203</td> <td>OID6</td> <td>8</td> </tr> <tr> <td>102</td> <td>OID7</td> <td>12</td> </tr> <tr> <td>202</td> <td>OID7</td> <td>8</td> </tr> </tbody> </table> Figure 4: Inverse todo list built for the load algorithms. - For each relationship described with that object, if the relationship has an inverse, make an entry on an inverse todo list, indicating that the inverse object should be updated to contain the OID of this object. Note that the inverse object is described by a surrogate in the data file. Therefore each inverse todo entry contains a surrogate for the object to update, the OID to store in that object, and an offset indicating where to store it. At the end of this step, the id map is complete and the inverse todo list contains entries for all of the updates dictated by inverse relationships. The inverse todo list is stored in the database, because it is too large to reside in memory. Figures 3 and 4 show the id map and inverse todo list for the example data file. 2. Sort the inverse todo list. - First, translate to an OID the surrogate in each entry indicating which object to update. Each translation involves a lookup in the id map. We call the new entries update entries, and the translated list an update list. Each update entry consists of the OID of the object to update, the OID to store in it, and an offset. - Sort the update entries, using a standard external sort, by the OID of the object to update. In our sort, we sort chunks of the update list in memory as the update list is generated, and write each chunk out to <table> <thead> <tr> <th>OID for object to update</th> <th>OID to store</th> <th>Update offset</th> </tr> </thead> <tbody> <tr> <td>OID1</td> <td>OID4</td> <td>12</td> </tr> <tr> <td>OID1</td> <td>OID6</td> <td>12</td> </tr> <tr> <td>OID2</td> <td>OID7</td> <td>12</td> </tr> <tr> <td>OID3</td> <td>OID5</td> <td>12</td> </tr> <tr> <td>OID8</td> <td>OID4</td> <td>8</td> </tr> <tr> <td>OID9</td> <td>OID7</td> <td>8</td> </tr> <tr> <td>OID9</td> <td>OID5</td> <td>8</td> </tr> <tr> <td>OID10</td> <td>OID6</td> <td>8</td> </tr> </tbody> </table> Figure 5: Update list after sorting. disk as a sorted run. Then we merge the sorted runs, as many as can fit in memory at once, until the entire list is sorted. However, we defer the final merge pass until step 3. Figure 5 shows the sorted update list. Sorting by OID groups all of the updates to a single object together. Additionally, because the OIDs are assigned in increasing order, it organizes the updates into the same order as the objects appear in the data file. (If OIDs are not assigned in a monotonically increasing sequence, an integer counter can be used to assign a creation order to each object. Then the creation order for each object is stored as an additional field in the id map and in each update entry, and used as the sort key.) 3. **Read the data file again and create the database.** - For each object, look up its surrogate in the id map and retrieve the OID that has been assigned to it. - For each relationship described with the object, look up its surrogate in the id map. Store the retrieved OID in the object. - Store each other attribute of the object in the object. - For each update entry that updates this object, read the entry from the sorted update list and store the appropriate OID in the object. The last merge pass of sorting the update list happens concurrently with reading the data file and creating the objects. Note that except for the id map, which is in memory, no other data structures or objects are being accessed repeatedly during any step of the algorithm. Therefore, the buffer pool is fully available for merging the last set of sorted runs in step 3 and the last merge pass is never written to disk; the merged entries can be discarded as soon as they have been retrieved and read. An important advantage of this algorithm over similar variants is that by pre-assigning OIDs to objects in step 1, creating the objects can be postponed until *all* the data (including inverse relationships) to be stored in an object is available. Therefore, when the object is initially created, it is of the correct size. (This advantage is only possible with logical OIDs.) Updates that add inverse relationships, on the other hand, usually change the size of the object. Since changing the sizes of objects often severely impacts the clustering of the objects, this advantage is quite significant. Note that, except for the id map, no data structure — inverse todo list, update list sorted run, database object — is read or written more than once. We have eliminated all of the random and multiple accesses to objects that were caused by inverse relationship updates in the naive algorithm. Lookups in the id map are still by random associate access. However, if the id map is resident in physical memory, then no I/Os are necessary to read from it. 3.3 Modification 1: id map is a persistent B+-tree The basic algorithm requires enough virtual memory to store the id map. However, it accesses the id map so frequently that it is more correct to say that it expects and relies on both the buffer pool and the id map being in physical memory. To overcome the limitation of needing physical memory for the id map, we redesigned it as a persistent B+-tree. The amount of the id map resident in memory is constrained by the size of the buffer pool. Paging the id map is delegated to the storage manager, and only the buffer pool needs to remain in physical memory. The load algorithm remains the same; id map lookups are still associative accesses, now to the B+-tree. Note that the choice of a B+-tree instead of a persistent hash table will not be relevant: the important feature of the B+-tree is that it supports random accesses to the id map by paging the id map in the buffer pool. The same would be true of a persistent hash table, and in both cases, random accesses to the id map mean random accesses to the pages of the persistent B+-tree or hash table. 3.4 Modification 2: id map is a persistent B+-tree with an in-memory cache Changing the id map from a virtual memory hash table to a persistent B+-tree had the side effect of placing the id map under the control of the storage manager. In addition to managing the id map’s buffer pool residency, the storage manager also introduces concurrency control overhead to the id map. To avoid some of this overhead, we decided to take advantage of a limited amount of virtual memory for the id map. For this algorithm, we keep the B+-tree implementation of the id map, but introduce an in-memory cache of id map entries. The cache is implemented as a hash table. All inserts store the id map entry in both the B+-tree and the cache. Whenever an insert causes a collision in a hash bucket of the cache, the previous hash bucket entry is discarded and the new entry inserted. All lookups check the cache first. If the entry is not found in the cache, the B⁺-tree is checked, and the retrieved entry is inserted into the cache. The load algorithm remains the same as the basic algorithm; id map lookups are still associative accesses, now first to the cache and then, if necessary, to the B⁺-tree. 3.5 New algorithm: id map is a persistent partitioned list The associative accesses to the id map in the above algorithms are random accesses, and when the id map does not fit in physical memory, they cause random disk I/O. The goal of this algorithm is to eliminate the random I/O. In the above algorithms, half of the id map lookups were to convert the inverse todo entries into update entries. A fundamental observation led to the new algorithm: these lookups, grouped together, constitute a join between the inverse todo list and the id map. The other half of the id map lookups were performed while reading the data file a second time, in step 3, to retrieve the OIDs for each relationship. These lookups were interspersed with reading the data file and creating objects. However, by separating the surrogates from the data file, into a different todo list, the surrogates can also be joined, as a group, with the id map. In this algorithm the id map is written to disk in two different forms at the same time. First, it is written sequentially, so that the OIDs can be retrieved in the same order as they are generated, which is necessary for creating the objects with the OIDs that have been pre-assigned to them. Second, the id map is written so that it can be joined with the surrogates to be looked up. We use a hash join with the id map as the inner relation, so the second time, the id map is written into hash partitions. As many partitions as can fit in the buffer pool are initially allocated. The algorithm has 5 steps. **Figure 6**: Id map with 2 partitions. <table> <thead> <tr> <th>Partition 0</th> <th>Partition 1</th> </tr> </thead> <tbody> <tr> <td><strong>Surrogate</strong></td> <td><strong>Surrogate</strong></td> </tr> <tr> <td>102</td> <td>101</td> </tr> <tr> <td>2</td> <td>103</td> </tr> <tr> <td>4</td> <td>1</td> </tr> <tr> <td>202</td> <td>3</td> </tr> <tr> <td></td> <td>201</td> </tr> <tr> <td></td> <td>203</td> </tr> </tbody> </table> 1. **Read the data file.** - For each object, read and hash the surrogate. Pre-assign an OID to the object, and make an entry in both the sequential id map and in the id map hash-partitioned on surrogate. - For each relationship described with the object, hash the surrogate for the relationship and make an entry in the appropriate partition of a todo list. Each todo entry contains the OID just pre-assigned to the object, the surrogate to look up, and an offset indicating where to store it. The todo list is hash-partitioned by surrogate, using the same hash function as the id map. - If the relationship has an inverse, hash the surrogate for the relationship and make an entry on an inverse todo list, indicating that the inverse object should be updated to contain the OID of this object. Each inverse todo entry contains a surrogate for the object to update, the OID to store in that object, and an offset indicating where to store it. The inverse todo list is also hash-partitioned by surrogate, using the same hash function as the id map. The buffer pool size determines the number of partitions of the id map. Since there must be a corresponding todo list partition and inverse todo list partition for each id map partition, the number of partitions is no more than the number of pages in the buffer pool divided by 3. Figure 7 shows the todo list constructed for the example data file, with 2 partitions. The id map and the inverse todo list are the same as for the basic algorithm, shown in Figures 3 and 4, except that they are now partitioned as shown in Figures 6 and 8. 2. Repartition the id map as necessary. If any of the id map partitions is too large to fit in memory, split that partition and the corresponding todo list and inverse todo list partitions by further hashing on the surrogates. Repeat until all id map partitions can (individually) fit in memory, which is necessary for building the hash table in the following step. 3. Join the todo and inverse todo lists with the id map to create the update list. Join one partition at a time. - Build a hash table on the entries in the id map partition in virtual memory. - For each entry in the todo list partition, probe the hash table for its surrogate. Make an entry on the update list containing the OID of the object to update (taken from the todo entry), the OID to store in the object (just retrieved from the hash table), and the offset (from the todo entry). - For each entry in the inverse todo list partition, probe the hash table for its surrogate. Make an entry on the update list containing the OID of the object to update (just retrieved from the hash table), the OID to store in the object (taken from the inverse todo entry), and the offset (from the inverse todo entry). Note that all entries on the update list look alike, regardless of whether they were originally on the todo or inverse todo list. 4. Sort the update list. - As the update entries are generated in step 3, sort them by OID of the object to update and write them out in sorted runs. In this step, use an external merge sort to merge the sorted runs. As in the basic algorithm, postpone the final merge pass until the last step. 5. Read the data file again and create the database. - For each object, look up its surrogate in the sequential id map and retrieve the OID that has been assigned to it. - For each non-relationship attribute of the object, store it in the object. - For each update entry in the sorted update list that updates this object, read the entry and store the appropriate OID in the object. The final merge pass of sorting the update list happens as the update entries are needed. - Create the object with the storage manager now that the in-memory representation is complete. Note that since the sequential id map entries are read in the same order in which they are generated, it is only necessary to store the OID in each entry, and not the corresponding surrogate. Each data structure used by the load is now being written and read exactly once, in sequential order. There is very little random I/O being performed on behalf of the algorithm, because there is no longer random access to any load data structure. 4 Implementation We implemented all of the algorithms in C++. The database was stored under the Shore storage manager [CDF+94]. We used the Shore persistent object manager, even though it is still under development, for two reasons. First, Shore provides the notion of a “value-added server” (VAS), which allowed us to place the load utility directly in the server. Second, Shore provides logical OIDs, which allowed us to pre-assign OIDs. Each list or list partition (e.g., each partition of the id map in the new algorithm) was stored as a single large object in Shore. We used a Hewlett-Packard 9000/720 with 32 megabytes of physical memory to run all of the algorithms. However, due to operating system and daemon memory requirements, we were only able to use about 16 Mb for any test run. The database volume was a 2 gigabyte Seagate ST-12400N disk controlled exclusively by Shore. The data file resided on a separate disk and thus did not interfere with the database I/O. For these tests, we turned logging off, as would be expected in a load utility [Moh93a]. 5 Performance tests We ran a series of performance tests to show how quickly (or slowly!) each algorithm could load different size data sets. In this section, we will use the names in Table 1 to refer to each algorithm. <table> <thead> <tr> <th>Algorithm</th> <th>Major data structures</th> <th>Described in</th> </tr> </thead> <tbody> <tr> <td>naive</td> <td>in-memory hash table id map</td> <td>Section 3.1</td> </tr> <tr> <td></td> <td>immediate inverse updates</td> <td></td> </tr> <tr> <td>in-mem</td> <td>in-memory hash table id map</td> <td>Section 3.2</td> </tr> <tr> <td></td> <td>inverse todo list</td> <td></td> </tr> <tr> <td>btree</td> <td>B⁺-tree id map</td> <td>Section 3.3</td> </tr> <tr> <td></td> <td>inverse todo list</td> <td></td> </tr> <tr> <td>cache</td> <td>B⁺-tree plus cache id map</td> <td>Section 3.4</td> </tr> <tr> <td></td> <td>inverse todo list</td> <td></td> </tr> <tr> <td>partitioned</td> <td>partitioned list id map</td> <td>Section 3.5</td> </tr> <tr> <td>-list</td> <td>todo and inverse todo lists</td> <td></td> </tr> </tbody> </table> Table 1: Algorithm names used in performance graphs. 5.1 Data sets loaded For the performance experiments we created 200 byte objects. The schema for each object contained ten bidirectional relationships. In the data file, we listed five relationships with each object. Each object also contained an average of five relationships that were listed with the inverse object, but stored in both objects. (For the final set of experiments, we explicitly listed all ten relationships with each object and had no inverses in the schema.) We varied the number of objects to control the size of the database; each data set had 5000 objects per megabyte (Mb) of data. The data files were approximately one-third as large as the data sets they described, e.g., the data file for the 100 Mb data set was 36 Mb. We modeled a high degree of locality of reference among the objects for most of the experiments. In the data sets with a high degree of locality, 90% of relationships from an object are to other objects within 10% of it in the data file (and hence the database). The remaining 10% of the relationships are to other objects chosen at random from the entire database. We believe that a high degree of locality models a database clustered by complex object. For a few experiments, we also modeled no locality of reference. In those data sets, all relationships are to objects chosen at random. 5.2 Performance results 5.2.1 Comparing algorithms with different classes of data set sizes ![Graphs showing performance comparison](image) Figure 9: Comparing algorithms across different classes of data set sizes. For the first set of experiments, we compared the performance of naive, in-mem and partitioned-list. We held the buffer pool size constant at 4 Mb, and varied the size of the data set being loaded from 5 Mb to 200 Mb. Each algorithm used some transient heap memory in addition to the buffer pool. Naive and in-mem allocate the id map in virtual memory. With the 5 Mb data set, the id map was 0.4 Mb; with the 100 Mb data set it was 12.5 Mb. In general, the size of the id map was 7-13% of the data set size. As the data set size increases, so does the amount of memory used by naive and in-mem; the total amount of memory each used was the size of the buffer pool plus the size of the id map. Partitioned-list creates a full page of data for each id map, todo list, and inverse todo list partition in memory before it sends that page to the storage manager. This minimizes the number of calls to the storage manager and reduces the rate of pinning and unpinning of pages and objects in the buffer pool, but it requires roughly as many pages of heap memory as there are pages in the buffer pool. The total amount of memory required by partitioned-list is therefore twice the size of the buffer pool. Therefore, for the smallest class of data set sizes, the partitioned-list algorithm used more memory than the other algorithms. However, with a 4 Mb buffer pool, naive and in-mem were already using more memory to load the 60 Mb data set: they used 10.3 Mb while partitioned-list used only 8 Mb. Figure 9(a) shows the wall clock time for the naive, in-mem, and partitioned-list algorithms as we loaded data sets of 2 to 200 Mb. Figures 9(b) and 9(c) show the number of I/Os that were performed by the same experiments: 9(b) depicts the number of I/Os in the buffer pool, and 9(c) depicts the number of I/Os performed as virtual memory is swapped in and out of physical memory. (We measured the virtual memory page swaps with the `getrusage` system call; Shore provided the buffer pool I/O statistics.) We show the partitioned-list algorithm above for comparison and discuss it in more detail in the next section. The naive algorithm performs comparably to the in-mem algorithm on the 2 Mb data set when nearly the entire data set fits in the 4 Mb buffer pool: they complete the load in 19.6 and 19.0 seconds, respectively. However, as the data set size increases, naive starts thrashing as it tries to bring the inverse relationship objects into the buffer pool, as is clear from the correlation between the wall clock time and the buffer pool I/Os. At 5 Mb, naive is already taking 5 times as long to load: 276 vs. 51 seconds. Naive’s performance is so poor because the buffer pool must randomly read and write an object for each inverse update. By the 60 Mb data set, naive is over an order of magnitude worse than in-mem, taking over 10 hours to load while in-mem finishes in 15 minutes. Naive is clearly unsuitable for loading once the data set exceeds the size of the buffer pool. The in-mem algorithm performs quite well — the best — until the id map no longer fits in physical memory. For the 80 Mb data set, the id map still fits in physical memory. As the id map grows for the data sets between 100 and 160 Mb, it no longer fits in physical memory, and the load time for in-mem becomes proportional to the number of I/Os performed for virtual memory page swaps. By the 180 Mb data set, the id map is 25 Mb and virtual memory begins to thrash so badly that the load cannot complete at all. In fact, in over 4 hours, in-mem had completed less than 10% of step 1 of the algorithm. (In-mem loaded the entire 160 Mb data set in under 3 hours.) We therefore recommend that in-mem be used only when there is plenty of physical memory for the id map. In-mem is better than partitioned-list when the id map does fit in memory because it writes neither the id map nor a todo list to disk. This performance gap could be narrowed by using a hybrid hash join [Sha86]. in the partitioned-list algorithm instead of the standard Grace hash join [Kea83] to join the id map, todo list, and inverse todo lists. However, it would only save writing the id map to disk; the todo list (which is not needed by in-mem) would still be written to disk. 5.2.2 Comparing viable algorithms for loading large data sets with very little memory ![Graphs comparing algorithms for loading data sets with very little memory available.](image) Figure 10: Comparing algorithms for loading data sets with very little memory available. In-mem is simply not a viable algorithm when the size of the id map, which depends on the number of objects to be loaded, exceeds the size of memory. However, both modifications to the in-mem algorithm place the id map in the buffer pool, and allow the storage manager to handle paging it in and out of physical memory. Therefore, the amount of physical memory required remains constant. We now compare the modified algorithms, btree and cache, to partitioned-list. As we noted in the previous section, partitioned-list used both the 4 Mb buffer pool and an equal amount of transient memory, for a total of 8 Mb. Cache used both the buffer pool and an in-memory cache of the id map. We therefore allocated a 4 Mb cache as well as the 4 Mb buffer pool, so that cache also used 8 Mb of physical memory. \( B^+ \)-tree had no transient memory requirements; therefore, to be fair in terms of total memory allocated, we tested the \( B^+ \)-tree algorithm with an 8 Mb buffer pool. Figure 10 shows the wall clock time, CPU time, and number of buffer pool I/Os incurred by the btree, cache, and partitioned-list algorithms to load data sets of 5 to 500 Mb. (We were unable to load more than 500 Mb due to disk space limitations.) Partitioned-list is clearly the best algorithm; it loaded all of the data sets in the least amount of wall clock time and CPU time, with the fewest number of I/Os. However, although the number of I/Os scales linearly with increasing data set sizes, the CPU time (and hence the wall clock time) does not. This is due to a bug in the page allocation routine of the Shore storage manager which has since been fixed.\(^2\) Comparing \(^2\)Preliminary tests with the bug fix show linear CPU time, so that, e.g., partitioned-list finishes loading the 500 Mb data set We expected the btree algorithm to begin paging the id map once the size of the id map exceeded the buffer pool. Yet it is not until loading the 180 MB data set that the btree algorithm begins to pass in the buffer pool. The wall clock time to the CPU time for partitioned-list reveals that approximately 75% of the wall clock time is CPU time. This is due to two factors. First, a background thread writes the dirty pages of the id map into the buffer pool and completes the I/O. The btree algorithm is competitive with partitioned-list but performs better because it has twice as large a buffer pool in which to keep pages of the id map resident. (The cache algorithm has less space to hold the data.) Once the cache algorithm is more than 75% full, the buffer pool is flushed through the btree. Then the btree algorithm is better because it has more space to store the data. However, this advantage is offset by the fact that the id map is larger than the cache. Even when the desired page resides in the buffer pool, the btree algorithm is better because it has faster access. The cache algorithm is faster than the btree algorithm when the id map is in memory. Figure 11: Comparing the sensitivity of the btree and partitioned-list algorithms to the locality of reference in the data set. without excessive paging in the buffer pool. First, surrogates are assigned sequentially in our test data files, so two objects listed consecutively in a data file have consecutive surrogates. Second, a high locality of reference means that most of the lookups will be for surrogates sequentially close to that of the referencing object. Third, a clustered B⁺-tree index means that sequentially similar keys (surrogates) will be in nearby entries. Therefore, for the above data sets, keeping the nearest 20% of the id map in the buffer pool suffices to satisfy 90% of the id map lookups. 20% of the id map for the 160 Mb data set is only 7 Mb, and fits easily in the 8 Mb buffer pool. Loading some data sets with no locality of reference validated this theory, and we show the results in Figure 11. There was no difference in the partitioned-list algorithm when loading data sets with and without locality of reference; the times appear to overlap each other on the graph. The btree algorithm, by contrast, was very sensitive. As soon as the entire id map did not fit in the buffer pool, the btree algorithm began thrashing as we originally predicted. This happened at the 40 Mb data set, when the id map was approximately 10 Mb, and got worse for larger data sets. It is interesting to note that there is very little extra CPU overhead to fetch a non-resident page; most of the CPU time is spent on concurrency control inside the buffer pool, which happens whether or not the page must first be (expensively) fetched from disk. ![Graphs](image) Figure 12: Comparing algorithms when there are no inverse relationships. ### 5.2.3 Comparing large data set algorithms when there are no inverse relationships Although all of the major commercial OODB vendors support inverse relationships, many object-relational DBs do not (e.g., Illustra [Ube94] and UniSQL [Kim94]) and/or users may choose not to use them. As a final comparison of the algorithms for handling large data sets, we altered the data file to explicitly list all ten relationships from each object and removed the inverse relationships from the schema. We ran both partitioned-list and btree, as well as a version of naive, identified as naive-btree, that was adapted to use a B+tree id map instead of keeping the id map in memory. Figure 12 shows the results. Naive-btree and btree are nearly indistinguishable on the graphs (btree is actually 5-6% faster). The major difference between them, their handling of inverse relationships, has been removed. However, partitioned-list is clearly still an order of magnitude faster than both of them, completing the load of 80 Mb in less than 1 hour while btree takes over 11 hours. 5.2.4 Discussion When the id map fits in memory, partitioned-list, our new algorithm, is less than twice the cost of in-mem, which does not create a todo list nor write the id map to disk. Using hybrid hash join instead of Grace hash join to join the id map with the todo list and inverse todo list would eliminate the extra cost of writing the id map and narrow the gap, but the todo list would still be written. When the id map does not fit in memory, in-mem is simply inviable, first because it thrashes virtual memory and then because it runs out of swap space. Partitioned-list is an order of magnitude better than either btree or cache, the other algorithms that can deal with an id map that does not fit in memory. Without locality of reference in the data set, partitioned-list completed 16 times faster than btree on a 60 Mb data set! Even when there are no inverse relationships in the schema, e.g., in object-relational databases such as Illustra [Ube94] and UniSQL [Kim94], partitioned-list is an order of magnitude faster. By eliminating all random accesses to data structures, and by writing and reading each data item exactly once, we achieve linear I/O costs for partitioned-list in the size of the data set. For a system that needs to handle very large loads, e.g., gigabytes of data, and does not have gigabytes of memory, we recommend partitioned-list as the best algorithm to implement. 6 Resumable load From the above performance results, it is clear that loading gigabytes and terabytes takes hours. Losing all of the first ten hours of a load due to a system crash would be extremely undesirable. Rather, we would like to be able to resume the load after the system recovers, and to resume it close to where it was at the time of the crash. It is also desirable to resume a load that was stopped for other reasons, e.g., to use all of the CPU power for an urgent query, or because disk space was temporarily unavailable. Furthermore, we wish to resume a load without requiring logging of the newly loaded data, and without undoing most of the load before restarting. Therefore, the best solution for resuming a load is to periodically take a restart checkpoint: to commit the current state of the load and save persistent information that indicates where and how to resume the load from this checkpoint. In this section we discuss how to adapt the partitioned-list algorithm presented in Section 3.5 to make it resumable. We identify the specific information to save during a restart checkpoint and discuss how to resume the partitioned-list algorithm from a given checkpoint. 6.1 Restart checkpoint records Whenever a restart checkpoint is taken, it is necessary to flush all partitions and lists from memory to the buffer pool, and then flush the dirty pages of the buffer pool to disk. Then a restart checkpoint record containing the necessary information is written and also flushed to disk. Flushing the buffer pool ensures that the state of the load as of the checkpoint can be recovered from disk after a crash. Teradata also flushes all loaded data to disk when taking a resumable load checkpoint [WCK93]. For each step of our partitioned-list load algorithm, we now summarize the action of the step, describe when a checkpoint is permitted, what to write in the checkpoint record, and how to use the checkpoint record information to resume the load. 1. Read the data file and create the sequential id map, id map partitions, todo list partitions, and inverse todo list partitions. A restart checkpoint is permitted between reading any two objects. After the Nth object, record the current position in the data file, the sequential id list, and each id map, todo list, and inverse todo list partition. When resuming a load at this checkpoint, discard all entries in the above lists and partitions after the recorded positions. Then continue by reading the \((N + 1)\)th object from the data file. 2. Join the id map, one partition at a time, with the todo list and inverse todo list to create the update list. A restart checkpoint is permitted at any time. Record which partition is being joined, and the current position in either the todo or inverse todo list (whichever is being joined at the time). Record the current end of the update list. When resuming a load from this checkpoint, first rebuild the hash table on the id map partition. Discard all update entries after the recorded point in the update list. Then continue reading the todo or inverse todo list and joining it with the id map. Note that taking a checkpoint terminates a sorted run of the update list; very frequent checkpoints may generate more runs to merge than would otherwise be created. 3. Merge sorted runs of the update list until only one merge pass remains. A restart checkpoint is permitted at any time. Record which runs are being merged, the location of the next entry to merge in each run, and the end of the new merged run. To resume, discard all entries in the merged run after the recorded point, and all entries in subsequent merged runs. Resume merging from the recorded points in each sorted run. 4. Read the data file and sequential id map, perform the final merge pass of the update list and create the database objects. A restart checkpoint is permitted between creating any two objects. Record the current position in the data file, sequential id map, and each sorted run of the update list. Record the OID of the last created object. Resuming from a checkpoint here is trickier; objects that were created after this checkpoint, but before the crash, cannot simply be “recreated.” They already exist and trying to create an object with the same OID would cause an error. However, if only part of an object (spread across multiple pages) was written to disk, then the entire object is invalid. It is therefore necessary to remove the objects created after the checkpoint and recreate them. However, the objects cannot simply be deleted because that would invalidate their OIDs, which we are already using to reference those objects. We recommend truncating the objects to zero length instead. Resume reading the data file, sequential id map, and update list from their respective recorded points. For each object, try to read the object with the corresponding OID from the database. If the object is found, first truncate it, then update it with the correct data. When an object is not found, resume normal loading with creating that object. As we indicate in each step above, a checkpoint can be taken at virtually any time during the load. However, there is a tradeoff between taking frequent checkpoints (and losing little work) and occasional checkpoints (and avoiding the overhead of flushing the buffer pool). Some balance between the two should be struck. 7 Conclusions A bulk loading utility is critical to users of OODBs with significant amounts of data. Loading new data is a bottleneck in object-oriented applications; however, it need not be. In this performance study we showed that even when less than 1% of the data fits in memory, good performance can still be achieved. The key lies in minimizing the number of random accesses to both the database and any other secondary storage data structures. In this paper we developed algorithms to load a data set so large that its id map cannot fit in physical memory. We believe that many scientific data and legacy data sets fit in this category. We presented a new algorithm, partitioned-list, in which we were able to eliminate random data accesses by writing the id map out to disk as a persistent list, and then using a hash join to perform lookups on the id map. This fundamental change allowed the algorithm to scale gracefully with increasing data sizes, instead of spending all its time bringing needed id map pages into memory once the id map (as either a virtual memory structure or as a persistent B+-tree) no longer fit in physical memory. Our new algorithm also incorporates techniques for efficiently handling inverse relationships. We note that a load utility must be able to turn off the automatic maintenance of inverse relationships for the duration of the load. Otherwise, the load utility can do no better than a naive algorithm, i.e. orders of magnitude worse than a clever algorithm for handling inverse relationships. However, the partitioned-list algorithm achieves another order of magnitude performance improvement on top of that for handling inverse relationships due to its handling of the id map lookups. This performance gain occurs even in data whose relationships have no inverses. We also presented a resumable load algorithm. We described both what to write in a checkpoint record for the partitioned-list algorithm and how to resume the algorithm from the last checkpoint. Restart checkpoints allow a single load transaction to be paused and resumed many times, for any reason, with a minimal loss of work. Our future work includes looking at techniques for loading new objects which share relationships with existing objects in the database. Specifically, we are investigating when to retrieve such objects from the database and when to update them to maximize both concurrency and loading speed. We also plan to investigate algorithms for loading objects in parallel on one or more servers with multiple database volumes. In addition, we are integrating the load implementation with the higher levels of Shore and turning it into a utility to be distributed with a future release of Shore. 8 Acknowledgements We would like to thank S. Sudarshan for suggesting that the id map lookups could be seen as a join, and C. Mohan and Nancy Hall for discussion of our resumable load ideas. We also want to thank Mike Zwilling and C. K. Tan for many hours of discussion and support for our implementation as a Shore value-added server, and Mark McAuliffe for many helpful suggestions regarding both our implementation and this paper. References
{"Source-Url": "http://ilpubs.stanford.edu:8090/111/1/1995-42.pdf", "len_cl100k_base": 12256, "olmocr-version": "0.1.50", "pdf-total-pages": 25, "total-fallback-pages": 0, "total-input-tokens": 60629, "total-output-tokens": 14487, "length": "2e13", "weborganizer": {"__label__adult": 0.0003266334533691406, "__label__art_design": 0.0003962516784667969, "__label__crime_law": 0.0003566741943359375, "__label__education_jobs": 0.0012969970703125, "__label__entertainment": 0.00010311603546142578, "__label__fashion_beauty": 0.00019860267639160156, "__label__finance_business": 0.0004377365112304687, "__label__food_dining": 0.0003228187561035156, "__label__games": 0.0007143020629882812, "__label__hardware": 0.001949310302734375, "__label__health": 0.0005784034729003906, "__label__history": 0.00038743019104003906, "__label__home_hobbies": 0.00012826919555664062, "__label__industrial": 0.0006232261657714844, "__label__literature": 0.0003159046173095703, "__label__politics": 0.000247955322265625, "__label__religion": 0.0004875659942626953, "__label__science_tech": 0.1671142578125, "__label__social_life": 9.083747863769533e-05, "__label__software": 0.0285491943359375, "__label__software_dev": 0.79443359375, "__label__sports_fitness": 0.00022614002227783203, "__label__transportation": 0.0005230903625488281, "__label__travel": 0.00019049644470214844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 58767, 0.03957]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 58767, 0.43947]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 58767, 0.91261]], "google_gemma-3-12b-it_contains_pii": [[0, 2593, false], [2593, 5584, null], [5584, 8227, null], [8227, 10486, null], [10486, 12646, null], [12646, 14306, null], [14306, 16800, null], [16800, 18902, null], [18902, 21475, null], [21475, 24365, null], [24365, 26932, null], [26932, 28361, null], [28361, 30786, null], [30786, 33639, null], [33639, 35649, null], [35649, 38818, null], [38818, 41152, null], [41152, 42447, null], [42447, 44577, null], [44577, 47339, null], [47339, 50139, null], [50139, 52715, null], [52715, 55377, null], [55377, 58278, null], [58278, 58767, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2593, true], [2593, 5584, null], [5584, 8227, null], [8227, 10486, null], [10486, 12646, null], [12646, 14306, null], [14306, 16800, null], [16800, 18902, null], [18902, 21475, null], [21475, 24365, null], [24365, 26932, null], [26932, 28361, null], [28361, 30786, null], [30786, 33639, null], [33639, 35649, null], [35649, 38818, null], [38818, 41152, null], [41152, 42447, null], [42447, 44577, null], [44577, 47339, null], [47339, 50139, null], [50139, 52715, null], [52715, 55377, null], [55377, 58278, null], [58278, 58767, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 58767, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 58767, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 58767, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 58767, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 58767, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 58767, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 58767, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 58767, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 58767, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 58767, null]], "pdf_page_numbers": [[0, 2593, 1], [2593, 5584, 2], [5584, 8227, 3], [8227, 10486, 4], [10486, 12646, 5], [12646, 14306, 6], [14306, 16800, 7], [16800, 18902, 8], [18902, 21475, 9], [21475, 24365, 10], [24365, 26932, 11], [26932, 28361, 12], [28361, 30786, 13], [30786, 33639, 14], [33639, 35649, 15], [35649, 38818, 16], [38818, 41152, 17], [41152, 42447, 18], [42447, 44577, 19], [44577, 47339, 20], [47339, 50139, 21], [50139, 52715, 22], [52715, 55377, 23], [55377, 58278, 24], [58278, 58767, 25]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 58767, 0.13531]]}
olmocr_science_pdfs
2024-11-29
2024-11-29
2970c5a0eb41d8a97956ba20c2313590dac06f1f
[REMOVED]
{"len_cl100k_base": 9227, "olmocr-version": "0.1.53", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 39805, "total-output-tokens": 11010, "length": "2e13", "weborganizer": {"__label__adult": 0.0007276535034179688, "__label__art_design": 0.0006651878356933594, "__label__crime_law": 0.0005936622619628906, "__label__education_jobs": 0.0015287399291992188, "__label__entertainment": 0.0001455545425415039, "__label__fashion_beauty": 0.00032258033752441406, "__label__finance_business": 0.0004224777221679687, "__label__food_dining": 0.0006117820739746094, "__label__games": 0.0019121170043945312, "__label__hardware": 0.003551483154296875, "__label__health": 0.0010747909545898438, "__label__history": 0.0006551742553710938, "__label__home_hobbies": 0.00017559528350830078, "__label__industrial": 0.001262664794921875, "__label__literature": 0.0006561279296875, "__label__politics": 0.0003707408905029297, "__label__religion": 0.000774383544921875, "__label__science_tech": 0.199462890625, "__label__social_life": 0.00013947486877441406, "__label__software": 0.01120758056640625, "__label__software_dev": 0.767578125, "__label__sports_fitness": 0.0005688667297363281, "__label__transportation": 0.005191802978515625, "__label__travel": 0.0003650188446044922}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50861, 0.02359]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50861, 0.50273]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50861, 0.90299]], "google_gemma-3-12b-it_contains_pii": [[0, 3250, false], [3250, 8573, null], [8573, 11057, null], [11057, 14373, null], [14373, 17888, null], [17888, 21782, null], [21782, 23560, null], [23560, 26505, null], [26505, 31237, null], [31237, 34159, null], [34159, 36530, null], [36530, 36730, null], [36730, 38971, null], [38971, 40292, null], [40292, 42866, null], [42866, 47592, null], [47592, 50861, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3250, true], [3250, 8573, null], [8573, 11057, null], [11057, 14373, null], [14373, 17888, null], [17888, 21782, null], [21782, 23560, null], [23560, 26505, null], [26505, 31237, null], [31237, 34159, null], [34159, 36530, null], [36530, 36730, null], [36730, 38971, null], [38971, 40292, null], [40292, 42866, null], [42866, 47592, null], [47592, 50861, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50861, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50861, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50861, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50861, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50861, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50861, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50861, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50861, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50861, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50861, null]], "pdf_page_numbers": [[0, 3250, 1], [3250, 8573, 2], [8573, 11057, 3], [11057, 14373, 4], [14373, 17888, 5], [17888, 21782, 6], [21782, 23560, 7], [23560, 26505, 8], [26505, 31237, 9], [31237, 34159, 10], [34159, 36530, 11], [36530, 36730, 12], [36730, 38971, 13], [38971, 40292, 14], [40292, 42866, 15], [42866, 47592, 16], [47592, 50861, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50861, 0.0]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
78678ab425757211a0f1f645f9bcdc5482e60ae5
Number Systems and Data Structures RALF HINZE Institut für Informatik III, Universität Bonn Römerstraße 164, 53117 Bonn, Germany Email: ralf@informatik.uni-bonn.de Homepage: http://www.informatik.uni-bonn.de/~ralf March, 2005 (Pick up the slides at .../~ralf/talks.html#T40.) An analogy Natural numbers (aka Peano numerals, unary numbers etc): \[ \text{data } \text{Nat} = \text{Zero} \mid \text{Succ Nat} \] \[ \text{plus} :: \text{Nat} \to \text{Nat} \to \text{Nat} \] \[ \text{plus Zero } n_2 = n_2 \\ \text{plus (Succ } n_1) n_2 = \text{Succ (plus } n_1 n_2) \] Lists (aka stacks, sequences etc): \[ \text{data } \text{List } \alpha = \text{Nil} \mid \text{Cons } \alpha (\text{List } \alpha) \] \[ \text{append} :: \forall \alpha . \text{List } \alpha \to \text{List } \alpha \to \text{List } \alpha \] \[ \text{append Nil } x_2 = x_2 \\ \text{append (Cons a } x_1) x_2 = \text{Cons a (append } x_1 x_2) \] There is a strong analogy between representations of numbers \((n)\) and representations of container objects (of size \(n\)). Data structures that are designed on the basis of this analogy are called numerical representations. Idea: the data structure inherits the properties of the number system. The operations on the data structure are modelled after their numerical counterparts. <table> <thead> <tr> <th>Operation</th> <th>Formula</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>Increment</td> <td>( n + 1 )</td> <td>Insertion into a container</td> </tr> <tr> <td>Decrement</td> <td>( n - 1 )</td> <td>Deletion from a container</td> </tr> <tr> <td>Addition</td> <td>( n_1 + n_2 )</td> <td>Union or merge of two container objects</td> </tr> </tbody> </table> This design technique is suitable for implementing arbitrary abstractions: sequences, priority queues, sets etc. The numerical representations we shall introduce are fully persistent: updates ever destroy the original data structure. ### Numerical representations—continued <table> <thead> <tr> <th>Arithmetic shift</th> <th>$n \cdot b$</th> <th>we shall see</th> </tr> </thead> <tbody> <tr> <td>Multiplication</td> <td>$n / b$</td> <td></td> </tr> <tr> <td>Division</td> <td>$n \cdot k$</td> <td></td> </tr> <tr> <td>Number conversion</td> <td>$n / k$</td> <td></td> </tr> <tr> <td></td> <td></td> <td>split of a container object</td> </tr> <tr> <td></td> <td></td> <td>construction of a container object</td> </tr> <tr> <td></td> <td></td> <td>conversion between different container types</td> </tr> </tbody> </table> History Some material is taken from Okasaki’s book, which I highly recommend. Outline of the talk ✖ Exploring the analogy (7–27) ✖ A toolbox of number systems (29–41) ✖ Analysis of data structures (43–51) ✖ A worked-out example: 2-3 finger trees (53–64) Random-access lists Lists are based on the unary number system; random-access lists are based on the binary number system. \[ \text{data } \text{Seq } \alpha = \text{Nil} \\ | \quad \text{Zero } ( \text{Seq } (\alpha, \alpha)) \\ | \quad \text{One } (\alpha, \text{Seq } (\alpha, \alpha)) \] The type of elements changes from position to position: the top-level possibly contains an element of type \( \alpha \), the next of type \((\alpha, \alpha)\), the next of type \(((\alpha, \alpha), (\alpha, \alpha))\) and so on. In other words, \( n \times 2 \) corresponds to pairing. \( \text{Seq} \) is an example of a non-regular or nested data type. Random-access lists—examples Nil One (11, Nil) Zero (One ((10, 11), Nil)) One (9, One ((10, 11), Nil)) Zero (Zero (One (((8, 9), (10, 11)), Nil))) One (7, Zero (One (((8, 9), (10, 11)), Nil))) Zero (One ((6, 7), One (((8, 9), (10, 11)), Nil))) One (5, One ((6, 7), One (((8, 9), (10, 11)), Nil))) Zero (Zero (Zero (One (((4, 5), (6, 7)), ((8, 9), (10, 11))), Nil)))) One (3, Zero (Zero (One (((4, 5), (6, 7)), ((8, 9), (10, 11))), Nil)))) Zero (One ((2, 3), Zero (One (((4, 5), (6, 7)), ((8, 9), (10, 11))), Nil)))) One (1, One ((2, 3), Zero (One (((4, 5), (6, 7)), ((8, 9), (10, 11))), Nil))))) Random-access lists—insertion Insertion corresponds to binary increment, except that the carry is explicit—the carry is witnessed by a container object of the appropriate size. \[ \text{cons} \quad :: \quad \forall \alpha . \ (\alpha, \text{Seq} \ \alpha) \rightarrow \text{Seq} \ \alpha \] \[ \begin{align*} \text{cons} \ (a, \text{Nil}) & = \text{One} \ (a, \text{Nil}) \\ \text{cons} \ (a, \text{Zero} \ x) & = \text{One} \ (a, x) \\ \text{cons} \ (a_1, \text{One} \ (a_2, x)) & = \text{Zero} \ (\text{cons} \ ((a_1, a_2), x)) \end{align*} \] \[\text{cons} \text{ requires a non-schematic form of recursion, called polymorphic recursion: the recursive call inserts a pair not an element.}\] \[\text{cons} \text{ runs in } \Theta(\log n) \text{ worst-case time.}\] Deletion corresponds to binary decrement, except that the borrow is explicit. \[ \text{uncons} \quad :: \quad \forall \alpha. \text{Seq} \alpha \rightarrow (\alpha, \text{Seq} \alpha) \] \[ \text{uncons} (\text{One} (a, \text{Nil})) = (a, \text{Nil}) \] \[ \text{uncons} (\text{One} (a, x)) = (a, \text{Zero} x) \] \[ \text{uncons} (\text{Zero} x) = \text{let } ((a_1, a_2), x) = \text{uncons} x \text{ in } (a_1, \text{One} (a_2, x)) \] \[\Rightarrow\] \text{uncons} is the mirror image of \text{cons}. \[ \text{cons} \quad :: \quad \forall \alpha. (\alpha, \text{Seq} \alpha) \rightarrow \text{Seq} \alpha \] \[ \text{cons} (a, \text{Nil}) = \text{One} (a, \text{Nil}) \] \[ \text{cons} (a, \text{Zero} x) = \text{One} (a, x) \] \[ \text{cons} (a_1, \text{One} (a_2, x)) = \text{Zero} (\text{cons} ((a_1, a_2), x)) \] Indexing corresponds to ...(well, it’s a bit like ‘\(\leq\)’). \[ \text{lookup} \\ \text{lookup 0 } (\text{One } (a, x)) = a \\ \text{lookup } (n + 1) (\text{One } (a, x)) = \text{lookup } n (\text{Zero } x) \\ \text{lookup } (2 \times n + 0) (\text{Zero } x) = \text{fst } (\text{lookup } n x) \\ \text{lookup } (2 \times n + 1) (\text{Zero } x) = \text{snd } (\text{lookup } n x) \] Container objects can be constructed in at least two different ways: - construct a container object containing \( n \) copies of a given element: \[ \text{replicate} :: \forall \alpha . \text{Integer} \rightarrow \alpha \rightarrow \text{Seq} \alpha \] - construct a container object from a given list of elements: \[ \text{toSeq} :: \forall \alpha . [\alpha] \rightarrow \text{Seq} \alpha \] Often, the former operation can be implemented more efficiently. In both cases, construction corresponds to conversion of number representations: here from the unary to the binary number system. Conversion of number representations There are at least two ways to convert a number in one system to the equivalent number in another system: ► use the arithmetic of the target number system; this is sometimes called the expansion method; functions of this type are typically folds. ► use the arithmetic of the source number system; this is sometimes called the multiplication or division method; functions of this type are typically unfolds. Using the arithmetic of the target system (unary to binary): \[ \begin{align*} \text{replicate} & : \forall \alpha. \text{Integer} \to \alpha \to \text{Seq} \alpha \\ \text{replicate } 0 & = \text{Nil} \\ \text{replicate } (n + 1) a & = \text{cons} (a, \text{replicate } n a) \end{align*} \] replicate runs in $\Theta(n)$ worst-case time; it is not polymorphically recursive. Using the arithmetic of the source system (unary to binary): \[ \text{replicate} :: \forall \alpha. \text{Integer} \rightarrow \alpha \rightarrow \text{Seq} \alpha \] \[ \text{replicate } n \ a = \begin{cases} \text{Nil} & \text{if } n == 0 \\ \text{case } \text{modDiv } n \ 2 \ \text{of} \\ (0, q) \rightarrow \text{Zero} \left( \text{replicate } q \ (a, a) \right) \\ (1, q) \rightarrow \text{One} \left( a, \text{replicate } q \ (a, a) \right) \end{cases} \] \[\text{replicate} \ \text{runs in } \Theta(\log n) \ \text{worst-case time; it is polymorphically recursive.}\] Using the arithmetic of the target system (unary to binary): \[ \text{toSeq} :: \forall \alpha \cdot [\alpha] \rightarrow Seq \alpha \\ \text{toSeq} \ [\ ] = \text{Nil} \\ \text{toSeq} \ (a : x) = \text{cons} \ (a, \text{toSeq} \ x) \] \(\text{toSeq}\) runs in \(\Theta(n)\) worst-case time. \(\text{[\alpha]}\) is the built-in list data type, which is isomorphic to \(\text{List}\ \alpha\) (see page 2): \(\text{[\alpha]} \cong \text{List} \ \alpha\), \([\ ] \cong \text{Nil}\), and \(a : x \cong \text{Cons} \ a \ x\). Using the arithmetic of the source system (unary to binary): \[\text{data } \text{Digit } \alpha = \text{Zero'} | \text{One'} \alpha\] \[\text{modDiv2 } :: [\alpha] \rightarrow (\text{Digit } \alpha, [(\alpha, \alpha)])\] \[\text{modDiv2 } [] = (\text{Zero'}, [])\] \[\text{modDiv2 } (a : x) = \text{case } \text{modDiv2 } x \text{ of} \] \[\quad (\text{Zero'}, q) \rightarrow (\text{One'} a, q)\] \[\quad (\text{One'} a', q) \rightarrow (\text{Zero'}, (a, a') : q)\] \[\text{toSeq } :: \forall \alpha. [\alpha] \rightarrow \text{Seq } \alpha\] \[\text{toSeq } x = \text{if } \text{null } x \text{ then } \text{Nil}\] \[\quad \text{else } \text{case } \text{modDiv2 } x \text{ of} \] \[\quad\quad (\text{Zero'}, q) \rightarrow \text{Zero} (\text{toSeq } q)\] \[\quad\quad (\text{One'} a, q) \rightarrow \text{One} (a, \text{toSeq } q)\] \[\text{toSeq runs in } \Theta(n) \text{ worst-case time.}\] Exercises Exercise 1. Implement two versions of \[ \text{size} :: \forall \alpha . \text{Seq} \, \alpha \rightarrow \text{Integer} \] \[ \text{fromSeq} :: \forall \alpha . \text{Seq} \, \alpha \rightarrow [\alpha] \] and determine the worst-case running times (binary to unary). The container object that corresponds to ‘0’ contains no elements. This is wasteful! Interestingly, we can also use the digits 1 and 2 instead of 0 and 1 (the base is still 2). Each number has a unique representation in this system; this is a so-called zeroless number system. 1-2 random-access lists—examples Nil One (11, Nil) Two ((10, 11), Nil) One (9, One ((10, 11), Nil)) Two ((8, 9), One ((10, 11), Nil)) One (7, Two (((8, 9), (10, 11)), Nil)) Two ((6, 7), Two (((8, 9), (10, 11)), Nil)) One (5, One ((6, 7), One (((8, 9), (10, 11)), Nil))) Two ((4, 5), One ((6, 7), One (((8, 9), (10, 11)), Nil))) One (3, Two (((4, 5), (6, 7)), One (((8, 9), (10, 11)), Nil))) Two ((2, 3), Two (((4, 5), (6, 7)), One (((8, 9), (10, 11)), Nil))) One (1, One ((2, 3), Two (((4, 5), (6, 7)), ((8, 9), (10, 11))), Nil))) 1-2 random-access lists—insertion \[ \begin{align*} \text{cons} & \quad :: \ \forall \alpha . (\alpha, \text{Seq } \alpha) \rightarrow \text{Seq } \alpha \\ \text{cons } (a, \text{Nil}) & \quad = \ \text{One } (a, \text{Nil}) \\ \text{cons } (a_1, \text{One } (a_2, x)) & \quad = \ \text{Two } ((a_1, a_2), x) \\ \text{cons } (a_1, \text{Two } ((a_2, a_3), x)) & \quad = \ \text{One } (a_1, \text{cons } ((a_2, a_3), x)) \end{align*} \] 1-2 random-access lists—deletion Again, $\text{uncons}$ is the mirror image of $\text{cons}$. \[ \begin{align*} \text{uncons} & : \forall \alpha . \text{Seq} \alpha \rightarrow (\alpha, \text{Seq} \alpha) \\ \text{uncons} (\text{One} (a, \text{Nil})) & = (a, \text{Nil}) \\ \text{uncons} (\text{Two} ((a_1, a_2), x)) & = (a_1, \text{One} (a_2, x)) \\ \text{uncons} (\text{One} (a_1, x)) & = (a_1, \text{Two} (\text{uncons} x)) \end{align*} \] The term $\text{Two} (\text{uncons} x)$ corresponds to an arithmetic shift ($n \times 2$): \[ \begin{align*} \text{zero} & : \forall \alpha . \text{Seq} (\alpha, \alpha) \rightarrow \text{Seq} \alpha \\ \text{zero} x & = \text{Two} (\text{uncons} x) \end{align*} \] 1-2 random-access lists—conversion Using \textit{zero} we can easily convert a 0-1 random-access list into a 1-2 random-access list. \begin{align*} \text{toSeq} & :: \forall \alpha. \text{Seq}_{01} \alpha \rightarrow \text{Seq} \alpha \\ \text{toSeq} \; \text{Nil}_{01} & = \text{Nil} \\ \text{toSeq} \; (\text{Zero}_{01} \; x) & = \text{zero} \; (\text{toSeq} \; x) \\ \text{toSeq} \; (\text{One}_{01} \; (a, x)) & = \text{One} \; (a, \text{toSeq} \; x) \end{align*} This implementation uses the arithmetic of the target number system. Exercise 2. Implement a version of `toSeq` that uses the arithmetic of the source number system. Exercise 3. Re-implement indexing for 1-2 random-access lists and show that it has a running time of $\Theta(\log i)$ rather than $\Theta(\log n)$. If considered in isolation, insertion and deletion both have an amortised running time of $\Theta(1)$. If ‘cons’ and ‘uncons’ are mixed, however, the running time degrades to $\Theta(\log n)$. Consider: ``` decr (incr (222222)) ``` This can be remedied using a redundant number system, which employs, for instance, the digits 0, 1, and 2 (or alternatively the digits 1, 2, and 3): ``` data Seq α = Nil | Zero (Seq (α, α)) | One (α, Seq (α, α)) | Two ((α, α), Seq (α, α)) ``` 0-1-2 random-access lists—insertion We classify 0 and 2 as dangerous and 1 as safe; ‘cons’ and ‘uncons’ recurse on dangerous digits, but always leave a safe digit behind, so that the next operation to reach that digit will not propagate. ``` cons :: \(\forall \alpha . (\alpha, \text{Seq } \alpha) \to \text{Seq } \alpha\) cons \((a, \text{Nil})\) = One \((a, \text{Nil})\) cons \((a, \text{Zero } x)\) = One \((a, x)\) cons \((a_1, \text{One } (a_2, x))\) = Two \(((a_1, a_2), x)\) cons \((a_1, \text{Two } ((a_2, a_3), x))\) = One \((a_1, \text{cons } ((a_2, a_3), x))\) ``` uncons :: \(\forall \alpha . \text{Seq} \alpha \rightarrow (\alpha, \text{Seq} \alpha)\) \[ \begin{align*} \text{uncons} (\text{One} (a, \text{Nil})) &= (a, \text{Nil}) \\ \text{uncons} (\text{One} (a, x)) &= (a, \text{Zero} x) \\ \text{uncons} (\text{Two} ((a_1, a_2), x)) &= (a_1, \text{One} (a_2, x)) \\ \text{uncons} (\text{Zero} x) &= \text{let } ((a_1, a_2), x) = \text{uncons } x \text{ in } (a_1, \text{One} (a_2, x)) \end{align*} \] uncons is no longer the mirror image of cons. Outline of the talk ✔ Exploring the analogy (7–27) ✖ A toolbox of number systems (29–41) ✖ Analysis of data structures (43–51) ✖ A worked-out example: 2-3 finger trees (53–64) Positional number systems The most common number systems are positional number systems. \[ (d_0 \ldots d_{n-1}) = \sum_{i=0}^{n-1} d_i \cdot w_i \text{ with } d_i \in D_i. \] Unary number system: \( w_i = 1 \) and \( D_i = \{ 1 \} \) for all \( i \). Binary number system: \( w_i = 2^i \) and \( D_i = \{ 0, 1 \} \) for all \( i \). 1-2 binary system: \( w_i = 2^i \) and \( D_i = \{ 1, 2 \} \) for all \( i \). 0-1-2 binary system: \( w_i = 2^i \) and \( D_i = \{ 0, 1, 2 \} \) for all \( i \). Common building blocks - Complete leaf tree - Complete tree - Pennant - Binomial tree Common abstractions The most elementary operation is adding two 1s of weight $w_i$ to form a 1 of weight $w_{i+1}$. - **Sequences**: if we use leaf trees, adding two 1s amounts to pairing (adding a new root node), see above. - **Priority queues (bags)**: we can either use pennants (semi-heaps) or binomial trees (heaps). For the former, adding two 1s is given by \[ a \ominus b = \begin{cases} a \leq b & \text{if } a \leq b \\ a \geq b & \text{if } a > b \end{cases} \] - **Sets**: adding two 1s is difficult (if not impossible), since the keys in a search tree must be maintained in symmetric order, but see below. Ternary number systems Number systems with a larger base are often advantageous, because fewer digits are needed to represent each number. On the downside, processing a single digit may take longer. ``` data Seq α = Nil | Zero ( Seq (α, α, α)) | One (α, Seq (α, α, α)) | Two (α, α, Seq (α, α, α)) ``` ☞ We use triples instead of pairs. Ternary number systems—insertion \[\text{cons} :: \forall \alpha . \langle \alpha, \text{Seq} \alpha \rangle \to \text{Seq} \alpha\] \[\text{cons} (a, \text{Nil}) = \text{One} (a, \text{Nil})\] \[\text{cons} (a, \text{Zero } x) = \text{One} (a, x)\] \[\text{cons} (a_1, \text{One} (a_2, x)) = \text{Two} (a_1, a_2, x)\] \[\text{cons} (a_1, \text{Two} (a_2, a_3, x)) = \text{Zero} (\text{cons} ((a_1, a_2, a_3), x))\] Fibonacci number system: \( w_i = F_i \) and \( D_i = \{0, 1\} \) for all \( i \), where \[ \begin{align*} F_0 &= 1 \\ F_1 &= 2 \\ F_{n+2} &= F_n + F_{n+1} \end{align*} \] This number system is redundant: we have, for instance, \((11) = (001)\). However, if we disallow consecutive 1s, then we regain uniqueness. The fibonacci number system is a lot like the binary number system, except that it involves only addition and subtraction, not multiplication or division by 2. The following data type captures the invariant that the digit 1 is not followed by a second 1. \begin{verbatim} \textbf{type} \textit{Seq} \alpha = \textit{Fib} \alpha (\alpha, \alpha) \\ \textbf{data} \textit{Fib} \alpha \beta = \textit{Nil} \\ \quad \mid \textit{Zero} (\textit{Fib} \beta (\alpha, \beta)) \\ \quad \mid \textit{One} (\alpha, \textit{Fib} (\alpha, \beta) (\beta, (\alpha, \beta))) \end{verbatim} The \textbf{smart constructor} \textit{one} restores the invariant: \begin{verbatim} \textit{one} :: \forall \alpha \beta . (\alpha, \textit{Fib} \beta (\alpha, \beta)) \to \textit{Fib} \alpha \beta \\ \textit{one} (a, \textit{Nil}) = \textit{One} (a, \textit{Nil}) \\ \textit{one} (a, \textit{Zero} x) = \textit{One} (a, x) \\ \textit{one} (a, \textit{One} (b, x)) = \textit{Zero} (\textit{Zero} (\textit{one} ((a, b), x))) \end{verbatim} Fibonacci number system—insertion Insertion is easy to define using *one*: \[ \begin{align*} \text{cons} & : \forall \alpha. \alpha \to \text{Seq} \alpha \to \text{Seq} \alpha \\ \text{cons} a \ \text{Nil} & = \text{One} (a, \text{Nil}) \\ \text{cons} a \ (\text{Zero} \ x) & = \text{one} (a, x) \\ \text{cons} a \ (\text{One} \ (b, x)) & = \text{Zero} \ (\text{one} \ ((a, b), x)) \end{align*} \] The type *Fib* \(\alpha \beta\) is a bit inconvenient to work with because it has two type arguments. Factorial number system: \( w_i = i! \) and \( D_i = \{0, \ldots, i\} \) for all \( i \). Note that \( \sum_{i=0}^{n-1} i \cdot i! = n! - 1 \). **Application:** Given a sequence of elements, generate a random permutation. - generate a random number \( r \) with \( 0 \leq r \leq n! - 1 \); - convert \( r \) into the factorial number system: \((d_0 \ldots d_{n-1})\); - for \( i = 0 \) to \( n - 1 \): exchange elements at positions \( i \) and \( i + d_{n-1-i} \). <table> <thead> <tr> <th>0</th> <th>1</th> <th>2</th> <th>3</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> \[ 0 \leftrightarrow 0 \text{ or } 1 \text{ or } 2 \text{ or } 3 \\ 1 \leftrightarrow 1 \text{ or } 2 \text{ or } 3 \\ 2 \leftrightarrow 2 \text{ or } 3 \\ 3 \leftrightarrow 3 \] Skew binary number system: \( w_i = 2^{i+1} - 1 \) and \( D_i = \{0, 1, 2\} \) for all \( i \). Why \( 2^{i+1} - 1 \)? This is the size of perfect binary trees of height \( i + 1 \). Why \( D_i = \{0, 1, 2\} \)? Using \( \{0, 1, 2\} \) we cannot represent all numbers. This is a redundant number system, as well. However if we add the constraint that only the lowest non-zero digit may be 2, then we regain uniqueness. Salient properties: increment and decrement work in constant time. Skew binary number system—continued \[ data Tree \alpha = Leaf \alpha \mid Node \alpha (Tree \alpha) (Tree \alpha) \] We use a so-called \textbf{sparse representation} to be able to access the lowest non-zero digit in constant time. \[ type Size = Integer \] \[ data Seq \alpha = Nil \mid Cons (Size, Tree \alpha, Seq \alpha) \] \[ \text{cons} :: \forall \alpha. \alpha \rightarrow Seq \alpha \rightarrow Seq \alpha \] \[ \begin{align*} \text{cons } a & (\text{Cons} (n_1, t_1, \text{Cons} (n_2, t_2, x))) \\ | n_1 == n_2 & = \text{Cons} (1 + n_1 + n_2, \text{Node } a \ t_1 \ t_2, x) \\ \text{cons } a \ x & = \text{Cons} (1, \text{Leaf } a, x) \end{align*} \] More number systems . . . There is a lot more to discover: - lazy number systems: good amortised bounds even in a persistent setting; - segmented number systems: supports constant time deque operations; - combinatorial number system: fixed number of digits; - mixed-radix number systems: persistent arrays with sublogarithmic access; - . . . Exercises Exercise 5. Explore the 1-2 fibonacci number system. Exercise 6. Try to come up with a suitable definition of skew fibonacci numbers. Outline of the talk ✔ Exploring the analogy (7–27) ✔ A toolbox of number systems (29–41) ✖ Analysis of data structures (43–51) ✖ A worked-out example: 2-3 finger trees (53–64) Problem: We insert an ascending sequence of elements into an empty red-black tree. Which shape has the final tree? Recap: red-black trees Red-black trees were developed by R. Bayer under the name symmetric binary B-trees as binary tree representations of 2-3-4 trees. The idea of red-black trees is to represent 3- and 4-nodes by small binary trees, which consist of a black root and one or two auxiliary red children. **Red condition:** Each red node has a black parent. **Black condition:** Each path from the root to an empty node contains exactly the same number of black nodes (this is called the tree’s black height). Red-black trees: balancing ``` \begin{align*} &\begin{array}{c} \text{a}_3 \\ \text{a}_2 \\ \text{a}_1 \\ \text{t}_1 \quad \text{t}_2 \\ \end{array} \\ &\begin{array}{c} \text{t}_3 \\ \end{array} \\ &\begin{array}{c} \text{t}_4 \\ \end{array} \end{align*} ``` ``` \begin{align*} &\begin{array}{c} \text{t}_1 \\ \text{a}_1 \\ \text{t}_2 \\ \text{t}_3 \\ \end{array} \\ &\begin{array}{c} \text{a}_2 \\ \text{t}_4 \\ \end{array} \end{align*} ``` ``` \begin{align*} &\begin{array}{c} \text{t}_1 \\ \text{t}_2 \\ \text{t}_3 \\ \text{t}_4 \\ \end{array} \\ &\begin{array}{c} \text{a}_2 \\ \text{a}_1 \\ \text{a}_3 \\ \end{array} \end{align*} ``` ``` \begin{align*} &\begin{array}{c} \text{t}_1 \\ \text{t}_2 \\ \text{t}_3 \\ \text{t}_4 \\ \end{array} \\ &\begin{array}{c} \text{a}_2 \\ \text{a}_1 \\ \text{a}_3 \\ \end{array} \end{align*} ``` ``` \begin{align*} &\begin{array}{c} \text{t}_1 \\ \text{t}_2 \\ \text{t}_3 \\ \text{t}_4 \\ \end{array} \\ &\begin{array}{c} \text{a}_3 \\ \text{a}_2 \\ \text{a}_1 \\ \end{array} \end{align*} ``` ``` \begin{align*} &\begin{array}{c} \text{t}_1 \\ \text{t}_2 \\ \text{t}_3 \\ \text{t}_4 \\ \end{array} \\ &\begin{array}{c} \text{a}_3 \\ \text{a}_2 \\ \text{a}_1 \\ \end{array} \end{align*} ``` Examples The following trees are generated for $1 \leq i \leq 8$ (a new node is always coloured red). Insertion always traverses the left spine of the tree to the leftmost leaf. Observations All the nodes below the left spine are black. Re-consider the balancing operation—for emphasis we draw the left spine horizontally. The black condition implies that the trees below the left spine must be perfectly balanced. Thus, the generated red-black trees correspond to sequences of pennants. It is helpful to redraw the examples according to the left-spine view. Let $h$ be the height of the rightmost pennant; the black condition implies that a pennant of height $i$ appears either once or twice for all $0 \leq i \leq h$. ☞ The generated red-black trees correspond to binary numbers in the 1-2 number system. The analogy to the 1-2 number system can be exploited to construct red-black trees from ordered sequences of elements in linear time. \[ \text{data } \text{Tree } \alpha = \begin{array}{l} \text{Empty} \\ \text{Red } (\text{Tree } \alpha) \alpha (\text{Tree } \alpha) \\ \text{Black } (\text{Tree } \alpha) \alpha (\text{Tree } \alpha) \end{array} \] \[ \text{data } \text{Set } \alpha = \begin{array}{l} \text{Nil} \\ \text{One } (\alpha, \text{Tree } \alpha) (\text{Set } \alpha) \\ \text{Two } (\alpha, \text{Tree } \alpha) (\alpha, \text{Tree } \alpha) (\text{Set } \alpha) \end{array} \] We do not use a nested data type, so that we can easily transform the left-spine view into an ordinary red-black tree. Construction of red-black trees—continued \[ \begin{align*} \text{cons} & \colon \forall \alpha. (\alpha, \text{Tree } \alpha) \to \text{Set } \alpha \to \text{Set } \alpha \\ \text{cons} (a, t) \text{ Nil} & = \text{One } (a, t) \text{ Nil} \\ \text{cons} (a_1, t_1) (\text{One } (a_2, t_2) x) & = \text{Two } (a_1, t_1) (a_2, t_2) x \\ \text{cons} (a_1, t_1) (\text{Two } (a_2, t_2) (a_3, t_3) x) & = \text{One } (a_1, t_1) (\text{cons } (a_2, \text{Black } t_2 a_3 t_3) x) \end{align*} \] \[ \begin{align*} \text{insert} & \colon \forall \alpha. \alpha \to \text{Set } \alpha \to \text{Set } \alpha \\ \text{insert } a x & = \text{cons } (a, \text{Empty}) x \end{align*} \] Exercise 4. Repeat the analysis with 1-2 brother trees. Outline of the talk ✔ Exploring the analogy (7–27) ✔ A toolbox of number systems (29–41) ✔ Analysis of data structures (43–51) ✖ A worked-out example: 2-3 finger trees (53–64) A more symmetric design All the data structures we have seen so far are asymmetric: ► adding an element to the left end is easy and efficient; ► adding an element to the right end is difficult (if not impossible) and inefficient. ☞ 2-3 finger trees remedy the situation by using two digits per level, one for the left and one for the right end. (A finger provides efficient access to nodes of a tree near a distinguished location.) Finger trees are constructed from 2-3 nodes: \[ \text{data Node } \alpha = \text{Node2 } \alpha \alpha \mid \text{Node3 } \alpha \alpha \alpha \] 2-3 nodes contain two or three subtrees, but no keys; all data is stored in the leaves of the tree. Conventional 2-3 trees can be defined as follows: \[ data \text{ Tree } \alpha = \text{ Zero } \alpha \mid \text{ Succ } (\text{ Tree } (\text{ Node } \alpha)) \] A typical 2-3 tree: All leaves of a 2-3 tree are at the same depth, the left and right spines have the same length. 2-3 finger trees If we take hold of the end nodes of a 2-3 tree and lift them up together, we obtain a tree that looks like this: Each pair of nodes on the central spine is merged into a single node (called Deep). A sequence of $n$ elements is represented by a tree of depth $\Theta(\log n)$; an element $d$ positions from the nearest end is stored at a depth of $\Theta(\log d)$. Finger trees provide efficient access to both ends of a sequence: \[ data \text{FingerTree } \alpha = \text{Empty} \\ | \quad \text{Single } \alpha \\ | \quad \text{Deep } (\text{Digit } \alpha) (\text{FingerTree } (\text{Node } \alpha)) (\text{Digit } \alpha) \] The top level contains elements of type \(\alpha\), the next of type \(\text{Node } \alpha\), and so on: the \(n\)th level contains elements of type \(\text{Node}^n \alpha\), namely 2-3 trees of depth \(n\). A digit is a buffer of one to four elements, represented as a list to simplify the presentation. \[ type \text{Digit } \alpha = [\alpha] \] Adding a new element to the left of the sequence: \[ (\triangleleft) \quad a \triangleleft \text{Empty} = \text{Single } a \] \[ a \triangleleft \text{Single } b = \text{Deep } [a] \text{ Empty } [b] \] \[ a \triangleleft \text{Deep } [b, c, d, e] \, m \, sf = \text{Deep } [a, b] (\text{Node3 } c \, d \, e < m) \, sf \] \[ a \triangleleft \text{Deep } \text{pr } m \, sf = \text{Deep } ([a] + \text{pr}) \, m \, sf \] Adding to the right end of the sequence is the mirror image of ‘▷’: \[ \begin{align*} (▷) & \quad :: \quad \text{FingerTree } a \rightarrow a \rightarrow \text{FingerTree } a \\ \text{Empty} & \quad \triangleright a = \text{Single } a \\ \text{Single } b & \quad \triangleright a = \text{Deep } [b] \text{ Empty } [a] \\ \text{Deep } \text{pr } m \ [e, d, c, b] & \quad \triangleright a = \text{Deep } \text{pr } (m \triangleright \text{Node3 } e \ d \ c) \ [b, a] \\ \text{Deep } \text{pr } m \ sf & \quad \triangleright a = \text{Deep } \text{pr } m \ (sf + \ [a]) \end{align*} \] We classify digits of two or three elements (which correspond to nodes) as safe, and those of one or four elements as dangerous (cf 0-1-2 random-access lists). A deque operation may only propagate to the next level from a dangerous digit, but in doing so it makes that digit safe, so that the next operation to reach that digit will not propagate. The use of 2-3 nodes rather than pairs provides enough flexibility so that we can also append two 2-3 finger trees. The tree *Empty* will be an identity for concatenation, and *Singles* may be concatenated using ‘≪’ or ‘≫’, so the only difficult case is concatenation of two *Deep* trees. Concatenation of two Deep trees: \[ \text{Deep } pr_1 \ m_1 \ sf_1 \cong \text{Deep } pr_2 \ m_2 \ sf_2 = \text{Deep } pr_1 \ldots \ sf_2 \] We can use the prefix of the first tree as the prefix of the result, and the suffix of the second tree as the suffix of the result. To combine the rest to make the new middle subtree, we require a function of type \[ \text{FingerTree (Node } \alpha) \rightarrow \text{Digit } \alpha \rightarrow \text{Digit } \alpha \rightarrow \text{FingerTree (Node } \alpha) \rightarrow \text{FingerTree (Node } \alpha) \] For simplicity, we combine the two digit arguments into a list of Nodes. Finger trees—concatenation—continued \[ \text{app3} :: \text{FingerTree} \alpha \to [\alpha] \to \text{FingerTree} \alpha \to \text{FingerTree} \alpha \\ \text{app3 Empty ts xs} = ts \triangleright xs \\ \text{app3 xs ts Empty} = xs \triangleright\triangleright ts \\ \text{app3 (Single x) ts xs} = x \triangleleft (ts \triangleright xs) \\ \text{app3 xs ts (Single x)} = (xs \triangleright\triangleright ts) \triangleright x \\ \text{app3 (Deep pr_1 m_1 sf_1) ts (Deep pr_2 m_2 sf_2)} \\ \quad = \text{Deep pr}_1 (\text{app3 m}_1 (\text{nodes (sf}_1 + ts + pr_2)) \ m_2) \ sf_2 \] \[ \text{nodes} \quad \triangleright\triangleright \quad \text{groups a list of at most 12 elements into a list of 2-3 nodes, ‘\triangleright\triangleright’ adds a list of at most 4 elements to the left of a finger tree.} \] \[ \text{(⊗) :: FingerTree} \alpha \to \text{FingerTree} \alpha \to \text{FingerTree} \alpha \\ x s \bigtriangleup\bigtriangleup y s = \text{app3 xs [] ys} \] \[ \text{The recursion terminates when we reach the bottom of the shallower tree, so the total time taken is } \Theta(\log(\min\{n_1, n_2\})). \] Finger trees—concatenation—continued \[ \text{nodes} \quad :: \quad [\alpha] \rightarrow [\text{Node} \, \alpha] \] \[ \text{nodes} \, [a, b] \quad = \quad [\text{Node2} \, a \, b] \] \[ \text{nodes} \, [a, b, c] \quad = \quad [\text{Node3} \, a \, b \, c] \] \[ \text{nodes} \, [a, b, c, d] \quad = \quad [\text{Node2} \, a \, b, \text{Node2} \, c \, d] \] \[ \text{nodes} \, (a : b : c : xs) = \text{Node3} \, a \, b \, c : \text{nodes} \, xs \] \[ (\triangleleft \,') \quad :: \quad [a] \rightarrow \text{FingerTree} \, a \rightarrow \text{FingerTree} \, a \] \[ x \triangleleft \, t = \text{foldr} \, (\triangleleft) \, t \, x \] \[ (\triangleright \,') \quad :: \quad \text{FingerTree} \, a \rightarrow [a] \rightarrow \text{FingerTree} \, a \] \[ t \triangleright \, x = \text{foldl} \, (\triangleright) \, t \, x \] 2-3 finger trees may also serve as implementations of - priority queues, - search trees, - priority search queues, - . . . Idea: augment the internal nodes by additional information (size, split key, or both) to steer the search. The use of 2-3 trees as opposed to pairs is essential: one can prove a lower bound of $\Omega(\sqrt{n})$ for insertion and deletion if the data structure is uniquely determined by its size. Outline of the talk - Exploring the analogy (7–27) - A toolbox of number systems (29–41) - Analysis of data structures (43–51) - A worked-out example: 2-3 finger trees (53–64) Conclusion - Number systems serve admirably as templates for data structures. - Even the most exotic number systems seem to have their uses in the realm of data structures. - We have only touched the surface of this exciting topic. Thanks for listening! Snyder, On uniquely represented data structures (extended abstract), 1977. Hinze, Constructing red-black trees, 1999.
{"Source-Url": "http://cs.fit.edu/~ryan/library/functional_programming/hinze.pdf", "len_cl100k_base": 11186, "olmocr-version": "0.1.49", "pdf-total-pages": 67, "total-fallback-pages": 0, "total-input-tokens": 115373, "total-output-tokens": 14440, "length": "2e13", "weborganizer": {"__label__adult": 0.0003879070281982422, "__label__art_design": 0.0008654594421386719, "__label__crime_law": 0.0004897117614746094, "__label__education_jobs": 0.0061492919921875, "__label__entertainment": 0.00015461444854736328, "__label__fashion_beauty": 0.00022232532501220703, "__label__finance_business": 0.0003919601440429687, "__label__food_dining": 0.0006456375122070312, "__label__games": 0.0008530616760253906, "__label__hardware": 0.001735687255859375, "__label__health": 0.0011186599731445312, "__label__history": 0.0006551742553710938, "__label__home_hobbies": 0.00031185150146484375, "__label__industrial": 0.001110076904296875, "__label__literature": 0.0005044937133789062, "__label__politics": 0.0005054473876953125, "__label__religion": 0.0008168220520019531, "__label__science_tech": 0.4658203125, "__label__social_life": 0.00023484230041503904, "__label__software": 0.00786590576171875, "__label__software_dev": 0.5078125, "__label__sports_fitness": 0.0004117488861083984, "__label__transportation": 0.0009307861328125, "__label__travel": 0.00027942657470703125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 32563, 0.02296]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 32563, 0.8313]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 32563, 0.61417]], "google_gemma-3-12b-it_contains_pii": [[0, 280, false], [280, 1052, null], [1052, 1952, null], [1952, 2525, null], [2525, 2883, null], [2883, 3060, null], [3060, 3711, null], [3711, 4308, null], [4308, 5080, null], [5080, 5909, null], [5909, 6295, null], [6295, 6889, null], [6889, 7336, null], [7336, 7714, null], [7714, 8294, null], [8294, 8818, null], [8818, 9720, null], [9720, 10003, null], [10003, 10282, null], [10282, 10814, null], [10814, 11252, null], [11252, 11965, null], [11965, 12505, null], [12505, 12752, null], [12752, 13236, null], [13236, 13815, null], [13815, 14305, null], [14305, 14482, null], [14482, 14984, null], [14984, 15071, null], [15071, 15694, null], [15694, 16067, null], [16067, 16489, null], [16489, 16965, null], [16965, 17822, null], [17822, 18325, null], [18325, 19029, null], [19029, 19519, null], [19519, 20187, null], [20187, 20531, null], [20531, 20677, null], [20677, 20854, null], [20854, 20969, null], [20969, 21482, null], [21482, 22719, null], [22719, 22899, null], [22899, 23212, null], [23212, 23533, null], [23533, 24248, null], [24248, 24927, null], [24927, 24983, null], [24983, 25160, null], [25160, 25595, null], [25595, 25843, null], [25843, 26125, null], [26125, 26510, null], [26510, 27126, null], [27126, 27547, null], [27547, 28481, null], [28481, 28771, null], [28771, 29399, null], [29399, 30515, null], [30515, 31347, null], [31347, 31770, null], [31770, 31947, null], [31947, 32203, null], [32203, 32563, null]], "google_gemma-3-12b-it_is_public_document": [[0, 280, true], [280, 1052, null], [1052, 1952, null], [1952, 2525, null], [2525, 2883, null], [2883, 3060, null], [3060, 3711, null], [3711, 4308, null], [4308, 5080, null], [5080, 5909, null], [5909, 6295, null], [6295, 6889, null], [6889, 7336, null], [7336, 7714, null], [7714, 8294, null], [8294, 8818, null], [8818, 9720, null], [9720, 10003, null], [10003, 10282, null], [10282, 10814, null], [10814, 11252, null], [11252, 11965, null], [11965, 12505, null], [12505, 12752, null], [12752, 13236, null], [13236, 13815, null], [13815, 14305, null], [14305, 14482, null], [14482, 14984, null], [14984, 15071, null], [15071, 15694, null], [15694, 16067, null], [16067, 16489, null], [16489, 16965, null], [16965, 17822, null], [17822, 18325, null], [18325, 19029, null], [19029, 19519, null], [19519, 20187, null], [20187, 20531, null], [20531, 20677, null], [20677, 20854, null], [20854, 20969, null], [20969, 21482, null], [21482, 22719, null], [22719, 22899, null], [22899, 23212, null], [23212, 23533, null], [23533, 24248, null], [24248, 24927, null], [24927, 24983, null], [24983, 25160, null], [25160, 25595, null], [25595, 25843, null], [25843, 26125, null], [26125, 26510, null], [26510, 27126, null], [27126, 27547, null], [27547, 28481, null], [28481, 28771, null], [28771, 29399, null], [29399, 30515, null], [30515, 31347, null], [31347, 31770, null], [31770, 31947, null], [31947, 32203, null], [32203, 32563, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 32563, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 32563, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 32563, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 32563, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 32563, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 32563, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 32563, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 32563, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 32563, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 32563, null]], "pdf_page_numbers": [[0, 280, 1], [280, 1052, 2], [1052, 1952, 3], [1952, 2525, 4], [2525, 2883, 5], [2883, 3060, 6], [3060, 3711, 7], [3711, 4308, 8], [4308, 5080, 9], [5080, 5909, 10], [5909, 6295, 11], [6295, 6889, 12], [6889, 7336, 13], [7336, 7714, 14], [7714, 8294, 15], [8294, 8818, 16], [8818, 9720, 17], [9720, 10003, 18], [10003, 10282, 19], [10282, 10814, 20], [10814, 11252, 21], [11252, 11965, 22], [11965, 12505, 23], [12505, 12752, 24], [12752, 13236, 25], [13236, 13815, 26], [13815, 14305, 27], [14305, 14482, 28], [14482, 14984, 29], [14984, 15071, 30], [15071, 15694, 31], [15694, 16067, 32], [16067, 16489, 33], [16489, 16965, 34], [16965, 17822, 35], [17822, 18325, 36], [18325, 19029, 37], [19029, 19519, 38], [19519, 20187, 39], [20187, 20531, 40], [20531, 20677, 41], [20677, 20854, 42], [20854, 20969, 43], [20969, 21482, 44], [21482, 22719, 45], [22719, 22899, 46], [22899, 23212, 47], [23212, 23533, 48], [23533, 24248, 49], [24248, 24927, 50], [24927, 24983, 51], [24983, 25160, 52], [25160, 25595, 53], [25595, 25843, 54], [25843, 26125, 55], [26125, 26510, 56], [26510, 27126, 57], [27126, 27547, 58], [27547, 28481, 59], [28481, 28771, 60], [28771, 29399, 61], [29399, 30515, 62], [30515, 31347, 63], [31347, 31770, 64], [31770, 31947, 65], [31947, 32203, 66], [32203, 32563, 67]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 32563, 0.02315]]}
olmocr_science_pdfs
2024-11-24
2024-11-24
3f5d32aaea270f1cc664358a642b0d66c9a5b154
Dynamic Model Functionality Dorian Gorgan August 1995 Dynamic Model Functionality Dorian Gorgan* Computer Science Department Technical University of Cluj-Napoca 26, G. Baritiu St., RO-3400 Cluj-Napoca, Romania e-mail: gorgan@utcluj.ro Abstract The functionality of a graphical Dynamic Model (DYMO) is presented. The model consists of active entities called objects, variables, flags, and passive entities such as behaviors, trajectories, actions, conditions, and so on. The active entities have an explicit defined behavior as a spatial and temporal evolution. The behavior is running on a trajectory, and is defined by a set of parameters, a set of positions and actions which the object executes during its evolution. The trajectory provides the possibility to direct manipulate the entities of the model and their elements. By direct manipulation the model developer may define the actions, rules and conditions included in the evolution associated to an entity position. The evolution of the model consists of the parallel and concurrent evolution of its active entities. Every entity such as object, variable, flag, complex object, behavior is managed by a set of light-weight processes called threads. A set of light-weight processes perform the behavior, the moving, the graphical presentation and the interaction with external modules of the active entities. The behavior execution is a succession of actions achieved by the current entity or by delegated entities. The model entities communicate between them by messages. The identification by name of all the entities is supported. The model is proper in high-end simulation systems, scientific or engineering visualization systems, rapid prototyping systems, graphical user interfaces and visual programming. * The work have been carried out at the Rutherford Appleton Laboratory, UK, and supervised by Prof. David A. Duce. The work have been supported by a TEMPUS grant. CONTENTS 1 INTRODUCTION 2 MODEL INTERFACES 3 FUNCTIONALITY PRINCIPLES 4 COOPERATING PARALLEL PROCESSES 4.1 Distributed Object Based Programming Systems 4.1.1 Object Structure in DOBPS 4.1.2 Object Management 4.2 Tools for Describing Systems of Cooperating Processes 4.3 Light-weight Processes. Threads 5 MODEL ENTITIES 5.1 Objects 5.2 Variables and Flags 5.3 Behaviors 5.4 Trajectories 5.5 Rules 5.6 Conditions and Expressions 5.7 Actions 5.7.1 Action Modelling 5.7.1.1 Create Action 5.7.1.2 Delete Action 5.7.1.3 Instantiate Action 5.7.1.4 Append Action 5.7.1.5 Get and Put Actions 5.7.1.6 Activate Action 5.7.1.7 Show Action 5.7.1.8 Jump Action 5.7.1.9 Rotate, Translate and Scale Actions 6 COMMUNICATION MECHANISM 6.1 Communication with messages 6.2 Message Format 7 MODEL PROCESSORS 7.1 Behavior Processor 7.2 Server Processor 7.3 Display Processor 7.4 Interaction Processors 7.5 Function Synchronization 8 MODEL EVOLUTION 8.1 Condition Evaluation 8.2 Action Execution 8.2.1 Create Action Execution 8.2.2 Delete Action Execution 8.2.3 Instantiate Action Execution 9 DIALOGUE MODELLING 9.1 Interface Language 9.2 User Interface Environments 9.3 Internal Dialogue. Interactors 10 CONCLUSIONS 11 REFERENCES 1 INTRODUCTION The static graphical model are not proper for a dynamical application in the field of simulation, computer aided design or graphical animation. The graphical model with an intrinsic behavior description for the active objects would be more flexible and more useful in the application programs. A dynamic model [14] reduces the intern dialogue between application program and the interface objects. Using the dynamic model, the application program has a user oriented control and is more closed to the natural mean of application entities manipulation. In dynamic model the logic of the program is distributed among the program entities, and the model behavior is a combination of the behavior of its parts. This concept provides a simple description of the parallel actions and of a parallel evolution. Graphical user interfaces use direct manipulation on the interface entities. Graphical models must provide the possibility to manipulate the abstract entities such as: velocity, time, future events, parallel actions, relation between active objects, behavior synchronization, and so on. In visual programming the graphics must provide visual presentations to a better understanding of the links between abstract objects manipulated in applications. Therefore the trajectory is a space-temporal evolution which has a presentation that can be manipulated. The main purpose of the DYMO model emphasizes on the following experiments further on highlighted in this paper: • a flexible model that allows visual programming, active object behavior definition by direct manipulation; • to establish a consistent set of entities that support an active and dynamic evolution: active and passive entities; • a simple and a consistent structure for active objects, variables, flags, behavior, trajectories, and so on, to support a dynamic functionality, unique identification, interactive applications, concurrent evolution and an abstract space manipulation; • a set of light-weight processes such as: behavior, server, display and interactions; • a flexible, dynamic and interactive behavior of active entities; • to establish the definition, the structure, the consistent modelling of notion such as: behavior, trajectory, trajectory position, rule, condition, expression, action, operation, action parameters; • to define and execute a space-temporal behavior using the notion of trajectory in space and in time; • to provide a graphical presentation and a possibility of direct manipulation of the abstract notions; • a simple set of action that allows complex behaviors and various type of applications; • a concurrent execution in a quasi-parallel manner using light-weight processes; • to synchronize the action execution and the access to shared resources: data structures, model entities, light-weight processes; • action execution by delegation; DYMO has been experimented in C++, under Unix. The basis of communication in DYMO are the thread functions from the light-weight library of SunOS. Figure 1. The dynamic model and modules it interacts with. 2 MODEL INTERFACES The model is a set of active objects which have a asynchronous behavior. The application developer, called with the general term of user, and using a direct manipulation approach constructs the dynamic model. The model developer creates, deletes and instantiates model entities, and defines their behavior. The entity behavior is a set of conditioned actions. All the time the system is running the active objects execute their behavior. The conditions fire the actions according to the actual state of the model: object attributes, positions, values of the variables or flags, and so on. The state of the model can be changed by the evolution of the model itself or by the external events. The external events update the model state through the interfaces between the model and user, and graphical systems, and applications (Figure 1). The application program modifies the model state as a consequence of the application algorithm or as a result of a real process supervising. Interface events are manipulated by interactors [16], [9]. The interactors are special object agents which supervise signals to/from external modules and send/receive messages to/from dynamic model. We define an event as a changing of a signal value. The interactors transform an asynchronous communication between the model and its external modules into a communication by messages inside the model. 3 FUNCTIONALITY PRINCIPLES DYMO has a structure and a functionality based on the following principles: • the fundamental entities of the model are active objects; • the object has an associated behavior; • the object behavior, actions, presentation, and motion are executed by light-weight processes; • the model entities are encapsulated objects which communicate through asynchronous messages; • all model elements may be direct manipulated and anyone has a name as an unique identification; • all of the model entities and their elements such as attributes, parameters, components, behavior, rules, positions, etc., may be dynamically changed by the model objects or by the external modules; • the model has an ordered behavior defined in time and space. The model has an intrinsic defined evolution. All objects, variables and flags are active entities which have private behaviors. The model developer defines the behavior for every entity rather than defining a global scenarios as an unique controlling program. Any object may be connected to a specific behavior, and can inherit, change or delete own behavior or the behavior of another object. The evolution of the model consists of the parallel and concurrent evolution of its active entities. Every entity such as object, variable, flag and complex object is managed by a set of light-weight processes called threads. The evolution of the model is according to the current state and the behavior definition of its objects. The object behavior is a sequence of actions performed by the object itself or by other delegated objects. The actions operate on input elements and generate output elements. The operated elements may be object attributes, object behaviors, the value of a variable, the position from a trajectory, actions associated to a position, and so on. The access to the operated elements is authorized only through the server processor of the accessed entity. The reason for this restriction has been imposed by the synchronization between object behaviors, the multiple access to common resources, and the flexibility of a distributed implementation and execution of the model. The principle of server process delegation is over the object encapsulation principle used in object oriented programming technique. Communication between objects use asynchronous messages. If an object needs to execute an action on another object or entity it delegates the second to execute this action. The delegation are based on message communication. The same time the message manipulation is according to private evolution. The identification of model entities is done by an unique name versus the solution of the identification by pointer. This solution has the disadvantage of a slow execution. This dislike can be passed over with a performant machine such as with a parallel or distributed execution of the program. The advantage are more significant and consist of a flexible implementation and execution on distributed resource environment, a portability of application programs, an easy reconfiguration of the connections in the dynamical model and with its external modules, a possibility to change the address and the structure of an entity without searching and changing all references to it. Another main advantage is the possibility to refer to them in user interface, in the object behavior definition, as arguments of actions, and so on. An object modifies the object attributes, the behavior parameters, and generally the model state when the objects are running their evolution. The changes are dynamic, and other objects may modify the state of the current object - presentation, position, name, behavior, etc. The behavior is defined in an abstract space where the model will be run. The evolution follows an explicit defined trajectory in the abstract space. The trajectory is a set of successive positions with associated rules. The rules of a position are performed when the object there is on the specified position. The spatial definition provides a natural manipulation of the abstract notions such as rules, future positions and states, interrelations between elements of entities, actions, and so on. The spacial definition supplies the model with the indispensable characteristics in applications such as graphical user interfaces, visual programming, multimedia presentation, virtual reality, rapid prototyping, and so on. 4 COOPERATING PARALLEL PROCESSES 4.1 Distributed Object Based Programming Systems Definition of an object, given in [3] is as an entity that encapsulates some private state information or data, a set of associated operations or procedures that manipulate the data, and possibly a thread of control so that collectively they can be treated as a single unit. The object can be accessed or modified only by making a request or an invocation of a publicly accessible operations of the object. Objects must respect the principle of encapsulation. There are two types of programming languages which use objects: object based languages that support objects (e.g. Ada, Modula-2), and object oriented languages that support the concept of inheritance (e.g. C++, Smalltalk). Inheritance from a single base class is referred to as single inheritance (e.g. C++, DYMO, MADE [1], HUMANOID [23], GARNET [16], UIDE [22]), whereas inheritance from multiple base classes is referred to as multiple inheritance (PREMO [7], [8], [23], [24]). Another variation of the inheritance scheme is delegation [1], [3], [8]. Delegation is a mechanism that allows an instance object to delegate the execution of an invocation request to another object. The objects can be the instances of the same class and one of them delegates the second for a servicing request the first object is unable to serve. For example the accessing to the state of the second object. An object based programming system can be defined as a computing environment that supplies both an object based programming language and a system that supports object abstraction at the operating system level. A distributed, object based programming system (DOBPS) [3], provides the features of an object based programming system as well as a decentralized or distributed computing environment. 4.1.1 Object Structure in DOBPS DOBPS can support different types of object dimension: large-grain, medium-grain and fine-grain. DYMO can be implemented on a DOBPS using the concept of medium-grain objects. The relationship between the processes and the objects characterizes the composition of the objects. DYMO uses the concept of active object model rather than the passive object model. In the passive object model, the objects and processes are completely separate entities. A process is not bound or restricted to a single object. In the active object model, a few server processes are created and associated to each object to execute its invocation requests. A process is a private resource of an object for which it was created. When an object is destroyed, its processes are destroyed also. DYMO supports the active object model. When an client object makes an action invocation, a server process of the addressed object accepts the request and performs the action of the client. The active object model can be static or dynamic. DYMO supports the dynamic model type, and every object has a different number of server processes. In the dynamic type of the active object model, server processes are dynamically created for an object as required. One disadvantage of the active object model is the deadlock. Deadlock can occur if an object does not have enough server processes to perform the requested services. In dynamic active model deadlock is less a problem. Amoeba [3], [15], CHORUS [18], Eden [3] are DOBPS which use a static number of processes in the active object model. Argus [3] uses a dynamic number of processes, and Clouds [3] and Emerald use a passive object model. 4.1.2 Object Management In distributed, object based programming systems an important function is to manage the object actions. Actions must have the following properties: serializability, atomicity and permanence. Serializability means that multiple actions that execute concurrently should be scheduled in such a way that the overall effect is as if they have were executed sequentially in some order. Atomicity means an action either successfully completes or has no effect. The permanence means the effects of an action that successfully completes is not lost, except in the event of a catastrophic failure. According to these properties there are three types of the action managing: requests, transactions and nested transactions. DYMO as Amoeba, CHORUS and Emerald systems supports the request scheme. In this scheme, the user is responsible for deciding when to initiate the committed procedure. The main disadvantage with request scheme is that the guarantee of permanence and atomicity is lost. In DYMO the serializability is supported by the invocation of the single server processor of the associated object and of the single behavior processor of the client object. Atomicity can be improved by the concept of pre- and post-conditions imposed to every action. For example the UIDE [22] supports An important function of a DOBPS is the synchronization of multiple actions. A mechanism of synchronization is necessary to ensure that all actions have the property of serializability and to protect the integrity of object states. There are two types of synchronization scheme: pessimistic synchronization and optimistic synchronization. The majority of systems have a pessimistic synchronization. Argus, CHORUS, Clouds, Eden, Emerald, TABS/Camelot. Amoeba supports the both schemes of synchronization. In pessimistic synchronization an action that invokes an object is temporarily suspended if it will interfere with another action that is currently being serviced by the object. The most used mechanisms are read and write locks or timestamps, semaphores and monitors. DYMO evolves the pessimistic synchronization using semaphores and monitors. In optimistic synchronization scheme an object does not signal the conflicts while invocation are being processed. The optimistic synchronization scheme allows the maximum degree of concurrence possible. Actions are never suspended. In pessimistic synchronization two actions that modify different parts of the same entity are not able to execute concurrently even when there is no problem of conflict. The facilities like security and object reliability are not resolved in DYMO. There is the possibility to save in a file the current state of the model. Therefore when the system fails the last saved model state can be reloaded. Another DOBPS can be mentioned such as Mach (Carnegie Mellon University) that is an operating system for uni- and multi-processors [4]. Mach provides flexible memory management and sharing, multiple threads within a single address space or task for concurrence and parallelism, and a network-transparent communication system. ### 4.2 Tools for Describing Systems of Cooperating Processes Using the facilities of distributed object based systems let see a few tools used for describing cooperating processes. Are presented MADE environment [1], the MANIFOLD language and PREMO standard proposal [7], [8], [25], [26], related to DYMO. Another programming language can be mentioned such as COOL (Concurrent Object Oriented Language), which was designed to exploit coarse-grained parallelism at the level in shared-memory multiprocessors [2]. COOL was developed at the Stanford University. The project MADE (Multimedia Application Development Environment) is trying to define and implement a portable object-oriented development environment for multimedia applications. The model emphasizes on two cardinal concepts: active objects and delegation. MADE does not aim at the definition of programming tools to handle video and audio, but it also identifies a set of more general objects that are necessary to develop advanced multimedia applications. For example, interaction objects for advanced user interaction facilities, time or synchronization objects for media synchronization, constraint management, and help, monitoring objects, and so on. Arbab and al. [1] define active objects as having its own virtual processor with its own thread of control. Active objects communicate with one another by sending synchronous messages which are served by the addressed object. For the callers, client objects there is only one type of message communication, named synchronous message passing. The receiver object may use two different forms of message performing methods: the requests are queued or the requests are sampled. The paradigms of message passing and of the control of received messages are well known, as we noticed, in the concurrent programming. The unusual feature of the model from MADE, are sampled messages. But this feature is not unusual in computer graphics. MADE was implemented on Unix and MS-DOS environments, using C++ language. The general concepts of objects have been mapped onto C++ classes. However, the C++ language has been extended as a language called mC++, which serves as the programming interface of the MADE toolkit. Every object in mC++ has its own thread of control rather than in C++ concepts of thread and object are separate entities. In MADE there are four types of objects: (1) active objects, (2) mutex objects, (3) unprotected objects and (4) C++ objects. The last three types are passive objects and the first three have a class-level behavior. Instances of mC++ objects can be thought of extensions which provide additional behavior to that defined in the prototypes. MANIFOLD language [19] is another tool for defining complex dynamic interaction techniques that are common in user interfaces. MANIFOLD is a language for describing systems of cooperating parallel processes. Processes in MANIFOLD communicate by means of buffered communication links called streams and by reacting to events raised as asynchronously by other processes. Each activated instance of a manifold definition is an independent process with its own virtual processor. A manifold processor is capable of performing a limited set of actions. This includes a set of primitive actions, plus the primary action of setting up pipelines. A pipeline is an expression defining a couple of streams, represented as a sequence of one or more groups, processors, or ports. An event handler is a labelled block of actions in manifold. Event handlers declare a preemptive change of state in a manifold that observes an event of interest. This is performed by its manifold processor which locates a proper event handler for observer event. PREMO (Presentation Environments for Multimedia Objects) is the name given to a proposed standardization in the field of presentation of multimedia objects. PREMO is a presentation environment which extends current graphics standards (GKS, PHIGS, etc.). It is an object oriented specification and includes distribution aspects (influence of MADE, ScriptX, GainMomentum, COBRA, COSS, etc.). The PREMO object model defines the semantics of object and non-object types, and object interactions. A PREMO system consists of a collection of components. Any component is a collection of object types and the model objects are instances of some object type. Objects are conceptually active. Between objects there are supertype/subtype relationships. Multiple supertypes are allowed. There is a set of operations that are actions applied on objects. Each operation has a signature that consists of a name, a list of parameters type and a list of result types. When an operation request is issued, a specific operation implementation is selected based on name and signature. Objects may define their operations as being synchronous, asynchronous, or sampled. Operations are "messages". An object can invoke its own operations without deadlock. The set of foundation objects contains the following types: EnhancedData - encapsulation of the notion of data to be processed; Controller - a Finite State Machine, with operations like handleEvent; EventHandler, Producers, Porters - active entities to build up processing networks such as fully data flow or fully control flow; Aggregate types - lists, arrays, tables; Objects for synchronization. 4.3 Light-weight Processes. Threads The functionality of active objects can be achieved by the application programmers by two means: parallelism and concurrence. The parallelism is used when the task is solved using several, physically distinct hardware processors. The concurrence is used when a task can be broken up into a set of collaborating, but functionally independent sub-tasks called processes, threads, or light-weight processes, which exchange information at well defined moments. In these terms parallelism is only a special form of concurrence. The main conceptual differences between concurrence and parallelism are the following: for parallelism the processes are expensive resources, in the case of concurrence the processes are cheap. The assumption of having cheap processes is not in the direction of hardware development rather than with the current trends in the evolution of recent software systems. A thread is a data type representing a flow of control. The light-weight process mechanism allows threads of control to share the same address space. Threads operate more efficiently than ordinary processes (e.g. SunOS processes), because they communicate via shared memory instead of a file system. The light-weight processes are useful for simulation programs which model concurrent situations. One thread can start other threads. The threads can be scheduled within the process (via threads library facilities), or can be scheduled by the kernel. Threads execute independently. There is no general way to predict (e.g. SunOS) how the execution of instructions by different threads is interleaved. On machines with more than one processor, more than one thread in a process executes simultaneously. Threads make operating system requests independently. Threads can manipulate asynchronous I/O events. Threads exist independently of virtual memory, I/O resources, resource allocation, and other operating system supported objects, but are able to work with these objects. 5 MODEL ENTITIES The dynamic model is a set of components which define the structure and the functionality of the model. The structure of the model is defined by the structure of its entities and the dynamic connections between them. The functionality is defined by the private functionality of entities. The entities of the model are: objects, variables, flags, behaviors, trajectories, rules, conditions, and actions. 5.1 Objects Objects are active entities with a private behavior. The evolution implies the execution of an associated behavior on a specific trajectory with a well defined state and parameters. The formal structure of an object is the following (Figure 2): ``` object (OBJECT name, position, parent_object, son_objects, attributes, active_flag, behavior_name, ``` processors (behavior, server, display, interactors) ) Figure 2. The object structure. An object has a behaviour with a trajectory and rules associated to trajectory positions. The structure type is called OBJECT. The object name is unique defined. Every object may be a prototype for an instance object which has a different name and a private position. The position denotes the current position in the virtual space. When the object is moving the position is changing according to its evolution on the trajectory. An object having an associated behavior executes its evolution only if the active_flag is true. The visibility_flag specifies the object is visible or not during its evolution. An object can be simple object or a complex object called aggregate. For simplicity we will use for both types the same common name object. The word object denotes a model entity having the above-mentioned structure rather than the notion of object from the point of view of programming language. The object which includes the current object is named its parent_object or parent. The included objects are called son_objects. The relations between parent and included objects are active when the model is running. An object inherits from its parent object all the characteristics: attributes, active_flag, visibility_flag, behavior, if it has not another explicit definition for them. An explicit element value has a higher priority then the inherited one. The attributes are graphical attributes or application attributes. Graphical attributes can be for example, the color, line pattern, dimensions, orientation, etc., and the application attributes can be elements used by the application program such as weight, age, temperature, nominal current, etc. An attribute is defined by three elements: name, value type and value. The type specifies the type of attribute value: integer, float or string. Any attribute and its elements may be inquired or modified. The execution of the model is a combination of the evolution of its elements. The evolution of an object is performed by its associated processors. The managers of the object are light-weight processes called threads. The processors share the same memory and have access to the model resources. An object has four processor types: behavior, server, display and interactor. The behavior processor performs the private object behavior. The server processor performs the actions requested by other objects to the owner object. The display processor creates the presentation (sound, graphics, images) of the owner objects. The interactor processors perform the interface between the object and the external modules like user, application program, or graphical systems. Interactors access the object state according to the value of the interface signals. Variables and Flags Variables and flags are active entities with a private evolution. The evolution implies the evaluation of an expression or a condition. The evaluation may be dynamically or statically performed. A dynamic evaluation means a permanent evaluation and a static evaluation means that the evaluation is performed at the explicitly specified moments. The value of a variable can be any value of a model element (integer, float, string), and the value of a flag is a boolean value: true or false. The formal structure of a variable and of a flag is the following (Figure 3): \[ \text{variable/ flag ( VARIABLE/ FLAG} \\ \text{ name,} \\ \text{ position,} \\ \text{ type,} \\ \text{ value,} \\ \text{ expression/ condition,} \\ \text{ processors (} \\ \text{ behavior,} \\ \text{ server,} \\ \text{ display,} \\ \text{ interactors} \\ \text{ )} \\ \text{ )} \] The structure type for a variable is called VARIABLE and for a flag is called FLAG. There are the same processors as within the object structure, but the definitions of processors are different. For example the behavior of a variable only evaluates the expression. The processor delegates other entities only to supply information about their state. The server processor performs get and put operations indeed. The variables and flags have positions where they can be presented by the system and direct manipulated by the users. An improved variation of active model can use a single entity type for variables and flags. The boolean value of the flag may be processed as an integer value. Behaviors Every active object has an associated behavior. A behavior is a passive object from the point of view of programming technique rather than an active object from the point of view of active model. The same behavior may be associated to a single object or to a set of object (Figure 4). A behavior has a name as an unique identifier. Its structure contains elements for direct manipulation: name, and position into an abstract coordinates system. The behavior is characterized by parameters such as the number of moving steps among two explicit positions on the trajectory, other application parameters (delay time, blinking rate, etc.), and a set of trajectory position with associated rules. The behavior may be operated as a model entity, e.g. created, destroyed, associated to an object, modified and so on. The formal definition of a behavior having the type BEHAVIOR, is the following: ```plaintext behavior ( BEHAVIOR name, type, steps_number, trajectory_set, parameters ) ``` The behavior can be linked to different sets of trajectory. Two behaviors having the same trajectory set may differ by behavior parameters. The type of behavior specifies the accessing sequence of the trajectory set, such as polyline, cycle, point, inertial, random, and so on. For example, for cycle type the last trajectory position is infinitely followed by the first explicit position. The same sequence of trajectory positions may be followed in different manners, e.g. the space between successive positions may be followed in a number of steps specified by the parameter steps_number and with a specified delay. 5.4 Trajectories The trajectory defines the evolution into the abstract space of an associated object. The main goal of trajectory is to provide a concrete representation of abstract notions. The incorporated positions allow a direct manipulation of abstract notions. Using the space representation the notion of successive moments of time are indirect represented as successive explicit positions. The abstract notion of time, as in real world, becomes a notion of space and a notion of the evolution in space. Consequently, the synchronization between objects in different moments of their evolution is equalized with the relations between objects on specified positions. A formal definition of trajectory is as following: ```plaintext trajectory ( TRAJECTORY position_name, position, rule ) ``` Every trajectory is a passive object, from the point of view of programming technique. It is characterized by a name, position in abstract space, and a set of rules. The space may be a 2D or 3D coordinates system. While the model is running and the associated object there is on an explicit position of the trajectory the rules associated to this position are evaluated. A position may have none, or a set of rule. Every rule incorporates conditions and associated actions (Figure 5). The rules are evaluated in the explicit defined sequence. The rules evaluating means all set of associated actions fire if the condition is true. After all of rules associated to the current position have been processed the current object starts to the next explicit position on the trajectory. The space between two explicit position is passed on the number of steps that characterized the behavior. Therefore an object may accept requests as delegated actions on any position from this evolution, but performs its private rules only on the explicit position from its trajectory. 5.5 Rules DYMO is a rule based model. A rule is a named pair of a condition and a set of actions (Figure 6): ```plaintext rule ( RULE name, condition, action ) ``` In the clausal form it has the following definition: \( \text{condition} \rightarrow \text{action}_1, \ldots, \text{action}_n \). The condition is evaluated and if it is true the actions are performed in a sequential order. Being a named entity the rule can be addressed in a user interface environment. ![Diagram of rule, condition, and actions relationship] Figure 6. The relation between rules, conditions and actions. ### 5.6 Conditions and Expressions Conditions are logical expressions which reflect the state of the dynamic model. A condition may be defined in terms of objects, variables, behavior parameters, positions, etc., and their elements. For example, a condition may have the form: \[(\text{object("R2")},\text{attribute("crt")})+(\text{object("D1")},\text{attribute("current")})<\text{object("R15"),attribute("current")})\] While the model is running the objects R2, D1 and R15 are inquired about the values of their attributes. The object which performs its behavior computes the condition with the values returned from the delegated entities. The terms of conditions are elements of the model entities which have name, position and graphical presentation. Therefore the entire syntactic form of conditions may be built using the direct manipulation technique. The condition modelling has pre-fixed Polish form: \[ \text{<unary_operator> <term> | <binary_operator> <term> <term> | <log_expression> | <str_op> <string_type> <string_type> | <aritm_expr> | <aritm_op> <aritm_expr> <aritm_expr> | <aritm_term> | <integer_type_term> | <float_type_term> | NOT_OP} \] where terms may have only three types: integer, float and string. There are three logic operators: not, and, or. The following relational operators: \(< > = <= >= !=\) and the following arithmetic operators: \(* / + -\) are used. The following simple determine grammar rules have been used to build and to interpret the conditions and the expressions from the actual experimented model: \[ \text{<condition>} ::= \text{<not_op> <condition>} \\ | \text{<log_op> <condition> <condition> } \\ | \text{<log_expression>} \] \[ \text{<log_expression>} ::= \text{<rel_op> <aritm_expr> <aritm_expr> } \\ | \text{<str_op> <string_type> <string_type> } \\ | \text{<aritm_expr>} \] \[ \text{<aritm_expr>} ::= \text{<aritm_op> <aritm_expr> <aritm_expr> } \\ | \text{<aritm_term>} \] \[ \text{<aritm_term>} ::= \text{<integer_type_term> | <float_type_term>} \] \[ \text{<not_op>} ::= \text{NOT_OP} \] 5.7 Actions In [14] there are defined the following set of 12 actions used in the dynamic model: create, delete, instantiate, append, get, put, activate, show, jump, rotate, translate, and scale. The first four actions control the creation and destruction of model entities. Get and put actions inquire and modify the content of the model entities. The activate and show actions control the motion and the visibility of the model entities. The action jump controls the sequence of trajectory positions. There are also three graphical actions such as rotate, translate and scale which control the graphical attributes of objects and their presentation. 5.7.1 Action Modelling Every action is an object, from the point of view of programming technique, having the following general form: ``` action ( ACTION operator, input_entities, output_entities, error ) ``` The operator acts on the input_entities and provides the output_entities. Input and output entities are defined in terms of model entities and their elements. For the reason of a pessimistic synchronization and for respecting the property of serializability, any operation on the model elements must be performed only by delegation. An action is defined in BNF formal language as followings: ``` <action> ::= <create_act> | <delete_act | <instantiate_act | <append_act | <get_act | <put_act | | <activate_act | <show_act | | <jump_act | | <rotate_act | <translate_act | <scale_act ``` 5.7.1.1 Create Action The create action starts from a nil entity and create a new entity with a private name, type, and position. The create action operates on the following entities: (a) objects, (b) behaviors, (c) variables, and (d) flags. The formal definition of the create action modelling is such as: ``` <create_act> ::= <create_obj> | <create_bhv> | <create_var> | <create_flag> <create_obj> ::= OP_CREATE EN_OBJECT <name> OBJ_POSITION <x> <y> <create_bhv> ::= OP_CREATE EN_BEHAVIOR <name> BH_TYPE <trj_type> <create_var> ::= OP_CREATE EN_VARIABLE <name> VAR_TYPE <var_type> VAR_POSITION <x> <y> <create_flag> ::= OP_CREATE EN_FLAG <name> FLG_TYPE <var_type> FLG_POSITION <x> <y> <trj_type> ::= TRJ_INHERITED | TRJ_POLYLINE | TRJ_POINT | TRJ_CYCLIC | TRJ_INERTIAL | TRJ_RANDOM | TRJ_GRAPH <var_type> ::= VAR_DYNAMIC | VAR_STATIC | VAR_APP <flag_type> ::= FLG_DYNAMIC | FLG_STATIC | FLG_APP ``` The create action is performed by the current object itself on the specified entity. The entity creation is performed without delegation since it not violate the encapsulation object concept. 5.7.1.2 Delete Action The delete action destroys an yet created entity or its elements. The delete action operates on the following entities: (a) objects, (b) behaviors, (c) variables, (d) flags and (e) their elements. The formal definition of the delete action modelling is the following: ``` <delete_act> ::= <delete_obj> | <delete_bhv> | <delete_var> | <delete_flag> <delete_obj> ::= OP_DELETE EN_OBJECT <name> | OP_DELETE EN_OBJECT <name> <obj_element> <delete_bhv> ::= OP_DELETE EN_BEHAVIOR <name> | OP_DELETE EN_BEHAVIOR <name> <bhv_element> <delete_var> ::= OP_DELETE EN_VARIABLE <name> <delete_flag> ::= OP_DELETE EN_FLAG <name> <obj_element> ::= OBJ_BEHAVIOR | OBJ_SONS <name> | OBJ_ATTRIBUTE <name> <bhv_element> ::= BH_TRAJECTORY | BH_POSITION <name> | BH_PARAMETER <name> | BH_POSITION <name> BH_RULE <name> | BH_POSITION <name> BH_RULE ``` The delete action may be performed by the entity itself if it is delegated to delete one of its elements. If the delegated delete action specifies to delete the owner active object the action is aborted. An object may delete any other entity. 5.7.1.3 Instantiate Action The instantiate action creates a copy of an entity with new name and position. All other characteristics of the entity are keeping - attributes, components, behavior, processors, etc. The instantiate action operates on the following entities: (a) objects, (b) behaviors, (c) variables, and (d) flags. The formal definition of the instantiate action modelling is the following: ``` <instantiate_act> ::= <inst_obj> | <inst_bhv> | <inst_var> | <inst_flag> <inst_obj> ::= OP_INSTANTIATE EN_OBJECT <name> OBJ_NAME <name> OBJ_POSITION <x> <y> <inst_bhv> ::= OP_INSTANTIATE EN_BEHAVIOR <name> BH_NAME <name> <inst_var> ::= OP_INSTANTIATE EN_VARIABLE <name> VAR_NAME <name> VAR_POSITION <x> <y> <inst_flag> ::= OP_INSTANTIATE EN_FLAG <name> FLG_NAME <name> FLG_POSITION <x> <y> <trj_type> ::= TRJ_INHERITED | TRJ_POLYLINE | TRJ_POINT | TRJ_CYCLIC | TRJ_INERTIAL | TRJ_RANDOM | TRJ_GRAPH <var_type> ::= VAR_DYNAMIC | VAR_STATIC | VAR_APP <flag_type> ::= FLG_DYNAMIC | FLG_STATIC | FLG_APP ``` The instantiate action is performed with delegation to the prototype entity. 5.7.1.4 Append Action The **append** action adds to an existent object or behavior a new element. A large set of operation can be performed through assign action (get and put), or append action. We choose the way of assign action for the reason of homogeneous processing. When an element is assigned the processor adds the new element any way - the element there is or is not. The formal definition: $$<append_act> ::= <append_obj> | <append_bhv>$$ $$<append_obj> ::= OP_APPEND EN_OBJECT <name> EN_OBJECT <name>$$ $$<append_bhv> ::= OP_APPEND EN_BEHAVIOR <name> <bhv_append_2>$$ $$<bhv_append_2> ::= TRJ_POS_NAME <name> | BH_POSITION <name> TRJ_POS_NAME <name>$$ 5.7.1.5 Get and Put Actions Get and put actions read and write the value of an entity element. The formal definition is the following: $$<get_act> ::= OP_GET <input_entity>$$ $$<put_act> ::= OP_PUT <output_entity>$$ in the user interface it can be added the **assign** action as a couple of get and put actions. $$<assign_act> ::= OP_ASSIGN <output_entity> <input_entity>$$ The entity elements are the same for input and for output unless the **input_entity** may be a constant. $$<input_entity> ::= <object_element> | <bhv_element> | <var_element>$$ $$<flag_element> | <app_function> | <constant>$$ in an extended model version the **input_entity** may be a condition, a logic expression or an arithmetic expression. In a particular case the expression may be a single element. In the case of assign action the type of operand must be compatible. $$<input_entity> ::= <condition> | ...$$ $$<output_entity> ::= <object_element> | <bhv_element> | <var_element>$$ $$<flag_element> | <app_function>$$ In graphical applications the point or the pixel may be considered as an abstract object having only attributes like position and color. The elements of a point can be read (position, color) or written (color). $$<input_entity> ::= <point_element> | ...$$ $$<output_entity> ::= <point_color> | ...$$ $$<object_element> ::= EN_OBJECT <name> <obj_elem_2>$$ $$<obj_elem_2> ::= OBJ_NAME | OBJ_PARENT | OBJ_POSITIONX | OBJ_POSITIONY$$ $$| OBJ_BEHAVIOR | OBJ_ATTRIBUTE <name>$$ $$<bhv_element> ::= EN_OBJECT <name> <bhv_elem_2>$$ $$<bhv_elem_2> ::= BH_NAME | BH_TYPE | BH_STEPS | BH_TRAJECTORY$$ $$| BH_PARAMETER <name>$$ 5.7.1.6 Activate Action The activate action modifies the flag which specify the entity is engaged in evolution executing. The flag called active_flag may be set or deleted any time. When the active_flag is false the entity evolution is stopped. The necessary condition to start or to continue the entity evolution is entity has an associated behavior and its active flag is set on true. The formal definition is such as: <active_act> ::= OP_ACTIVATE EN_OBJECT <name> <active_flag_val> <active_flag_val> ::= TRUE | FALSE 5.7.1.7 Show Action The show action modifies the flag which specify the entity is visible or not. The flag called visibility_flag may be set or deleted any time. The formal definition is such as: <show_act> ::= OP_SHOW EN_OBJECT <name> <visible_flag_val> <visible_flag_val> ::= TRUE | FALSE The actions activate and show could be performed through assign action, considering active_flag and visibility_flag as attributes. We choose the approach with two distinct attribute for a faster processing. 5.7.1.8 Jump Action The jump action controls the position of the object on the trajectory. The position controlling may be implicit defined by the type of trajectory or explicit through the jump action. The action may be performed by the current object requested from its evolution or from the evolution of another object. The current object performs the jump action by delegation. If this is the case, it is the responsibility of the model developer to specify a valid new position name. If the jump action refers to another object it must be resolved the potential inconsistency between the associated behavior and the next position. Implicitly the new position must be in the set of trajectory associated to the delegated object. The formal definition allows both variants - the same and another object: <jump_act> ::= OP_JUMP EN_OBJECT <name> BH_POSITION <name> 5.7.1.9 Rotate, Translate and Scale Actions The actions rotate, translate and scale set or modify the graphical attributes of an object. The formal definitions are the following: \[ \begin{align*} \langle \text{rotate\_act} \rangle & \quad ::= \text{OP\_ROTATE EN\_OBJECT } \langle \text{name} \rangle \text{ OBJ\_ANGLE } \langle \text{angle} \rangle \\ \langle \text{translate\_act} \rangle & \quad ::= \text{OP\_TRANSLATE EN\_OBJECT } \langle \text{name} \rangle \text{ } \langle \text{translate\_elem} \rangle \\ \langle \text{translate\_elem} \rangle & \quad ::= \text{OBJ\_TRANSLATEX } \langle \text{tx} \rangle \text{ | OBJ\_TRANSLATEY } \langle \text{ty} \rangle \\ \langle \text{scale\_act} \rangle & \quad ::= \text{OP\_SCALE EN\_OBJECT } \langle \text{name} \rangle \text{ } \langle \text{scale\_elem} \rangle \\ \langle \text{scale\_elem} \rangle & \quad ::= \text{OBJ\_SCALEX } \langle \text{sx} \rangle \text{ | OBJ\_SCALEY } \langle \text{sy} \rangle \end{align*} \] The parameter angle designates the angle of orientation, tx and ty denote the translation relative to the computed current position on the trajectory, and sx and sy are the graphical attributes specifying the modification of the dimension on x and y axes. All parameters of rotate, translate and scale actions are interpreted just in the graphical presentation process. In an homogeneous implementation all three actions may be performed by assign actions. ![Diagram of active entities communicating by messages](image) Figure 7. Two active entities communicate by messages. A pair of a sender and a receiver thread controls the message passing. 6 COMMUNICATION MECHANISM 6.1 Communication with messages Active objects change information using messages. As many concurrent environments like Amoeba, Mach, MANIFOLD, MADE, PREMO, and so on, DYMO handles asynchronous message passing. The basis of communication in DYMO are the thread functions from the light-weight library of SunOS. DYMO has been implemented in C++, under Unix. The library contains functions like message_send and message_receive which achieve the communication protocol. To initiate a communication (Figure 7), the sender thread builds the message as a data structure and calls the message_send function. The sender specifies the following parameters for the message_send function: the receiver thread, the address and dimension of the sent message, and the address and dimension of the received message. The received message is a data structure too. The same time the receiver thread is waiting the message from a precise thread or from an unknown thread. When the message is arriving the receiver identifies the sender thread and receives the addresses and dimensions of the message data structures. All the time the receiver processes the received message and builds the answer, the sender thread is waiting the delegated thread to reply. When the receiver thread completes its operations it discharges the connection calling a reply function from the light-weight library. From this point sender and receiver threads resume their executions. All active entities from DYMO have associated a sender thread and a receiver thread which perform a communication. The same thread may be sender or receiver according to the model evolution. 6.2 Message Format The messages represent the information exchanged between model entities. The message designates a command from a current active entity, and the answer from the delegated entity. The sent message is a command specifying an action that the sender entity can not execute it and delegates another entity to perform it. The formal structure of the sent message is the following: ``` sent_message ( MESSAGE action address, sender entity name, ) ``` The action address allows the receiver entity to perform the delegated action without any other information incorporated in message. All necessary information are embodied in the structure of the specified action. In the experimented version of DYMO the action is an object from the point of view of programming language. It contains parameters describing the action and private methods to access these parameters. The action object complies with the principle of encapsulation. This approach provide the possibility of executing different actions with various structure and content. A delegated action can be in a defined behavior or can be dynamically created. The length of the message is constant and does not depend on type and content of the action. The received message denotes the answer after the delegated action has been completed. It is a reply from the delegated entity to the sender. The message has the following formal structure: ``` received_message ( MESSAGE value type, returned value, ) ``` The significance of information from reply message is related to the performed action. The value type gives information about the correctness of action execution. If an error has arisen the returned value is an error code. Error code provides information about the nature of action failure. In DYMO have been experimented three type of returned values: integer, floating point and string. The string type can be used as an unique solution. The experience with DYMO has demonstrated the structure and the content of selected messages are consistent and supports knowledge for a good concurrent and distributed evolution of the active object model. Another important conclusion is the message structure is independent of the type of delegated action and answer. 7 MODEL PROCESSORS DYMO uses the concept of active object model rather than the passive object model. In the passive object model, the active entities and processes are completely separate entities. In the active object model, a few server processes are created and associated to each active entity to execute its invocation requests. A process is a private resource of an active entity for which it was created. When an active entity is destroyed, its processes are destroyed also. The active object model can be static or dynamic. DYMO supports the dynamic model type, and every object has a fixed number of processes: behavior, server, display processes and a different number of interaction processes. A process is a light-weight process controlled by thread functions. A better version of DYMO should create associated processes only if they are necessary. The behavior processor must be created only if the entity has associated a private behavior. When the behavior of an object is deleted its behavior process will be destroyed also. It is essential the set of thread to be reduced to increase the execution speed. The display processor should be created only for visible entities. The interaction process is created only for interaction entities. An internal entity which does not communicate with external modules: input/output devices, user interface, or application component. 7.1 Behavior Processor Behavior process executes the behavior of an active entity. The active entity of the dynamic model are objects, variables and flags. For an active object the behavior process interprets the rules of the current explicit defined position and computes the next position. The functionality of such a processor is as followings: ``` THREAD behavior_processor { repeat forever { if object is active { if current position is an explicit defined position { computes the next explicit position; mark the current position as a blocked element; /* executes the associated rules; */ for every rule from a position { if condition { executes the set of actions; } } computes the next position; } } } } ``` The defined behavior consists of a set of trajectory position. These positions are called explicit defined positions or explicit positions. The explicit position may have associated rules. An object can be delegated to execute actions on any position, but only on explicit position interprets its private behavior. To interpret the associated behavior means to execute all the rules from a current explicit position. Every rule consists of a condition and a set of actions. The condition is defined in terms of elements of model entities. Therefore a condition evaluation means to interrogate model entities about their values, using get actions. The conclusion is the rule execution means a sequence of actions executed by delegated model entities. Before starting a current position rules execution the current position data structure have to be blocked against any modification performed by the own server processor. ![Diagram of explicit positions](image) **Figure 8.** The explicit positions (Pce and Pne), current position (Pc), and the next position (Pn) on the active entity behaviour. While the object is active it is moving from one explicit position to the next explicit position in the sequence the positions have been defined (Figure 8). The next explicit position is decided according to the type of trajectory (polyline, cyclic, point, random, etc.), the sequence of explicit defined position, or the jump action executed on the current explicit position. The object covers the distance between two consecutive explicit positions by a set of computed intermediate positions. They are computed by a type of interpolation defined as a behavior parameter. The speed on the trajectory is evolved from a delay on every position defined as a behavior parameter also. The variables and flags do not have trajectory positions. The behavior only consists in an expression or a condition. If the type of variable or flag is dynamic it is evaluated by the behavior processor all the time with a system dependent rate. If the entity type is static the behavior definition is evaluated only when the entity type is enquired. ### 7.2 Server Processor Any interrogation or modification of an entity structure is achieved by the server processor. All the operations of the server are initiated by a message encoding an action. The owner or another entity delegates the server processor to achieve the action. The functionality of the server processor is as follows: ```plaintext THREAD server_processor { repeat forever { receive message; switch(delegated action) { case OP_GET: execute get action; . . . } reply to sender entity; } } ``` The server may access any element of owner entity but may not modify the blocked elements. For instance is not possible to modify a trajectory position used by the behavior processor. ### 7.3 Display Processor If the model entity is visible it has a graphical presentation. Display processor is a light-weight processor which builds the graphical presentation according to the graphical attributes of entity. Attributes like color, line pattern, fill pattern, and so on, define the current appearance on the screen. Attributes such as orientation angle, translation parameters, and scale on x and y parameters builds a shape related to the current position of the entity in the abstract coordinates space. For the reason of homogeneous and synchronized access to the graphical attributes of the entity the display processor have to delegate the server processor rather than to directly access them. Actual experiment we have chosen the direct access approach. In an extended version of the active object model the display processors should use the facilities of a graphical system. The graphical system can built graphical presentation in different manner for the same active model. For example, an unique already created model can be watched using various view parameters: window and viewport definitions, observer positions, observer moving, hidden objects, fotorealistic images, and so on. ### 7.4 Interaction Processors Interaction processors are threads which can manipulate asynchronous I/O events. The state of the model can be changed by the evolution of the model itself or by the external events. The external events update the model state through the interfaces between the model and user, and graphical systems, and applications. Entities with interaction processes models the interactors. The interactors are special object agents which supervise signals of external modules and use messages to communicate with dynamic model. When an interface signal arises specific interaction process updates the associated attribute of the owner entity. Any modification of the entity attribute is translated in a modification of an output signal. The attributes may be interrogated by the dynamic model using the communication mechanism. ### 7.5 Function Synchronization An important function of dynamic model is the synchronization of multiple actions. A mechanism of synchronization is necessary to ensure that all actions have the property of serializability and to protect the integrity of entity states. The main problem is to avoid race conditions [24]. There are two types of synchronization scheme: pessimistic synchronization and optimistic synchronization. The majority of systems have a pessimistic synchronization. In pessimistic synchronization an action that invokes an active entity is temporarily suspended if it will interfere with another action that is currently being serviced by the active entity. The most used mechanisms are read and write locks or timestamps, semaphores and monitors. DYMO evolves the pessimistic synchronization using semaphores and monitors. In pessimistic synchronization two actions that modify different parts of the same entity are not able to execute concurrently even when there is no problem of conflict. In optimistic synchronization scheme an object does not signal the conflicts while invocation are being processed. The optimistic synchronization scheme allows the maximum degree of concurrence possible and actions are never suspended. The method of synchronization is according to the scheduling mechanism of light-weight processes and the nature of action achieved by them. Another important consideration is the grain of accessed data structures. Display and interaction processes perform actions on the entity attributes and do not generate conflicts. For example it is not important if the color of an entity is modified at the current or at the next position, if the moving step is small or the displaying speed is high. Also the modification speed by model is higher than modifications through external signals, for instance a mouse moving. If any entity has only one behavior process and one server process is necessary a synchronization of actions to the same data structures or a so called mutual exclusion (mutex). DYMO uses semaphores and monitors over the fragmented data structures. The grained data structures provide a better concurrence since it is reduced critical sections. For example, while a behavior process accesses an explicit position only this position is blocked rather than blocking entire behavior or owner active entity. Another consideration is the nature of operation. There is not necessary a mutual exclusion between two inquiring operations. If one operation is a modification of an element this element must be blocked by the active processes and other processes has not access. We consider the better solution is to use monitors rather than mutex semaphores since unfortunately semaphores do not resolve the problem of deadlock. DYMO uses monitors to implement semaphores. The monitors approach is supported in SunOS which has a light-weight processes library. Figure 9. An example of condition structure. The same solution with semaphores implemented by monitors is useful to build an active objects model with a variable number of server processes for every entity. This implementation supports an entity may execute a few delegated actions the same time. When a new delegated action is requested the delegated entity creates a new server process and destroys it when the action is completed. 8 MODEL EVOLUTION Model evolution is a quasi-parallel evolution of model active entities. The model active entities have associated behaviors which define the sequence of action executed by every entity. The entity behavior is interpreted and executed by light-weight processes. Actions are initiated by model entities and operate in a concurrent manner on the same set of model entities. The main characteristic of the model is the state of model and the behavior of model entities may be dynamical modified by the model itself and by the external modules such as user, application, and graphical systems. An active entity can be dynamically associated with a behavior that can be dynamically modified also. The model can change the behavior parameters and the trajectory positions: positions set, position name, coordinates and position rules. 8.1 Condition Evaluation The conditions and expressions as they have been above-stated, are deterministic grammar rules. For the reason of speed execution a condition is a data structure rather than a string of characters that have to be compiled. A condition data structure is a tree of objects (Figure 9), from the point of view of programming language. The structure of the object consists of an operator and two terms, and methods to evaluate the object as tree node. The operator may be a logical, relational, string, or arithmetic operator. The term may be another tree node such as another object indeed, or a get action. Therefore finally the condition evaluation consists in a get action execution. ![Figure 9](image9.png) Active entity - behaviour processor - server processor Behaviour definition Message action ![Figure 10](image10.png) Figure 10. To execute a current action the behaviour processor sends a message to the own or to another server processor. The condition and the expression are evaluated by the behavior processor for an object, a variable or a flag. The condition evaluation gives the value for a flag entity. The expression evaluation gives the value for a variable. Conditions and expressions are components of active object behavior. The experimented model has condition and expression evaluation in rule structure only rather than an extended variant of the model with expression as action terms. For example the x coordinate of a new position in a create action could be an arithmetic expression. 8.2 Action Execution The behavior processor executes the behavior of active entities. The consequence of behavior interpretation is a sequence of actions. For variables and flags the behavior execution consists of a sequence of get actions to evaluate conditions and expressions which define the entity values. For active objects there is a above-mentioned set of actions. All actions are executed by delegation. To delegate another entity to execute an action the first entity sends a message to the second entity, called delegated entity. As it was presented the message specifies an action object the delegated entity executes it (Figure 10). Any action is an object from the point of view of the programming language (i.e. C++). The object obeys the principle of encapsulation. It consists of action parameters and methods to access the action structure. The formal structure of an action object is as follows: ```plaintext object_action { operation, delegated entity, entity name, specific action parameters, object methods } ``` There are two circumstances: (1) the action data structure is already defined by the model developer through user interface, and (2) the action data structure have to be built while the model evolution is running. The second situation occurs when an action invocation is a consequence of a main requested action. For instance, the instantiate action needs get and put actions. After the delegated action is completed the action data structure is destroyed. The actions such as append, get and put, activate, show, jump, rotate, translate and scale, just change an attribute or a parameter from an entity structure. Therefore the action execution is simple, as it was already mentioned. The execution of create, delete and instantiate actions arises a few difficulties. Therefore they are presented further on. ### 8.2.1 Create Action Execution The create action is an exception of action execution. The create action is performed by the owner behavior processor without delegation since it does not need information about other model entities. The create action structure specifies the type and the position of the entity that have to be created also. ### 8.2.2 Delete Action Execution An active object executes the delete action by delegation. If delegates the own server processor to delete an object element. It is forbidden to delete the owner object itself. An delegated server processor may delete the owner object only if the object is not engaged into a current action. For respecting the atomicity of the model any entity destruction must be performed only if the specified entity has not an active delegation. An active delegation means the entity has delegated another entity or it has been delegated by another. If the delegated object is engaged in an delegated action the delete action will be completed after the object finishes the engagement. Also, to respect the consistency of the model the deleting of an entity which is a reference must be resolved as an error and the delete action must abort. For instance is not allowed to delete a behavior linked with at least one active object. Another useful characteristic of the model would be protected entities. A protected entity is controlled by an entity attribute and specifies the entity deletion is forbidden. In the case of complex objects the delete action is a recursive action, since have to delete all components objects. Let be an object B which has the parent object A and the component objects C1, C2,..,Cn. If an object M have to delete the object B the delete action includes the following actions: 1. object M delegates the object B to execute the delete action; 2. object B stops its behavior; 3. object B delegates object A to delete object B from its components; 4. object B delegates all components C1,..,Cn to execute the delete action; 5. object B replies to delete action message and performs the delete operation. ### 8.2.3 Instantiate Action Execution In the case of complex objects the delete action is a recursive action, since have to delete all components objects. Let be an object B which has the parent object A and the component objects C1, C2,..,Cn. If an object M have to delete the object B the delete action includes the following actions: Instantiate action is executed by delegation. The current active object delegates the prototype entity to create own instance, excepting the case of behavior instantiating. The instance for a behavior entity is created by an active object. Unlike the previous version of DYMO, last experimented version creates any instance as an independent entity. There is not any connection between prototype and its instance. The instance entity retains the same structure, behavior, attributes and processors. Any case the instance entity gets new name and position. In the case of behavior entity the instance just gets a new name. Instance action is a complex action which consists of a set of assign actions (get and put actions). The get and put actions copy the characteristics of prototype to the instance entity. The prototype entity replies to the instantiate action message only when all assign actions are completed. 9 DIALOGUE MODELLING The active model provides a solid interaction. The model contains consistent information that allow access to all entities and their elements through user interface by external dialogue. All model elements are identified by unique names and positions. The paper just highlights these characteristics without to detail them. The DYMO experiment does not yet contains an interface implementation. 9.1 Interface Language *Interface language* consists of symbols and rules used in the *dialogue* between active model and external modules, especially the user and model developer. The interface language is the language used to construct the *external dialogue* between model and user. Interface language denotes also, the language which describes the model saved into an external file and which allows to reload the model into system memory. This kind language is not the purpose of this paper. The model entities and their elements are identified by *unique names*. For example objects, variables, flags, behaviors, positions, rules, attributes, parameters, have unique names that identifies entities and their elements in interface language and internal encoding. Interface language includes *symbolic constants* like OP_CREATE, EN_OBJECT, VAR_DYNAMIC, BH_POSITION, INTEGER_VALUE, and so on, that identify entity and element types. They are used to build the deterministic structures like rules, conditions, actions, objects, attributes, and so on. In a menu based manner and using the direct manipulation the user selects, builds, operates on model elements. The model contains consistent information that allow access to all entities and their elements through user interface by interface language. One of the significant facility is to edit behavior rules. The editing process includes operation such as condition editing, action editing and position specification. The grammar rules that define the interface language are simple and deterministic. Therefore the syntactic forms may be built in a linear manner, from left to right side. The syntactic form is not a problem for a textual editing but it have to allow the direct manipulation approach. Model positions are defined in a *normalized abstract coordinates space*. The interface language may use an user coordinates system and user measurement units. The user interface environment must provide the graphical presentation of the model entities. It is essential to have graphical presentation and to manipulate the set of trajectory positions. That provides the possibility to manipulate the *abstract entities* such as: velocity, time, future events, parallel actions, relation between active objects, behavior synchronization, and so on. In visual programming the interface have to provide visual presentations to a better understanding of the links between abstract notions manipulated in applications. Therefore the trajectory is a space-temporal evolution. It has a graphical presentation with elements that can be manipulated. The direct manipulation of model entities inside the abstract space is similar with the direct manipulation of application objects inside the virtual space of application. 9.2 User Interface Environments An active model application consists of the kernel that is an active object model linked with external modules such as user interface, graphical system, and application component. The *User Interface Environment (UIE)* should consist of the tools and the methodology to develop active model applications. UIE allows visual programming. UIE should provide operations such as: - defining and developing model entities; - editing by direct manipulation the behavior of model active entities; saving and loading the active model; * defining the links between active model and external modules; * developing active model as an independent component of application systems; * an incremental improvement of the model without consequences on external connected modules; * connecting the already built active model to various graphical systems, user interfaces, and application components. UIE emphasizes on active model features rather than User Interface Management Systems (UIDE) that emphasizes on dialogue and application component developing. UIDE provides tools for dialogue developing, application component programming, and software application improvement. 9.3 Internal Dialogue. Interactors The active model resolves one of the most difficult problem of the software applications that is the separation between application component and interface component. That problem is known also as the dialogue independence. The active model approach provides a user oriented developing of applications where the same model contains the application entities and interface objects. Model entities are application entities and the behavior of the model evolves the application algorithm. Interactors or active objects with interaction processors implements the interface objects and their behavior. A very flexible and interactive approach is available to define the model entities behavior. Internal dialogue has an homogeneous solution by interactors that implement the interface between model and external modules. The variables of internal dialogue between application component and dialogue component are represented by the application attributes of model active entities. 10 CONCLUSIONS The experimented active model has proved a dynamic model implementation is reasonable on a sequential machine. Indubitable a machine with a special parallel structure offers a better but a more expensive parallelism. However a concurrent software approach provides a good solution for a quasi-parallel evolution of the active object model. The experiment with DYMO model emphasizes the following conclusions: * the experimented set of model entities is consistent and support an active and dynamic evolution. New experiments are necessary to establish a flexible set of interactors that support interfaces with various user interface, application components, graphical systems, under various software platforms and operating systems; * the structures for active objects, variables, flags, behavior, trajectories, and so on, are simple and allow an homogeneous manipulation. The entities structures support a dynamic functionality, unique identification, interactive applications, concurrent evolution and abstract space manipulations. The unique identification by names allows the implementation on distributed object based programming systems; * the light-weight processes or threads such as: behavior, server, display and interactions, prove a cheap, quasi-parallel, concurrent and reasonable fast execution; * a flexible, dynamic and interactive behavior for active entities has been defined; * a consistent modelling of notion such as: behavior, trajectory, trajectory position, rule, condition, expression, action, operation, and action parameters support an interactive, incremental and dynamical development of active object model. * the model concepts emphasize the notion of trajectory which provides a space-temporal behavior definition and the possibility of direct manipulation of the abstract notions. * has been verified a simple set of 12 actions that allows complex behaviors and various type of applications. * action execution by delegation has been experimented on the conceptual defined model. * the experiment has proved the active object model is a considerable solution for visual programming environments. The extension of the DYMO experiment should consist on the following: * to develop a direct manipulation based user interface language; * to define and experiment a User Interface Environment that allows the developing and execution of active object model; * to experiment the possibility of an incremental and independent development of active object models. 11 REFERENCES [27] ERCIM Constraints management Workshop Report. Edited by David A. Duce, Rutherford Appleton Laboratory. Abingdon, United Kingdom, 24-25 April, 1995.
{"Source-Url": "http://cgis.utcluj.ro/gorgan/res/publ/papers/dy.PDF", "len_cl100k_base": 15701, "olmocr-version": "0.1.50", "pdf-total-pages": 28, "total-fallback-pages": 0, "total-input-tokens": 62178, "total-output-tokens": 18659, "length": "2e13", "weborganizer": {"__label__adult": 0.0002789497375488281, "__label__art_design": 0.0006089210510253906, "__label__crime_law": 0.00023066997528076172, "__label__education_jobs": 0.0017461776733398438, "__label__entertainment": 7.474422454833984e-05, "__label__fashion_beauty": 0.00012624263763427734, "__label__finance_business": 0.0002288818359375, "__label__food_dining": 0.00023365020751953125, "__label__games": 0.0007305145263671875, "__label__hardware": 0.0012645721435546875, "__label__health": 0.0002727508544921875, "__label__history": 0.00036787986755371094, "__label__home_hobbies": 9.649991989135742e-05, "__label__industrial": 0.0004162788391113281, "__label__literature": 0.00029158592224121094, "__label__politics": 0.00020956993103027344, "__label__religion": 0.0004606246948242187, "__label__science_tech": 0.0306854248046875, "__label__social_life": 6.830692291259766e-05, "__label__software": 0.01001739501953125, "__label__software_dev": 0.95068359375, "__label__sports_fitness": 0.0002007484436035156, "__label__transportation": 0.000518798828125, "__label__travel": 0.00017070770263671875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 82720, 0.0214]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 82720, 0.77941]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 82720, 0.88235]], "google_gemma-3-12b-it_contains_pii": [[0, 56, false], [56, 1942, null], [1942, 3344, null], [3344, 6419, null], [6419, 11871, null], [11871, 17077, null], [17077, 22996, null], [22996, 27043, null], [27043, 29851, null], [29851, 31892, null], [31892, 33869, null], [33869, 35114, null], [35114, 37597, null], [37597, 39976, null], [39976, 42453, null], [42453, 44836, null], [44836, 46730, null], [46730, 49613, null], [49613, 53701, null], [53701, 56763, null], [56763, 60819, null], [60819, 63312, null], [63312, 65333, null], [65333, 69624, null], [69624, 74261, null], [74261, 78468, null], [78468, 81683, null], [81683, 82720, null]], "google_gemma-3-12b-it_is_public_document": [[0, 56, true], [56, 1942, null], [1942, 3344, null], [3344, 6419, null], [6419, 11871, null], [11871, 17077, null], [17077, 22996, null], [22996, 27043, null], [27043, 29851, null], [29851, 31892, null], [31892, 33869, null], [33869, 35114, null], [35114, 37597, null], [37597, 39976, null], [39976, 42453, null], [42453, 44836, null], [44836, 46730, null], [46730, 49613, null], [49613, 53701, null], [53701, 56763, null], [56763, 60819, null], [60819, 63312, null], [63312, 65333, null], [65333, 69624, null], [69624, 74261, null], [74261, 78468, null], [78468, 81683, null], [81683, 82720, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 82720, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 82720, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 82720, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 82720, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 82720, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 82720, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 82720, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 82720, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 82720, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 82720, null]], "pdf_page_numbers": [[0, 56, 1], [56, 1942, 2], [1942, 3344, 3], [3344, 6419, 4], [6419, 11871, 5], [11871, 17077, 6], [17077, 22996, 7], [22996, 27043, 8], [27043, 29851, 9], [29851, 31892, 10], [31892, 33869, 11], [33869, 35114, 12], [35114, 37597, 13], [37597, 39976, 14], [39976, 42453, 15], [42453, 44836, 16], [44836, 46730, 17], [46730, 49613, 18], [49613, 53701, 19], [53701, 56763, 20], [56763, 60819, 21], [60819, 63312, 22], [63312, 65333, 23], [65333, 69624, 24], [69624, 74261, 25], [74261, 78468, 26], [78468, 81683, 27], [81683, 82720, 28]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 82720, 0.00516]]}
olmocr_science_pdfs
2024-11-30
2024-11-30
8027abe8bd0009e9a42da7df0a20fa81d13512ab
Abstract: Maxim's 1-Wire® devices each have a 64-bit unique registration number in read-only memory (ROM) that is used to address them individually by a 1-Wire master in a 1-Wire network. If the ROM numbers of the slave devices on the 1-Wire network are not known, then using a search algorithm can discover them. This document explains the search algorithm in detail and provides an example implementation for rapid integration. This algorithm is valid for all current and future devices that feature a 1-Wire interface. Introduction Maxim's 1-Wire devices each have a 64-bit unique registration number in read-only memory (ROM) (Figure 1) that is used to address them individually by a 1-Wire master in a 1-Wire network. If the ROM numbers of the slave devices on the 1-Wire network are not known, then they can be discovered by using a search algorithm. This document explains the search algorithm in detail and provides an example implementation for rapid integration. This algorithm is valid for all current and future devices that feature a 1-Wire interface. Search Algorithm The search algorithm is a binary tree search where branches are followed until a device ROM number, or leaf, is found. Subsequent searches then take the other branch paths until all of the leaves present are discovered. The search algorithm begins with the devices on the 1-Wire being reset using the reset and presence pulse sequence. If this is successful then the 1-byte search command is sent. The search command readies the 1-Wire devices to begin the search. There are two types of search commands. The normal search command (F0 hex) performs a search... with all devices participating. The alarm or conditional search command (EC hex) performs a search with only the devices that are in some sort of alarm state. This reduces the search pool to quickly respond to devices that need attention. Following the search command, the actual search begins with all participating devices simultaneously sending the first bit (least significant) in their ROM number (also called registration number). (See Figure 1.) As with all 1-Wire communication, the 1-Wire master starts every bit whether it is data to be read or written to the slave devices. Due to the characteristics of the 1-Wire, when all devices respond at the same time, this results in a logical AND of the bits sent. After the devices send the first bit of their ROM number, the master initiates the next bit and the devices then send the complement of the first bit. From these two bits, information can be derived about the first bit in the ROM numbers of the participating devices. (See Table 1.) <table> <thead> <tr> <th>Table 1. Bit Search Information</th> </tr> </thead> <tbody> <tr> <td>Bit (true)</td> </tr> <tr> <td>0 0</td> </tr> <tr> <td>0 1</td> </tr> <tr> <td>1 0</td> </tr> <tr> <td>1 1</td> </tr> </tbody> </table> According to the search algorithm, the 1-Wire master must then send a bit back to the participating devices. If the participating device has that bit value, it continues participating. If it does not have the bit value, it goes into a wait state until the next 1-Wire reset is detected. This 'read two bits' and 'write one bit' pattern is then repeated for the remaining 63 bits of the ROM number (see Table 2). In this way the search algorithm forces all but one device to go into this wait state. At the end of one pass, the ROM number of this last device is known. On subsequent passes of the search, a different path (or branch) is taken to find the other device ROM numbers. Note that this document refers to the bit position in the ROM number as bit 1 (least significant) to bit 64 (most significant). This convention was used instead of bit 0 to bit 63 for convenience, to allow initialization of discrepancy counters to 0 for later comparisons. <table> <thead> <tr> <th>Table 2. 1-Wire Master and Slave Search Sequence</th> </tr> </thead> <tbody> <tr> <td>Master</td> </tr> <tr> <td>1-Wire reset stimulus</td> </tr> <tr> <td>Write search command (normal or alarm)</td> </tr> <tr> <td>Read 'AND' of bit 1</td> </tr> <tr> <td>Read 'AND' of complement bit 1</td> </tr> <tr> <td>Write bit 1 direction (according to algorithm)</td> </tr> </tbody> </table> Read 'AND' of bit 64 Each slave sends bit 64 of its ROM number. Read 'AND' of complement bit 64 Each slave sends complement bit 64 of its ROM number. Write bit 64 direction (according to algorithm) Each slave receives the bit written by master, if bit read is not the same as bit 64 of its ROM number then go into a wait state. On examination of Table 1, it is obvious that if all of the participating devices have the same value in a bit position then there is only one choice for the branch path to be taken. The condition where no devices are participating is an atypical situation that can arise if the device being discovered is removed from the 1-Wire during the search. If this situation arises then the search should be terminated and a new search could be done starting with a 1-Wire reset. A discrepancy, the condition where there are both 0s and 1s in the bit position, is the key to finding devices in the subsequent searches. The search algorithm specifies that on the first pass, when there is a discrepancy (bit/complement = 0/0), the '0' path is taken. Note that this is arbitrary for this particular algorithm. Another algorithm could be devised to use the '1' path first. The bit position for the last discrepancy is recorded for use in the next search. Table 3 describes the paths that are taken on subsequent searches when a discrepancy occurs. <table> <thead> <tr> <th>Search Bit Position vs Last Discrepancy</th> <th>Path Taken</th> </tr> </thead> <tbody> <tr> <td>=</td> <td>Take the '1' path</td> </tr> <tr> <td>&lt;</td> <td>Take the same path as last time (from last ROM number found)</td> </tr> <tr> <td>&gt;</td> <td>Take the '0' path</td> </tr> </tbody> </table> The search algorithm also keeps track of the last discrepancy that occurs within the first eight bits of the algorithm. The first eight bits of the 64-bit registration number is a family code. As a result, the devices discovered during the search are grouped into family types. The last discrepancy within that family code can be used to selectively skip whole groups of 1-Wire devices. See the description of ADVANCED SEARCH VARIATIONS for doing selective searches. The 64-bit ROM number also contains an 8-bit cyclic-redundancy-check (CRC). This CRC value is verified to ensure that only correct ROM numbers are discovered. See Figure 1 for the layout of the ROM number. The DS2480B Serial to 1-Wire Line Driver performs some of this same search algorithm in hardware. See the DS2480B data sheet and application note 192, Using the DS2480B Serial 1-Wire Line Driver for details. The DS2490 USB to 1-Wire bridge performs the entire search in hardware. Figure 2 shows a flow chart of the search sequence. Note the Reference side bar that explains the terms used in the flow chart. These terms are also used in the source code appendix to this document. Perform a 1-Wire Reset Presence Detected? Yes Is Last_DeviceFlag = 1? Yes Set id_bit_number to 1. Set last_zero to 0. Send search command (0F or EC hex) Read bit (id_bit) and complement ID bit (cmp_id_bit) from 1-Wire id_bit = cmp_id_bit = 1 Yes No id_bit = cmp_id_bit = 0? Yes Set search_direction bit to id_bit No id_bit_number = LastDiscrepancy Yes Set search_direction bit to current id_bit_number No search_direction = 0? Yes Set last_zero to current id_bit_number No Is last_zero < 5? Yes Set LastFamilyDiscrepancy to last_zero No id_bit_number > 64? Yes Set LastDiscrepancy to last_zero No Reference cmp_id_bit - the complement of the id bit. This bit is the AND of the complement of all of the id_bit_number bits of the devices that are still participating in the search. id_bit - the first bit read in a bit search sequence. This bit is the AND of all of the id_bit_number bits of the devices that are still participating in the search. id_bit_number - the ROM bit number 1 to 64 currently being searched. LastDeviceFlag - flag to indicate previous search was the last device. LastDiscrepancy - bit index that identifies from which bit the (next) search discrepancy check should start. LastFamilyDiscrepancy - bit index that identifies the LastDiscrepancy within the first 8-bit family code of ROM number. last_zero - bit position of the last zero written where there was a discrepancy. ROM_NO - 6-byte buffer that contains the current ROM registration number discovered. search_direction - bit value indicating the direction of the search. All devices with this bit stay in the search and the rest go into a wait state for a 1-Wire reset. Figure 2. Search flow. There are two basic types of operations that can be performed by using the search algorithm by manipulating the LastDiscrepancy, LastFamilyDiscrepancy, LastDeviceFlag, and ROM_NO register values (see Table 4). These operations concern basic discovery of the ROM numbers of 1-Wire devices. First The 'FIRST' operation is to search on the 1-Wire for the first device. This is performed by setting LastDiscrepancy, LastFamilyDiscrepancy, and LastDeviceFlag to zero and then doing the search. The resulting ROM number can then be read from the ROM_NO register. If no devices are present on the 1-Wire the reset sequence does not detect a presence and the search is aborted. Next The 'NEXT' operation is to search on the 1-Wire for the next device. This search is usually performed after a 'FIRST' operation or another 'NEXT' operation. It is performed by leaving the state unchanged from the previous search and performing another search. The resulting ROM number can then be read from the ROM_NO register. If the previous search was the last device on the 1-Wire then the result is FALSE and the condition is set to execute a 'FIRST' with the next call of the search algorithm. Figure 3 (a, b, c) goes through a simple search example with three devices. For illustration, this example assumes devices with a 2-bit ROM number only. Devices A = 01 (binary: bit 2, bit 1) B = 00 C = 11 FIRST bit 1 Read bit complement-bit Read Write direction Bit written by master, path taken A 1 0 B 0 1 C 1 0 AND result of 'true' bit read 0 0 0 (bit position > LastDiscrepancy) bit 2 Read bit complement-bit Read Write direction A (wait state) B 0 1 C (wait state) 0 1 0 (only one path available) Device B is found 00, LastDiscrepancy is now 1 NEXT bit 1 Read bit complement-bit Read Write direction A 1 0 B 0 1 C 1 0 0 0 1 (bit position = LastDiscrepancy) bit 2 Read bit complement-bit Read Write direction A 0 1 B (wait state) C 1 0 0 0 0 (bit position > LastDiscrepancy) Device A is found 01, LastDiscrepancy is now 2 NEXT bit 1 Read bit complement-bit Read Write direction A 1 0 B 0 1 C 1 0 0 0 1 (bit position < LastDiscrepancy) bit 2 Read bit complement-bit Read Write direction A (wait state) B 1 0 C 1 0 0 0 1 (bit position = LastDiscrepancy) Device C is found 11, LastDeviceFlag is TRUE Note: Each branching at a bit level denotes a ‘discrepancy’ where both the bit and complement-bit return '0'. Advanced Search Variations There are three advanced search variations using the same state information, namely LastDiscrepancy, LastFamilyDiscrepancy, LastDeviceFlag, and ROM_NO. These variations allow specific family types to be... targeted or skipped and device present verification (see Table 4). Verify The 'VERIFY' operation verifies if a device with a known ROM number is currently connected to the 1-Wire. It is accomplished by supplying the ROM number and doing a targeted search on that number to verify it is present. First, set the ROM_NO register to the known ROM number. Then set the LastDiscrepancy to 64 (40 hex) and the LastDeviceFlag to 0. Perform the search operation and then read the ROM_NO result. If the search was successful and the ROM_NO remains the ROM number that was being searched for, then the device is currently on the 1-Wire. Target Setup The 'TARGET SETUP' operation is a way to preset the search state to first find a particular family type. Each 1-Wire device has a one byte family code embedded within the ROM number (see Figure 1). This family code allows the 1-Wire master to know what operations this device is capable of. If there are multiple devices on the 1-Wire it is common practice to target a search to only the family of devices that are of interest. To target a particular family, set the desired family code byte into the first byte of the ROM_NO register and fill the rest of the ROM_NO register with zeros. Then set the LastDiscrepancy to 64 (40 hex) and both LastDeviceFlag and LastFamilyDiscrepancy to 0. When the search algorithm is next performed the first device of the desired family type is discovered and placed in the ROM_NO register. Note that if no devices of the desired family are currently on the 1-Wire, then another type will be found, so the family code in the resulting ROM_NO must be verified after the search. Family Skip Setup The 'FAMILY SKIP SETUP' operation sets the search state to skip all of the devices that have the family code that was found in the previous search. This operation can only be performed after a search. It is accomplished by copying the LastFamilyDiscrepancy into the LastDiscrepancy and clearing out the LastDeviceFlag. The next search then finds devices that come after the current family code. If the current family code group is the last group in the search then the search returns with the LastDeviceFlag set. <table> <thead> <tr> <th>Table 4. Search Variations State Setup</th> </tr> </thead> <tbody> <tr> <td></td> </tr> <tr> <td>FIRST</td> </tr> <tr> <td>NEXT</td> </tr> <tr> <td>VERIFY</td> </tr> <tr> <td>TARGET SETUP</td> </tr> </tbody> </table> Conclusion The supplied search algorithm allows the discovery of the individually unique ROM numbers from any given group of 1-Wire devices. This is essential to any multidrop 1-Wire application. With the ROM numbers in hand, each 1-Wire device can be selected individually for operations. This document also discusses search variations to find or skip particular 1-Wire device types. See the Appendix for a 'C' code example implementation of the search and all of the search variations. Appendix Figure 4 shows a 'C' code implementation of the search algorithm along with a function for each search variation. The FamilySkipSetup and TargetSetup functions do not actually do a search, they just set up the search registers so the next 'Next' skips or finds the desired type. Note that the low-level 1-Wire functions are implemented with calls to the TMEX API. These calls are for test purposes and can be replaced with platform-specific calls. See application note 155, "1-Wire® Software Resource Guide Device Description" for a description of the TMEX API and other 1-Wire APIs. The TMEX API test implementation of the following code example can be downloaded from the Maxim website. ```c // TMEX API TEST BUILD DECLARATIONS #define TMEXUTIL #include "ibtmexcw.h" long session_handle; // END TMEX API TEST BUILD DECLARATIONS // definitions #define FALSE 0 #define TRUE 1 // method declarations int OWFirst(); int OWNext(); int OWVerify(); void OWTargetSetup(unsigned char family_code); void OWFamilySkipSetup(); int OWReset(); void OWWriteByte(unsigned char byte_value); void OWWriteBit(unsigned char bit_value); unsigned char OWReadBit(); int OWSearch(); unsigned char docrc8(unsigned char value); // global search state ``` unsigned char ROM_NO[8]; int LastDiscrepancy; int LastFamilyDiscrepancy; int LastDeviceFlag; unsigned char crc8; // Find the 'first' devices on the 1-Wire bus // Return TRUE : device found, ROM number in ROM_NO buffer // FALSE : no device present // int OWFirst() { // reset the search state LastDiscrepancy = 0; LastDeviceFlag = FALSE; LastFamilyDiscrepancy = 0; return OWSearch(); } // Find the 'next' devices on the 1-Wire bus // Return TRUE : device found, ROM number in ROM_NO buffer // FALSE : device not found, end of search // int OWNext() { // leave the search state alone return OWSearch(); } // Perform the 1-Wire Search Algorithm on the 1-Wire bus using the existing // search state. // Return TRUE : device found, ROM number in ROM_NO buffer // FALSE : device not found, end of search // int OWSearch() { int id_bit_number; int last_zero, rom_byte_number, search_result; int id_bit, cmp_id_bit; unsigned char rom_byte_mask, search_direction; // initialize for search id_bit_number = 1; last_zero = 0; rom_byte_number = 0; rom_byte_mask = 1; search_result = 0; crc8 = 0; // if the last call was not the last one if (!LastDeviceFlag) { // 1-Wire reset if (!OWReset()) { // reset the search LastDiscrepancy = 0; LastDeviceFlag = FALSE; LastFamilyDiscrepancy = 0; return FALSE; } } // issue the search command OWWriteByte(0xF0); // loop to do the search do { // read a bit and its complement id_bit = OWReadBit(); cmp_id_bit = OWReadBit(); // check for no devices on 1-wire if ((id_bit == 1) && (cmp_id_bit == 1)) break; else { // all devices coupled have 0 or 1 if (id_bit != cmp_id_bit) search_direction = id_bit; // bit write value for search else { // if this discrepancy if before the Last Discrepancy // on a previous next then pick the same as last time if (id_bit_number < LastDiscrepancy) search_direction = (((ROM_NO[rom_byte_number] & rom_byte_mask) > 0)); else // if equal to last pick 1, if not then pick 0 search_direction = (id_bit_number == LastDiscrepancy); // if 0 was picked then record its position in LastZero if (search_direction == 0) { } last_zero = id_bit_number; // check for Last discrepancy in family if (last_zero < 9) LastFamilyDiscrepancy = last_zero; // set or clear the bit in the ROM byte rom_byte_number // with mask rom_byte_mask if (search_direction == 1) ROM_NO[rom_byte_number] |= rom_byte_mask; else ROM_NO[rom_byte_number] &= ~rom_byte_mask; // serial number search direction write bit OWWriteBit(search_direction); // increment the byte counter id_bit_number // and shift the mask rom_byte_mask id_bit_number++; rom_byte_mask <<= 1; // if the mask is 0 then go to new SerialNum byte rom_byte_number and reset mask if (rom_byte_mask == 0) { docrc8(ROM_NO[rom_byte_number]); // accumulate the CRC rom_byte_number++; rom_byte_mask = 1; } } } while(rom_byte_number < 8); // loop until through all ROM bytes 0-7 // if the search was successful then if (!((id_bit_number < 65) || (crc8 != 0))) { // search successful so set LastDiscrepancy,LastDeviceFlag,search_result LastDiscrepancy = last_zero; // check for last device if (LastDiscrepancy == 0) LastDeviceFlag = TRUE; search_result = TRUE; } } // if no device found then reset counters so next 'search' will be like a // first if (!search_result || !ROM_NO[0]) { LastDiscrepancy = 0; LastDeviceFlag = FALSE; LastFamilyDiscrepancy = 0; search_result = FALSE; } return search_result; } //-------------------------------------------------------------------------- // Verify the device with the ROM number in ROM_NO buffer is present. // Return TRUE : device verified present // FALSE : device not present // int OWVerify() { unsigned char rom_backup[8]; int i,rslt,ld_backup,ldf_backup,lfd_backup; // keep a backup copy of the current state for (i = 0; i < 8; i++) { rom_backup[i] = ROM_NO[i]; } ld_backup = LastDiscrepancy; ldf_backup = LastDeviceFlag; lfd_backup = LastFamilyDiscrepancy; // set search to find the same device LastDiscrepancy = 64; LastDeviceFlag = FALSE; if (OWSearch()) { // check if same device found rslt = TRUE; for (i = 0; i < 8; i++) { if (rom_backup[i] != ROM_NO[i]) { rslt = FALSE; break; } } } else rslt = FALSE; // restore the search state for (i = 0; i < 8; i++) ROM_NO[i] = rom_backup[i]; LastDiscrepancy = ld_backup; LastDeviceFlag = ldf_backup; LastFamilyDiscrepancy = lfd_backup; // return the result of the verify return rslt; } //-------------------------------------------------------------------------- // Setup the search to find the device type 'family_code' on the next call // to OWNext() if it is present. // void OWTargetSetup(unsigned char family_code) { int i; // set the search state to find SearchFamily type devices ROM_NO[0] = family_code; for (i = 1; i < 8; i++) ROM_NO[i] = 0; LastDiscrepancy = 64; LastFamilyDiscrepancy = 0; LastDeviceFlag = FALSE; } //-------------------------------------------------------------------------- // Setup the search to skip the current device type on the next call // to OWNext(). // void OWFamilySkipSetup() { // set the Last discrepancy to last family discrepancy LastDiscrepancy = LastFamilyDiscrepancy; LastFamilyDiscrepancy = 0; // check for end of list if (LastDiscrepancy == 0) LastDeviceFlag = TRUE; } //-------------------------------------------------------------------------- // 1-Wire Functions to be implemented for a particular platform //-------------------------------------------------------------------------- // Reset the 1-Wire bus and return the presence of any device // Return TRUE : device present // FALSE : no device present // int OWReset() { // platform specific // TMEX API TEST BUILD return (TMTouchReset(session_handle) == 1); } // Send 8 bits of data to the 1-Wire bus // void OWWriteByte(unsigned char byte_value) { // platform specific // TMEX API TEST BUILD TMTouchByte(session_handle,byte_value); } // Send 1 bit of data to the 1-Wire bus // void OWWriteBit(unsigned char bit_value) { // platform specific // TMEX API TEST BUILD TMTouchBit(session_handle,(short)bit_value); } // Read 1 bit of data from the 1-Wire bus // Return 1 : bit read is 1 // 0 : bit read is 0 // unsigned char OWReadBit() { // platform specific // TMEX API TEST BUILD return (unsigned char)TMTouchBit(session_handle,0x01); } // TEST BUILD # Code Snippet ```c static unsigned char dscrc_table[] = { 0, 94,188,226, 97, 63,221,131,194,156,126, 32,163,253, 31, 65, 157,195, 33,127,252,162, 64, 30, 95, 1,227,189, 62, 96,130,220, 35,125,159,193, 66, 28,254,160,225,191, 93, 3,128,222, 60, 98, 190,224, 2, 92,223,129, 99, 61,124, 34,192,158, 29, 67,161,255, 70, 24,250,164, 39,121,155,197,132,218, 56,102,229,187, 89, 7, 219,133,103, 57,186,228, 6, 88, 25, 71,165,251,120, 38,196,154, 101, 59,217,135, 4, 90,184,230,167,249, 27, 69,198,152,122, 36, 248,166, 68, 26,153,199, 37,123, 58,100,134,216, 91, 5,231,185, 140,210, 48,110,237,179, 81, 15, 78, 16,242,172, 47,113,147,205, 17, 79,173,243,112, 46,204,146,211,141,111, 49,178,236, 14, 80, 175,241, 19, 77,206,144,114, 44,109, 51,209,143, 12, 82,176,238, 50,108,142,208, 83, 13,239,177,240,174, 76, 18,145,207, 45,115, 202,148,118, 40,171,245, 23, 73, 8, 86,180,234,105, 55,213,139, 87, 9,235,181, 54,104,138,212,149,203, 41,119,244,170, 72, 22, 233,183, 85, 11,136,214, 52,106, 43,117,151,201, 74, 20,246,168, 116, 42,200,150, 21, 75,169,247,182,232, 10, 84,215,137,107, 53}; // Calculate the CRC8 of the byte value provided with the current // global 'crc8' value. // Returns current global crc8 value // unsigned char docrc8(unsigned char value) { // See Application Note 27 // TEST BUILD crc8 = dscrc_table[crc8 ^ value]; return crc8; } // TEST BUILD MAIN // int main(short argc, char **argv) { short PortType=5,PortNum=1; int rslt,i,cnt; // TMEX API SETUP // get a session session_handle = TMExtendedStartSession(PortNum,PortType,NULL); if (session_handle <= 0) { printf("No session, %d\n",session_handle); exit(0); } ``` --- **Page 17 of 20** // setup the port rslt = TMSetup(session_handle); if (rslt != 1) { printf("Fail setup, %d\n", rslt); exit(0); } // END TMEX API SETUP // find ALL devices printf("\nFIND ALL\n"); cnt = 0; rslt = OWFirst(); while (rslt) { // print device found for (i = 7; i >= 0; i--) { printf("%02X", ROM_NO[i]); printf(" %d\n", ++cnt); } rslt = OWNext(); } // find only 0x1A printf("\nFIND ONLY 0x1A\n"); cnt = 0; OWTargetSetup(0x1A); while (OWNext()) { // check for incorrect type if (ROM_NO[0] != 0x1A) break; // print device found for (i = 7; i >= 0; i--) { printf("%02X", ROM_NO[i]); printf(" %d\n", ++cnt); } } // find all but 0x04, 0x1A, 0x23, and 0x01 printf("\nFIND ALL EXCEPT 0x10, 0x04, 0x0A, 0x1A, 0x23, 0x01\n"); cnt = 0; rslt = OWFirst(); while (rslt) { // check for incorrect type if ((ROM_NO[0] == 0x04) || (ROM_NO[0] == 0x1A) || (ROM_NO[0] == 0x01) || (ROM_NO[0] == 0x23) || (ROM_NO[0] == 0x0A) || (ROM_NO[0] == 0x10)) OWFamilySkipSetup(); else { // print device found for (i = 7; i >= 0; i--) printf("%02X", ROM_NO[i]); printf(" %d ",++cnt); } rslt = OWNext(); } // TMEX API CLEANUP // release the session TMEndSession(session_handle); // END TMEX API CLEANUP Revision History 01/30/02 Version 1.0—Initial release 05/16/03 Version 1.1—Corrections: Search ROM commands corrected to F0 hex. <table> <thead> <tr> <th>Related Parts</th> <th></th> <th>Free Samples</th> </tr> </thead> <tbody> <tr> <td><strong>DS18B20</strong></td> <td>Programmable Resolution 1-Wire Digital Thermometer</td> <td></td> </tr> <tr> <td><strong>DS18S20</strong></td> <td>1-Wire Parasite-Power Digital Thermometer</td> <td></td> </tr> <tr> <td><strong>DS1904</strong></td> <td>iButton RTC</td> <td></td> </tr> <tr> <td><strong>DS1920</strong></td> <td>iButton Temperature Logger</td> <td></td> </tr> <tr> <td><strong>DS1921G</strong></td> <td>Thermochron iButton Device</td> <td></td> </tr> <tr> <td><strong>DS1963S</strong></td> <td>iButton Monetary Device with SHA-1 Function</td> <td></td> </tr> <tr> <td><strong>DS1971</strong></td> <td>iButton 256-Bit EEPROM</td> <td></td> </tr> <tr> <td><strong>DS1973</strong></td> <td>iButton 4Kb EEPROM</td> <td></td> </tr> <tr> <td><strong>DS1982</strong></td> <td>iButton 1Kb Add-Only</td> <td></td> </tr> <tr> <td><strong>DS1985</strong></td> <td>iButton 16Kb Add-Only</td> <td></td> </tr> <tr> <td><strong>DS1990A</strong></td> <td>iButton Serial Number</td> <td></td> </tr> <tr> <td><strong>DS1992</strong></td> <td>iButton 1Kb/4Kb Memory</td> <td></td> </tr> <tr> <td><strong>DS1993</strong></td> <td>iButton 1Kb/4Kb Memory</td> <td></td> </tr> <tr> <td><strong>DS1995</strong></td> <td>iButton 16Kb Memory</td> <td></td> </tr> <tr> <td>Part Number</td> <td>Description</td> <td>Free Samples</td> </tr> <tr> <td>------------</td> <td>-----------------------------------------------------------------------------------------</td> <td>--------------</td> </tr> <tr> <td>DS1996</td> <td>iButton 64Kb Memory</td> <td></td> </tr> <tr> <td>DS2401</td> <td>Silicon Serial Number</td> <td></td> </tr> <tr> <td>DS2406</td> <td>Dual Addressable Switch Plus 1Kb Memory</td> <td></td> </tr> <tr> <td>DS2408</td> <td>1-Wire 8-Channel Addressable Switch</td> <td></td> </tr> <tr> <td>DS2411</td> <td>Silicon Serial Number with V&lt;sub&gt;CC&lt;/sub&gt; Input</td> <td></td> </tr> <tr> <td>DS2417</td> <td>1-Wire Time Chip With Interrupt</td> <td></td> </tr> <tr> <td>DS2431</td> <td>1024-Bit 1-Wire EEPROM</td> <td></td> </tr> <tr> <td>DS2432</td> <td>1Kb Protected 1-Wire EEPROM with SHA-1 Engine</td> <td></td> </tr> <tr> <td>DS2433</td> <td>4Kb 1-Wire EEPROM</td> <td></td> </tr> <tr> <td>DS2438</td> <td>Smart Battery Monitor</td> <td></td> </tr> <tr> <td>DS2450</td> <td>1-Wire Quad A/D Converter</td> <td></td> </tr> <tr> <td>DS2502</td> <td>1Kb Add-Only Memory</td> <td></td> </tr> <tr> <td>DS2505</td> <td>16Kb Add-Only Memory</td> <td></td> </tr> <tr> <td>DS2506</td> <td>64Kb Add-Only Memory</td> <td></td> </tr> <tr> <td>DS2740</td> <td>High-Precision Coulomb Counter</td> <td></td> </tr> <tr> <td>DS2762</td> <td>High-Precision Li+ Battery Monitor with Alerts</td> <td></td> </tr> <tr> <td>MAX31826</td> <td>1-Wire Digital Temperature Sensor with 1Kb Lockable EEPROM</td> <td></td> </tr> </tbody> </table> **More Information** For Technical Support: [http://www.maximintegrated.com/support](http://www.maximintegrated.com/support) For Samples: [http://www.maximintegrated.com/samples](http://www.maximintegrated.com/samples) Other Questions and Comments: [http://www.maximintegrated.com/contact](http://www.maximintegrated.com/contact) APPLICATION NOTE 187, AN187, AN 187, APP187, Appnote187, Appnote 187 © 2013 Maxim Integrated Products, Inc.
{"Source-Url": "http://pdfserv.maximintegrated.com/en/an/AN187.pdf", "len_cl100k_base": 8303, "olmocr-version": "0.1.50", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 36230, "total-output-tokens": 9713, "length": "2e13", "weborganizer": {"__label__adult": 0.000957012176513672, "__label__art_design": 0.0008029937744140625, "__label__crime_law": 0.0009317398071289062, "__label__education_jobs": 0.0005354881286621094, "__label__entertainment": 0.00018990039825439453, "__label__fashion_beauty": 0.0005578994750976562, "__label__finance_business": 0.0007853507995605469, "__label__food_dining": 0.0007610321044921875, "__label__games": 0.0028018951416015625, "__label__hardware": 0.362548828125, "__label__health": 0.0007147789001464844, "__label__history": 0.00045108795166015625, "__label__home_hobbies": 0.0006504058837890625, "__label__industrial": 0.004917144775390625, "__label__literature": 0.0002887248992919922, "__label__politics": 0.0004494190216064453, "__label__religion": 0.000797271728515625, "__label__science_tech": 0.176025390625, "__label__social_life": 7.134675979614258e-05, "__label__software": 0.0206146240234375, "__label__software_dev": 0.420654296875, "__label__sports_fitness": 0.0009889602661132812, "__label__transportation": 0.0022106170654296875, "__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, 31137, 0.10263]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 31137, 0.47587]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 31137, 0.78565]], "google_gemma-3-12b-it_contains_pii": [[0, 1649, false], [1649, 4651, null], [4651, 7590, null], [7590, 9296, null], [9296, 10629, null], [10629, 11615, null], [11615, 11725, null], [11725, 11959, null], [11959, 14807, null], [14807, 16549, null], [16549, 17673, null], [17673, 19033, null], [19033, 20170, null], [20170, 21357, null], [21357, 22718, null], [22718, 23591, null], [23591, 25402, null], [25402, 26440, null], [26440, 28216, null], [28216, 31137, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1649, true], [1649, 4651, null], [4651, 7590, null], [7590, 9296, null], [9296, 10629, null], [10629, 11615, null], [11615, 11725, null], [11725, 11959, null], [11959, 14807, null], [14807, 16549, null], [16549, 17673, null], [17673, 19033, null], [19033, 20170, null], [20170, 21357, null], [21357, 22718, null], [22718, 23591, null], [23591, 25402, null], [25402, 26440, null], [26440, 28216, null], [28216, 31137, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 31137, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 31137, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 31137, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 31137, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 31137, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 31137, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 31137, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 31137, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 31137, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 31137, null]], "pdf_page_numbers": [[0, 1649, 1], [1649, 4651, 2], [4651, 7590, 3], [7590, 9296, 4], [9296, 10629, 5], [10629, 11615, 6], [11615, 11725, 7], [11725, 11959, 8], [11959, 14807, 9], [14807, 16549, 10], [16549, 17673, 11], [17673, 19033, 12], [19033, 20170, 13], [20170, 21357, 14], [21357, 22718, 15], [22718, 23591, 16], [23591, 25402, 17], [25402, 26440, 18], [26440, 28216, 19], [28216, 31137, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 31137, 0.09394]]}
olmocr_science_pdfs
2024-11-30
2024-11-30
936192432f114f4b5f2126d2a3527df2e31632fc
[REMOVED]
{"Source-Url": "http://panda.ispras.ru/~kuliamin/docs/AzovPrg-2008-en.pdf", "len_cl100k_base": 8418, "olmocr-version": "0.1.48", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 40356, "total-output-tokens": 11995, "length": "2e13", "weborganizer": {"__label__adult": 0.0003085136413574219, "__label__art_design": 0.00025963783264160156, "__label__crime_law": 0.0002570152282714844, "__label__education_jobs": 0.0005526542663574219, "__label__entertainment": 4.8100948333740234e-05, "__label__fashion_beauty": 0.00012993812561035156, "__label__finance_business": 0.0001227855682373047, "__label__food_dining": 0.0002551078796386719, "__label__games": 0.0005102157592773438, "__label__hardware": 0.000682830810546875, "__label__health": 0.00031566619873046875, "__label__history": 0.0001537799835205078, "__label__home_hobbies": 5.8531761169433594e-05, "__label__industrial": 0.0002484321594238281, "__label__literature": 0.0002092123031616211, "__label__politics": 0.00016450881958007812, "__label__religion": 0.00036454200744628906, "__label__science_tech": 0.008026123046875, "__label__social_life": 5.936622619628906e-05, "__label__software": 0.005283355712890625, "__label__software_dev": 0.9814453125, "__label__sports_fitness": 0.00022709369659423828, "__label__transportation": 0.0003185272216796875, "__label__travel": 0.00016069412231445312}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 51049, 0.03817]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 51049, 0.71299]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 51049, 0.88452]], "google_gemma-3-12b-it_contains_pii": [[0, 7224, false], [7224, 12842, null], [12842, 18460, null], [18460, 23493, null], [23493, 25265, null], [25265, 27812, null], [27812, 28831, null], [28831, 30441, null], [30441, 36357, null], [36357, 41997, null], [41997, 47094, null], [47094, 49895, null], [49895, 51049, null]], "google_gemma-3-12b-it_is_public_document": [[0, 7224, true], [7224, 12842, null], [12842, 18460, null], [18460, 23493, null], [23493, 25265, null], [25265, 27812, null], [27812, 28831, null], [28831, 30441, null], [30441, 36357, null], [36357, 41997, null], [41997, 47094, null], [47094, 49895, null], [49895, 51049, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 51049, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 51049, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 51049, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 51049, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 51049, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 51049, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 51049, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 51049, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 51049, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 51049, null]], "pdf_page_numbers": [[0, 7224, 1], [7224, 12842, 2], [12842, 18460, 3], [18460, 23493, 4], [23493, 25265, 5], [25265, 27812, 6], [27812, 28831, 7], [28831, 30441, 8], [30441, 36357, 9], [36357, 41997, 10], [41997, 47094, 11], [47094, 49895, 12], [49895, 51049, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 51049, 0.0]]}
olmocr_science_pdfs
2024-11-23
2024-11-23
be78318683876c4df693932a009c5925072b7e9c
ABSTRACT Although not as frequent as merging, a data manipulation task which SAS® programmers are required to perform is vertically combining SAS data sets. The SAS system provides multiple techniques for appending SAS data sets, which is otherwise known as concatenating, or stacking. There are pitfalls and adverse data quality consequences for using traditional approaches to appending data sets. There are also efficiency implications with using different methods to append SAS data files. In this paper, with practical examples, I examine the technical procedures that are necessary to follow to prepare data to be appended. I also compare different methods that are available in BASE SAS to append SAS data sets, based on efficiency criteria. INTRODUCTION A SAS programmer may encounter different task situations on a given project where the need to append data sets arises. Some task examples involve the time period corresponding to the data files the programmer is using. A programmer may be provided monthly data sets and need to create an annual data set. Rather, a programmer may work with quarterly data sets and need to produce an annual data set. Also, a programmer may need to create a 3-year or 5-year data set from single-year data sets. In these examples, the purpose of appending is due to the need to analyze data over a longer time period, such as a full year, or to look at trends across a 3 or 5 year time span. THE PROCESS OF APPENDING There are multiple ways of describing the process of vertically combining SAS datasets. Appending, concatenating, and stacking are all terms used which refer to vertically combining SAS data sets. The diagram in Figure 1 below visually illustrates the process of appending. Figure 1. Append diagram flowchart THE TRAPS OF DATA SET APPENDING SAS programmers are responsible for ensuring the validity of the data sources they use. Data quality issues arise when the data sets you need to append don’t have the same variable attributes. Data sets can have discrepancies in variable types, variable lengths, and variable formats. Another trap to lookout for is when the data sets don’t share the same set of variables. DISCREPANCY IN VARIABLE TYPES; CHARACTER VS. NUMERIC In the case of variable type mismatches, SAS won’t append the data sets. The SAS log in Figure 2 shows error messages for a DATA STEP append corresponding to variable type mismatches. ```sas 62 Data Sales; 63 Set Sales_95 64 Sales_96; ERROR: Variable Actual has been defined as both character and numeric. ERROR: Variable MonYr has been defined as both character and numeric. 65 Run; NOTE: The SAS System stopped processing this step because of errors. WARNING: The data set WORK.SALES may be incomplete. When this step was stopped there were 0 observations and 11 variables. ``` Figure 2. Variable(s) is character in one data set, numeric in the other DISCREPANCY IN VARIABLE LENGTHS When variables have different lengths, SAS will append the data sets. Though, the validity of the data may be compromised. This mainly pertains to character variables. An examination of the data might reveal truncated data values. The SAS log in figure 3 displays a warning message concerning a discrepancy in variable lengths. ```sas 62 Data NA_Sales; 63 Set US 64 Canada 65 Mexico; 66 Run; WARNING: Multiple lengths were specified for the variable State by input data set(s). This can cause truncation of data. NOTE: There were 6336 observations read from the data set WORK.US. NOTE: There were 2880 observations read from the data set WORK.CANADA. NOTE: There were 2304 observations read from the data set WORK.MEXICO. NOTE: The data set WORK.NA_SALES has 11520 observations and 11 variables. ``` Figure 3. Data sets with length mismatch DISCREPANCY IN VARIABLE FORMAT If there’s a difference in variable formats, SAS will also append the data sets. In this case, SAS will use the format from the first data set, regardless of how many data sets you’re appending. If you use PROC APPEND to concatenate, SAS will issue a warning message in the log about the format discrepancy. As the example in Figure 4 shows, SAS completes the append using the DATE7. format for sales_date, but issues a warning message describing the date format discrepancy. Proc Append Base=Annual_Sales Data=QTR4; Run; NOTE: Appending WORK.QTR4 to WORK.ANNUAL_SALES. WARNING: Variable Sales_Date has format DATE7. on the BASE data set and format MMDDYY10. on the DATA data set. DATE7. used. NOTE: There were 2880 observations read from the data set WORK.QTR4. NOTE: 2880 observations added. NOTE: The data set WORK.ANNUAL_SALES has 11520 observations and 12 variables. NOTE: PROCEDURE APPEND used (Total process time): real time 0.00 seconds cpu time 0.00 seconds Figure 4. Data set append with format discrepancy. VARIABLE IN ONE DATA SET, NOT THE OTHER It's entirely plausible that your data sets may include different sets of variables. In this case SAS will append the data, although it depends on the construct you use. However, SAS will assign missing values in the new data set for the records from the source data set which doesn't have the variable. In the example in Figure 5, 12 monthly data sets are appended using the DATA STEP. The Jan and Feb data data sets are missing both Product and Product_Type variables, respectively. In Appendix I, a sample of the Sales_Annual data set shows missing values for Product and Product_Type for Jan and Feb records. Data Sales_Annual; Set Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec; Run; NOTE: There were 960 observations read from the data set WORK.JAN. NOTE: There were 960 observations read from the data set WORK.FEB. NOTE: There were 960 observations read from the data set WORK.MAR. NOTE: There were 960 observations read from the data set WORK.APR. NOTE: There were 960 observations read from the data set WORK.MAY. NOTE: There were 960 observations read from the data set WORK.JUN. NOTE: There were 960 observations read from the data set WORK.JUL. NOTE: There were 960 observations read from the data set WORK.AUG. NOTE: There were 960 observations read from the data set WORK.AUG. NOTE: There were 960 observations read from the data set WORK.AUG. NOTE: There were 960 observations read from the data set WORK.OCT. NOTE: There were 960 observations read from the data set WORK.NOV. NOTE: The data set WORK.SALES_ANNUAL has 11520 observations and 11 variables. Figure 5. Monthly data set append using Data Step method. BEST PRACTICES BEFORE APPENDING In order to ensure consistency between the data sets you’re appending its necessary to examine the contents of those data sets, the variables they contain, and the attributes of those variables. The most straightforward way to do this is to run a PROC CONTENTS on each of the data sets. The PROC CONTENTS output contains important metadata. It includes a list of variables in the data set, including the type, length, format and informat of each variable. The code for PROC CONTENTS is in Figure 6. The SAS output for PROC CONTENTS for the Sales_95 and Sales_96 data sets is displayed in Appendix II at the end of the paper. ``` Proc Contents Data=Work.Sales_95; Proc Contents Data=Work.Sales_96; Run; ``` Figure 6. Proc Contents Using the output, a programmer can compare the data sets with respect to these attributes to see if there any differences which impact data quality and validity. Then the programmer can write code to modify the variable attributes in one or more data sets. A programmer can also use PROC DATASETS to investigate variable attributes. If you use the CONTENTS statement, PROC DATASETS generates the same output as PROC CONTENTS. PROC DATASETS code is in Figure 7. ``` Proc Datasets Library=Work Contents Data=Sales_95; Quit; Run; ``` Figure 7. Proc Datasets PROC COMPARE is another BASE SAS tool which a programmer can harness to investigate data set metadata. In my opinion, PROC COMPARE is a more effective way to do this because it performs the comparison for you. The report generated by PROC COMPARE lists variables with attribute discrepancies, in the variables summary section of the output. A caveat is the comparison produced by PROC COMPARE is limited to two data sets. This makes it especially useful in the case of combining two data sets. Figure 8 shows the code for PROC COMPARE. To suppress the values summary which can be quite lengthy, you must use the NOVALUES option. The output for PROC COMPARE is included in Appendix III at the end of the paper. ``` Proc Compare Base=Sales_95 Compare=Sales_96 Novalues; Run; ``` Figure 8. Proc Compare RESOLVING THE INCONSISTENCIES Once the data set differences have been discovered, the next logical step is to make changes to the data set variables to align them with each other. These variable modifications are easily performed using a DATA STEP to do simple data manipulations. For instance, you can increase the variable length using the LENGTH statement. The INPUT and PUT functions are handy to change variable type by explicitly converting variables from character to numeric and vice-versa. The RENAME and DROP option/statement can be harnessed to change variable names and drop extraneous variables. Figure 9 displays DATA STEP code which modifies variable attributes using these constructs. ```sas Data Sales_95; Length State $22; Set appsds.Sales_95 (Rename=(Mon=MonYR Quarter=Qtrc State=NewState Actual=Actualn) Drop=County); *Re-assign State with new length; State = NewState; *Convert Actual to numeric; Actual = Input(Actualn, dollar12.2); *Convert MonYR to character; Quarter = Put(Qtrc, 3.); Drop NewState Actualn Qtrc; Run; ``` **Figure 9. Data Step to correct attribute discrepancies** AFTER APPENDING Once the process of appending is complete, it’s important to verify variable attributes on the new data set. This only requires running a simple PROC CONTENTS on the output data set. For many appends the attributes from the first data set prevail. However, it’s useful to examine the descriptor portion of the data set to ensure that the results conform to expectations. I recommend running PROC CONTENTS on the new data set after the append executes. The code for PROC CONTENTS was displayed earlier in this paper in Figure 6. A diligent SAS programmer reviews the data values to ensure the quality and accuracy of the data set. As described, the process of the append may truncate values for variables that have length discrepancies. Also in the new data set, missing values will be assigned for records from a data set without a corresponding variable. PROC FREQ is a good data validity tool for checking character data values. With PROC FREQ, you can output frequency tables on each variable in the data set. The code for PROC FREQ is displayed in Figure 10 below. ```sas Proc Freq Data=Sales_95; Tables State Quarter / List Missing; Run; ``` **Figure 10. Proc Freq** It’s a good practice to document the values that constitute a variable before combining data sets. Thus, I also recommend running frequency tables on input data sets prior to executing the append. METHODS OF APPENDING DATA STEP SET STATEMENT I consider the DATA STEP SET statement to be the traditional approach to appending data sets. When I first started programming in SAS, I only used the DATA STEP to append data sets. This is probably because it was the first method I learned, and I hadn’t learned the other techniques. To concatenate two data sets together using the SET statement, a user simply specifies SAS data sets one after the other. Using the DATA STEP SET statement, an unlimited number of data sets can be appended together. I’ve used the DATA STEP to append up to 12 SAS data sets. A SAS code example of DATA STEP concatenation is in Figure 11. ``` Data Sales; Set Sales_95 Sales_96; Run; ``` Figure 11. Data Step Concatenation OBSTACLES TO APPENDING In using the conventional DATA STEP method, SAS will generally append data sets together which have attribute differences. In the case of variables which have discrepancies in type (character vs. numeric), SAS will not append the data sets together and will issue an explicit error message detailing the discrepancy. In the three other cases of discrepancies, SAS will append the data sets and will issue a warning message when there’s a length discrepancy. For Length and Format discrepancies, SAS will use the attributes from the first data set for the new variable on the appended data set. However, when one input data set is missing a variable, SAS will write missing values for those records from the data set. Figure 12 below details the results for each case of variable discrepancies when using the DATA STEP Set statement. <table> <thead> <tr> <th>Discrepancy</th> <th>Result</th> <th>Note</th> </tr> </thead> <tbody> <tr> <td>Variable Type</td> <td>Will not Append</td> <td>Error Message</td> </tr> <tr> <td>Variable Length</td> <td>Will Append</td> <td>Variable length in first data set carried over. Issues Warning Message</td> </tr> <tr> <td>Variable Format</td> <td>Will Append</td> <td>Variable format from first data set carried over.</td> </tr> <tr> <td>Variables</td> <td>Will Append</td> <td>Missing values for records from data set without variable</td> </tr> </tbody> </table> Figure 12. Data Step Set statement – data set discrepancies EFFICIENCY IMPLICATIONS The DATA STEP can be a time-consuming and resource intensive construct. Using the DATA STEP usually means a sequential reading of observations in the input data sets. Using the DATA STEP method, all data sets listed in the SET statement are read and processed. In DATA STEP mechanics, this means that all observations are loaded to the program data vector and written to the new output data set. Reading and writing large volumes of data results in extensive consumption of input/output (I/O) resources. Thus, using the DATA STEP has the drawback of inefficiency by consuming I/O resources. It can also entail substantial CPU or processing time. The effect on efficiency is positively correlated with the amount of data being processed. If you are appending large data sets which contain millions of records, the effect on efficiency will be proportionately large. You should expect a relative increase in time to process an append which requires substantial I/O and other resources, due to the large amount of data being processed. Figure 13 displays a concatenation example. The notes in the SAS log confirm the full set of observations from each data set were read using the DATA STEP. ``` 74 Data NDF_DSC; 75 Set NDF_1994 76 NDF_1995_AFTER; 77 Run; ``` NOTE: There were 515155 observations read from the data set WORK.NDF_1994. NOTE: There were 533420 observations read from the data set WORK.NDF_1995_AFTER. NOTE: The data set WORK.NDF_DSC has 1048575 observations and 36 variables. NOTE: DATA statement used (Total process time): real time 50.36 seconds cpu time 5.44 seconds Figure 13. Data Step Concatenation example PROC APPEND Another BASE SAS construct that can be used to append SAS data sets is the APPEND procedure. With PROC APPEND, you specify a BASE data set, and a DATA data set. PROC APPEND has the limitation of combining only two data sets. The coding of PROC APPEND is straight forward. Unlike the DATA STEP, it's not necessary to specify a new output data set. The BASE data set becomes the new data set with records appended from the DATA data set. An example of PROC APPEND is in Figure 14. ``` 106 Proc Append Base=US Data=Canada_Mexico; 107 Run; ``` NOTE: Appending WORK.CANADA_MEXICO to WORK.US. WARNING: Variable Actual has format COMMA12. on the BASE data set and format DOLLAR12. on the DATA data set. COMMA12. used. WARNING: Variable Predict has format COMMA12. on the BASE data set and format DOLLAR12. on the DATA data set. COMMA12. used. WARNING: Variable Mon was not found on BASE file. The variable will not be added to the BASE file. WARNING: Variable State has different lengths on BASE and DATA files (BASE 10 DATA 22). ERROR: No appending done because of anomalies listed above. Use FORCE option to append these files. NOTE: 0 observations added. NOTE: The data set WORK.US has 6336 observations and 10 variables. NOTE: Statements not processed because of errors noted above. Figure 14. Proc Append - SAS log By default, PROC APPEND will not combine the data sets if discrepancies exist between dataset variables, with the exception of format discrepancies. As figure 14 shows, PROC APPEND will issue explicit warning messages if discrepancies exist in variables or variable attributes. The messages state the specific discrepancy, and the variables involved on the BASE and DATA data sets respectively. THE FORCE OPTION Using the FORCE option, PROC APPEND will combine data sets if discrepancies exist in the variable type, length, or variables between the BASE and DATA data sets. SAS data sets that have a discrepancy in formats will be appended without using FORCE. When there’s a discrepancy in variable attributes between BASE and DATA data sets, the attributes from the BASE data set prevail. The table in figure 15 shows the result and details for various attribute differences. <table> <thead> <tr> <th>Trap</th> <th>Result</th> <th>Note</th> </tr> </thead> <tbody> <tr> <td>Variable Type</td> <td>Will append with FORCE option.</td> <td>Missing values for records from DATA data set.</td> </tr> <tr> <td>Variable Length</td> <td>Will append with FORCE option.</td> <td>Length from BASE data set prevails. Records from DATA data set may contain truncated values.</td> </tr> <tr> <td>Variable Format</td> <td>Will append with FORCE option.</td> <td>Format from BASE data set prevails.</td> </tr> <tr> <td>Variables</td> <td>Will Append with FORCE option.</td> <td>Missing values for records from data set without variable</td> </tr> </tbody> </table> Figure 15. Proc Append – data set discrepancies In figure 16 is an example using PROC APPEND with the FORCE option in the SAS log. The input data sets have a mismatch in type for the ACTUAL variable, but the append still completes. ``` 73 Proc Append Base=Sales_95 Data=Sales_96 Force; 74 Run; ``` **NOTE:** Appending WORK.SALES_96 to WORK.SALES_95. **WARNING:** Variable Actual not appended because of type mismatch. **NOTE:** FORCE is specified, so dropping/truncating will occur. **NOTE:** There were 5760 observations read from the data set WORK.SALES_96. **NOTE:** 5760 observations added. **NOTE:** The data set WORK.SALES_95 has 11520 observations and 11 variables. **NOTE:** PROCEDURE APPEND used (Total process time): real time 0.00 seconds cpu time 0.01 seconds Figure 16. Proc Append with FORCE option. EFFICIENCY IMPLICATIONS The main advantage of using PROC APPEND is improved processing efficiency. Unlike the DATA STEP method, using PROC APPEND only the DATA data set is read and processed. The records from the DATA data set are simply added to the end of the BASE data set. This results in improved processing efficiency over the DATA STEP method, especially if the BASE data set is large. The better processing efficiency with PROC APPEND entails savings of valuable computing resources, such as I/O. In Figure 17 is an example using PROC APPEND. The notes in the SAS log explain that the full set of observations in the DATA data set were read and added. Run; NOTE: There were 533420 observations read from the data set WORK.NDF_1995_AFTER. NOTE: 533420 observations added. NOTE: The data set WORK.NDF_1994 has 1048575 observations and 36 variables. NOTE: PROCEDURE APPEND used (Total process time): real time 27.33 seconds cpu time 2.80 seconds Figure 17. Proc Append efficiency example. PROC SQL SET OPERATORS PROC SQL has capabilities which extend to appending SAS data sets. You can vertically combine SAS data sets with PROC SQL using SET operators. There are four different SET operators in PROC SQL; INTERSECT, EXCEPT, UNION, and OUTER UNION. The set operator which appends data sets and is equivalent to the DATA STEP SET statement and PROC APPEND is OUTER UNION. Each of the four SET operators selects records to include in the result set, and combine data sets in one manner or another. The INTERSECT operator selects records which are common to both tables. The EXCEPT operator selects records in the first table that are not in the second table. The UNION operator selects records that are exclusive to each of the tables, and records that are common to the tables. The OUTER UNION operator selects all records from both tables. By default, the first three SET operators select unique records from both tables. To select both unique and duplicate records, you need to use the ALL keyword. Since OUTER UNION selects all records by default, use of the ALL keyword isn’t necessary. However, unlike the other three operators, OUTER UNION doesn’t append or overlay columns by default. To append columns according to column name, use of the CORR keyword is required. Figure 18 is a SAS log which displays an append using the PROC SQL OUTER UNION set operator. Proc Sql; Create Table NDF_PSQL as Select * From NDF_1994 Outer Union Corr Select * From NDF_1995_AFTER; NOTE: Table WORK.NDF_PSQL created, with 1048575 rows and 36 columns. Quit; NOTE: PROCEDURE SQL used (Total process time): real time 48.91 seconds cpu time 8.00 seconds Figure 18. Outer Union Set operator The PROC SQL OUTER UNION construct has the capability of appending more than two SAS data sets. In comparison PROC APPEND is limited to two tables. To perform this with PROC SQL set operators, you need to combine more than two SELECT queries. With this method each additional table combined requires a separate query. With PROC SQL OUTER UNION, more lines of code are required than a DATA STEP append because of having to repeat SELECT and OUTER UNION CORR for each extra input table. The DATA STEP also permits appending more than two input tables. The efficiency impact of PROC SQL OUTER UNION is similar to the DATA STEP SET statement. The PROC SQL example in figure 18 took 48.91 seconds of real time to execute. If we examine the results from Figure 13, SAS took 50.36 seconds of real time to execute the append using the DATA STEP SET statement. Using PROC SQL OUTER UNION shows only a minor increase in performance of about 1.5 seconds. **PROC DATASETS** Another construct in BASE SAS which can be used to append data sets is PROC DATASETS. With PROC DATASETS, you use the APPEND statement to concatenate. The construct is quite similar to PROC APPEND. The user specifies a BASE and a DATA data set. If there discrepancies in variable attributes between data sets, the BASE data set attributes prevail. PROC DATASETS also has a FORCE option which can be used to execute the append if data set differences exist in variables, variable length or formats. Figure 19 is a SAS log with a PROC DATASETS append example. ``` 73 Proc Datasets Library=Work nolist; 74 Append Base=NDF_1994 Data=NDF_1995_AFTER; 75 Run; ``` NOTE: There were 533420 observations read from the data set WORK.NDF_1995_AFTER. NOTE: 533420 observations added. NOTE: The data set WORK.NDF_1994 has 1048575 observations and 36 variables. 76 Quit; NOTE: PROCEDURE DATASETS used (Total process time): real time 22.85 seconds cpu time 2.74 seconds ``` **Figure 19. Proc Datasets Append statement** The efficiency implications of using PROC DATASETS are also the same as PROC APPEND. The example in figure 19 shows the observations from the DATA data set (NDF_1995_AFTER) were read and added to the end of the BASE data set (NDF_1994). As evidenced with PROC DATASETS, SAS only reads the DATA data set when appending data sets. If you look at the processing time in the examples, PROC DATASETS took about 5 seconds less real time (22.85) than PROC APPEND (27.33). The only real difference between PROC APPEND and the PROC DATASETS APPEND statement is the default SAS library. PROC APPEND uses WORK or USER as its default library, and with PROC DATASETS the default library is the procedure input library. The remaining aspects, including the structure of the append and the append processing, are the same. METHOD COMPARISON <table> <thead> <tr> <th>BASE SAS Method</th> <th>Real Time</th> <th>Ranking</th> <th>% Change</th> <th>CPU Time</th> <th>Ranking</th> <th>% Change</th> </tr> </thead> <tbody> <tr> <td>DATA STEP SET statement</td> <td>50.36</td> <td>4</td> <td>5.34</td> <td>3</td> <td></td> <td></td> </tr> <tr> <td>PROC APPEND</td> <td>27.33</td> <td>2</td> <td>-46%</td> <td>2.80</td> <td>2</td> <td>-48%</td> </tr> <tr> <td>PROC SQL OUTER UNION</td> <td>48.91</td> <td>3</td> <td>-3%</td> <td>8.00</td> <td>4</td> <td>50%</td> </tr> <tr> <td>PROC DATASETS</td> <td>22.85</td> <td>1</td> <td>-55%</td> <td>2.74</td> <td>1</td> <td>-49%</td> </tr> </tbody> </table> Figure 20. Append – BASE SAS Method comparison In Figure 20, the four different BASE SAS constructs for appending are compared according to efficiency criteria. Using each of the four methods, two SAS data sets containing approximately 500000 observations each were appended. The comparison tests were run in a virtual environment using 64-bit SAS University Edition and the SAS Studio interface, version 3.71 The DATA STEP method took the most actual time and performed the slowest. PROC APPEND performed well, and came in 2nd both in terms of real time, and cpu time. Using PROC APPEND resulted in a 46% decrease in cpu time and 48% decrease in real time, over the DATA STEP method. PROC SQL OUTER UNION came in last in cpu time and consumed the most cpu. PROC DATASETS performed the best both in real time and cpu time. PROC DATASETS showed a 55% decrease in cpu time and 49% decrease in real time over the DATA STEP method. CONCLUSION There are proper data validation steps for a SAS programmer to follow both before and after appending SAS data sets, regardless of the append construct you select. It’s a wise practice to examine and compare variable attributes prior to combining data sets. This can be performed using standard BASE SAS constructs PROC CONTENTS and PROC DATASETS. PROC COMPARE is a better tool to use before appending two data sets since it performs an automated comparison. After appending, I recommend using PROC FREQ to check data quality. For appending methods, the DATA STEP and PROC SQL both permit combining more than two data sets, but have efficiency limitations. PROC APPEND and PROC DATASETS have the advantage of processing efficiency and are conceptually equivalent. In my test cases, PROC DATASETS slightly outperformed PROC APPEND in processing time. REFERENCES ACKNOWLEDGEMENTS The author would like to thank Lisa Mendez, SAS Global Forum 2020 Conference Chair, Kirby Sinclair, Room Facilitator, and the SAS Global Forum 2019 Executive Committee and Conference Team for accepting my abstract and paper, and organizing a great conference. Jay Iyengar is Director of Data Systems Consultants LLC. He is a SAS Consultant, Trainer, and SAS Certified Advanced Programmer. He’s been co-leader and organizer of the Chicago SAS Users Group (WCSUG) for the last 5 years. He’s presented papers and training seminars at SAS Global Forum (SGF), Midwest SAS Users Group (MWSUG), Wisconsin Illinois SAS Users Group (WIILSU), Northeast SAS Users Group (NESUG), and Southeast SAS Users Group (SESUG) conferences. He has been using SAS since 1997. His industry experience includes International Trade, Healthcare, Database Marketing and Educational Testing. CONTACT INFORMATION Your comments and questions are valued and encouraged. Contact the author at: Jay Iyengar Data Systems Consultants LLC Oak Brook, IL 60523 Email: datasyscon@gmail.com Linkedin: https://www.linkedin.com/in/jisasprogconsult TRADEMARK CITATION SAS and all other SAS Institute Inc. product or service names are registered trademarks or trademarks of SAS Institute Inc. in the USA and other countries. ® indicates USA registration. Other brand and product names are registered trademarks or trademarks of their respective companies. <table> <thead> <tr> <th>Country</th> <th>State</th> <th>County</th> <th>Actual</th> <th>Predict</th> <th>ProductType</th> <th>Year</th> <th>Quarter</th> <th>Mon</th> <th>MonYr</th> <th>Product</th> </tr> </thead> <tbody> <tr> <td>Canada</td> <td>Saskatchewan</td> <td>$540.00</td> <td>$1,301.60</td> <td>BED</td> <td>1996</td> <td>1 Jan</td> <td>Jan-96</td> <td></td> <td></td> <td></td> </tr> <tr> <td>Canada</td> <td>Saskatchewan</td> <td>$101.60</td> <td>$547.20</td> <td>CHAIR</td> <td>1996</td> <td>1 Jan</td> <td>Jan-96</td> <td></td> <td></td> <td></td> </tr> <tr> <td>Canada</td> <td>Saskatchewan</td> <td>$1,163.20</td> <td>$588.00</td> <td>DESK</td> <td>1996</td> <td>1 Jan</td> <td>Jan-96</td> <td></td> <td></td> <td></td> </tr> <tr> <td>Canada</td> <td>Saskatchewan</td> <td>$1,070.40</td> <td>$248.00</td> <td>SOFA</td> <td>1996</td> <td>1 Jan</td> <td>Jan-96</td> <td></td> <td></td> <td></td> </tr> <tr> <td>Canada</td> <td>Saskatchewan</td> <td>$35.20</td> <td>$392.00</td> <td>BED</td> <td>1996</td> <td>1 Jan</td> <td>Jan-96</td> <td></td> <td></td> <td></td> </tr> <tr> <td>Canada</td> <td>Saskatchewan</td> <td>$931.20</td> <td>$1,158.40</td> <td>CHAIR</td> <td>1996</td> <td>1 Jan</td> <td>Jan-96</td> <td></td> <td></td> <td></td> </tr> <tr> <td>Canada</td> <td>Saskatchewan</td> <td>$816.00</td> <td>$996.80</td> <td>DESK</td> <td>1996</td> <td>1 Jan</td> <td>Jan-96</td> <td></td> <td></td> <td></td> </tr> <tr> <td>U.S.A.</td> <td>California</td> <td>$1,782.96</td> <td>$568.48</td> <td></td> <td>1995</td> <td>1 Feb</td> <td>Feb-95</td> <td>FURNITURE</td> <td></td> <td></td> </tr> <tr> <td>U.S.A.</td> <td>California</td> <td>$2,014.16</td> <td>$2,358.24</td> <td></td> <td>1995</td> <td>1 Feb</td> <td>Feb-95</td> <td>FURNITURE</td> <td></td> <td></td> </tr> <tr> <td>U.S.A.</td> <td>California</td> <td>$2,151.52</td> <td>$1,025.44</td> <td></td> <td>1995</td> <td>1 Feb</td> <td>Feb-95</td> <td>OFFICE</td> <td></td> <td></td> </tr> <tr> <td>U.S.A.</td> <td>California</td> <td>$2,584.00</td> <td>$2,132.48</td> <td></td> <td>1995</td> <td>1 Feb</td> <td>Feb-95</td> <td>OFFICE</td> <td></td> <td></td> </tr> <tr> <td>U.S.A.</td> <td>California</td> <td>$1,856.40</td> <td>$1,308.32</td> <td></td> <td>1995</td> <td>1 Feb</td> <td>Feb-95</td> <td>FURNITURE</td> <td></td> <td></td> </tr> <tr> <td>U.S.A.</td> <td>California</td> <td>$897.60</td> <td>$2,759.44</td> <td></td> <td>1995</td> <td>1 Feb</td> <td>Feb-95</td> <td>FURNITURE</td> <td></td> <td></td> </tr> </tbody> </table> ## APPENDIX II <table> <thead> <tr> <th>Data Set Name</th> <th>APPSDS.SALES_95</th> <th>Observations</th> <th>576</th> </tr> </thead> <tbody> <tr> <td>Member Type</td> <td>DATA</td> <td>Variables</td> <td>11</td> </tr> <tr> <td>Engine</td> <td>V9</td> <td>Indexes</td> <td>0</td> </tr> <tr> <td>Created</td> <td>05/18/2018 14:04:12</td> <td>Observation Length</td> <td>120</td> </tr> <tr> <td>Last Modified</td> <td>05/18/2018 14:04:12</td> <td>Deleted Observations</td> <td>0</td> </tr> <tr> <td>Protection</td> <td>Compressed</td> <td>NO</td> <td></td> </tr> <tr> <td>Data Set Type</td> <td>Sorted</td> <td>NO</td> <td></td> </tr> <tr> <td>Label</td> <td></td> <td></td> <td></td> </tr> <tr> <td>Data Representation</td> <td>SOLARIS_X86_64, LINUX_X86_64, ALPHA_TRU64, LINUX_IA64</td> <td></td> <td></td> </tr> <tr> <td>Encoding</td> <td>utf-8 Unicode (UTF-8)</td> <td></td> <td></td> </tr> </tbody> </table> ### Engine/Host Dependent Information <table> <thead> <tr> <th>Data Set Page Size</th> <th>65536</th> </tr> </thead> <tbody> <tr> <td>Number of Data Set Pages</td> <td>11</td> </tr> <tr> <td>First Data Page</td> <td>1</td> </tr> <tr> <td>Max Obs per Page</td> <td>545</td> </tr> <tr> <td>Obs in First Data Page</td> <td>518</td> </tr> <tr> <td>Number of Data Set Repairs</td> <td>0</td> </tr> <tr> <td>Filename</td> <td>/folders/myfolders/SAS Data Sets/Appending_sds/sales_95.sas7bdat</td> </tr> <tr> <td>Release Created</td> <td>9.0401M4</td> </tr> <tr> <td>Host Created</td> <td>Linux</td> </tr> <tr> <td>Inode Number</td> <td>139145</td> </tr> <tr> <td>Access Permission</td> <td>rw-rw-r--</td> </tr> <tr> <td>Owner Name</td> <td>Sasdemo</td> </tr> <tr> <td>File Size</td> <td>768KB</td> </tr> <tr> <td>File Size (bytes)</td> <td>786432</td> </tr> <tr> <td>#</td> <td>Variable</td> </tr> <tr> <td>----</td> <td>------------</td> </tr> <tr> <td>4</td> <td>Actual</td> </tr> <tr> <td>1</td> <td>Country</td> </tr> <tr> <td>3</td> <td>County</td> </tr> <tr> <td>10</td> <td>Mon</td> </tr> <tr> <td>11</td> <td>MonYr</td> </tr> <tr> <td>5</td> <td>Predict</td> </tr> <tr> <td>6</td> <td>Product</td> </tr> <tr> <td>7</td> <td>ProductType</td> </tr> <tr> <td>9</td> <td>Quarter</td> </tr> <tr> <td>2</td> <td>State</td> </tr> <tr> <td>8</td> <td>Year</td> </tr> <tr> <td>Data Set Name</td> <td>APPSDS.SALES_96</td> </tr> <tr> <td>-----------------------</td> <td>----------------</td> </tr> <tr> <td>Member Type</td> <td>DATA</td> </tr> <tr> <td>Engine</td> <td>V9</td> </tr> <tr> <td>Created</td> <td>05/21/2018 15:31:14</td> </tr> <tr> <td>Last Modified</td> <td>05/21/2018 15:31:14</td> </tr> <tr> <td>Protection</td> <td></td> </tr> <tr> <td>Data Set Type</td> <td></td> </tr> <tr> <td>Label</td> <td></td> </tr> <tr> <td>Data Representation</td> <td></td> </tr> <tr> <td>Encoding</td> <td>utf-8 Unicode (UTF-8)</td> </tr> </tbody> </table> ### Engine/Host Dependent Information <table> <thead> <tr> <th>Data Set Page Size</th> <th>65536</th> </tr> </thead> <tbody> <tr> <td>Number of Data Set Pages</td> <td>11</td> </tr> <tr> <td>First Data Page</td> <td>1</td> </tr> <tr> <td>Max Obs per Page</td> <td>545</td> </tr> <tr> <td>Obs in First Data Page</td> <td>518</td> </tr> <tr> <td>Number of Data Set Repairs</td> <td>0</td> </tr> <tr> <td>Filename</td> <td>/folders/myfolders/SAS Data Sets/Appending_sds/sales_96.sas7bdat</td> </tr> <tr> <td>Release Created</td> <td>9.0401M4</td> </tr> <tr> <td>Host Created</td> <td>Linux</td> </tr> <tr> <td>Inode Number</td> <td>139230</td> </tr> <tr> <td>Access Permission</td> <td>rw-rw-r--</td> </tr> <tr> <td>Owner Name</td> <td>Sasdemo</td> </tr> <tr> <td>File Size</td> <td>768KB</td> </tr> <tr> <td>File Size (bytes)</td> <td>786432</td> </tr> <tr> <td>#</td> <td>Variable</td> </tr> <tr> <td>----</td> <td>------------</td> </tr> <tr> <td>4</td> <td>Actual</td> </tr> <tr> <td>1</td> <td>Country</td> </tr> <tr> <td>3</td> <td>County</td> </tr> <tr> <td>10</td> <td>Mon</td> </tr> <tr> <td>11</td> <td>MonYr</td> </tr> <tr> <td>5</td> <td>Predict</td> </tr> <tr> <td>6</td> <td>Product</td> </tr> <tr> <td>7</td> <td>ProductType</td> </tr> <tr> <td>9</td> <td>Quarter</td> </tr> <tr> <td>2</td> <td>State</td> </tr> <tr> <td>8</td> <td>Year</td> </tr> </tbody> </table> APPENDIX III The COMPARE Procedure Comparison of WORK.US with WORK.CANADA (Method=EXACT) Data Set Summary <table> <thead> <tr> <th>Dataset</th> <th>Created</th> <th>Modified</th> <th>NVar</th> <th>NObs</th> </tr> </thead> </table> Variables Summary Number of Variables in Common: 10. Number of Variables in WORK.CANADA but not in WORK.US: 1 Number of Variables with Differing Attributes: 2. Listing of Common Variables with Differing Attributes <table> <thead> <tr> <th>Variable</th> <th>Dataset</th> <th>Type</th> <th>Length</th> <th>Format</th> <th>Informat</th> </tr> </thead> <tbody> <tr> <td>State</td> <td>WORK.US</td> <td>Char</td> <td>10</td> <td></td> <td></td> </tr> <tr> <td></td> <td>WORK.CANADA</td> <td>Char</td> <td>22</td> <td>$22.</td> <td>$22.</td> </tr> <tr> <td>MonYR</td> <td>WORK.US</td> <td>Num</td> <td>8</td> <td>MONYY7.</td> <td>MONYY.</td> </tr> <tr> <td></td> <td>WORK.CANADA</td> <td>Num</td> <td>8</td> <td>MONYY.</td> <td>MONYY.</td> </tr> </tbody> </table>
{"Source-Url": "https://www.sas.com/content/dam/SAS/support/en/sas-global-forum-proceedings/2020/4956-2020.pdf", "len_cl100k_base": 9638, "olmocr-version": "0.1.53", "pdf-total-pages": 18, "total-fallback-pages": 0, "total-input-tokens": 37941, "total-output-tokens": 10176, "length": "2e13", "weborganizer": {"__label__adult": 0.00033926963806152344, "__label__art_design": 0.0007123947143554688, "__label__crime_law": 0.0004870891571044922, "__label__education_jobs": 0.00513458251953125, "__label__entertainment": 0.00013196468353271484, "__label__fashion_beauty": 0.0001800060272216797, "__label__finance_business": 0.003498077392578125, "__label__food_dining": 0.0003685951232910156, "__label__games": 0.0006403923034667969, "__label__hardware": 0.0010700225830078125, "__label__health": 0.0004222393035888672, "__label__history": 0.000396728515625, "__label__home_hobbies": 0.0002162456512451172, "__label__industrial": 0.0010166168212890625, "__label__literature": 0.0003273487091064453, "__label__politics": 0.00031256675720214844, "__label__religion": 0.00035452842712402344, "__label__science_tech": 0.0789794921875, "__label__social_life": 0.00019109249114990232, "__label__software": 0.1666259765625, "__label__software_dev": 0.73779296875, "__label__sports_fitness": 0.00018477439880371096, "__label__transportation": 0.0003998279571533203, "__label__travel": 0.00024771690368652344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 35784, 0.05169]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 35784, 0.22986]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 35784, 0.83269]], "google_gemma-3-12b-it_contains_pii": [[0, 1776, false], [1776, 4313, null], [4313, 6620, null], [6620, 8750, null], [8750, 11274, null], [11274, 14164, null], [14164, 16951, null], [16951, 19739, null], [19739, 22248, null], [22248, 24821, null], [24821, 27282, null], [27282, 29089, null], [29089, 30583, null], [30583, 31975, null], [31975, 32720, null], [32720, 34070, null], [34070, 34824, null], [34824, 35784, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1776, true], [1776, 4313, null], [4313, 6620, null], [6620, 8750, null], [8750, 11274, null], [11274, 14164, null], [14164, 16951, null], [16951, 19739, null], [19739, 22248, null], [22248, 24821, null], [24821, 27282, null], [27282, 29089, null], [29089, 30583, null], [30583, 31975, null], [31975, 32720, null], [32720, 34070, null], [34070, 34824, null], [34824, 35784, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 35784, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 35784, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 35784, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 35784, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 35784, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 35784, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 35784, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 35784, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 35784, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 35784, null]], "pdf_page_numbers": [[0, 1776, 1], [1776, 4313, 2], [4313, 6620, 3], [6620, 8750, 4], [8750, 11274, 5], [11274, 14164, 6], [14164, 16951, 7], [16951, 19739, 8], [19739, 22248, 9], [22248, 24821, 10], [24821, 27282, 11], [27282, 29089, 12], [29089, 30583, 13], [30583, 31975, 14], [31975, 32720, 15], [32720, 34070, 16], [34070, 34824, 17], [34824, 35784, 18]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 35784, 0.29584]]}
olmocr_science_pdfs
2024-12-12
2024-12-12
67971c48b58635a39f04037e0d3ae94393add33c
WS-I* Compliant Web Service SOAP Message Security Performance Link to publication record in Ulster University Research Portal Published in: International Journal of Web Science Publication Status: Published (in print/issue): 01/01/2012 DOI: 10.1504/IJWS.2012.052533 Document Version Author Accepted version General rights Copyright for the publications made accessible via Ulster University's Research Portal 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 Research Portal is Ulster University's institutional repository that provides access to Ulster's research outputs. Every effort has been made to ensure that content in the Research Portal does not infringe any person's rights, or applicable UK laws. If you discover content in the Research Portal that you believe breaches copyright or violates any law, please contact pure-support@ulster.ac.uk. WS-I* compliant web service SOAP message security performance Gerard McHale and John O’Raw Department of Computing, Letterkenny Institute of Technology, Letterkenny, Ireland E-mail: gerardmchale1@gmail.com E-mail: john.oraw@lyit.ie Kevin Curran* Faculty of Computing and Engineering, University of Ulster, BT48 7JK, Derry, Northern Ireland E-mail: kj.curran@ulster.ac.uk *Corresponding author Abstract: The OASIS web services security (WSS) standard has been developed to provide encryption and digital signing for SOAP messaging to ensure the information in the message is confidential and that the sender and receiver are who they say they are. It has also introduced interoperability and performance problems. Interoperability has been improved with the introduction of the WS-I* Basic and Basic Security Profiles. New web stacks such as Apache CXF have attempted to address performance issues. The purpose of this research is to investigate the performance impacts of securing WS-I* compliant SOAP messages when using the Apache CXF web service framework. We measured the performance impact of WS-Security and WS-SecureConversation under different conditions and using various WS-I* compliant cryptographic algorithms. We found that WS-SecureConversation is the better option when sending a large number of messages but for a small number of large messages WS-Security can sometimes be the better option. Keywords: web services; WS-I* Basic; security; SOAP; WS-Security; Apache CXF. Biographical notes: Gerard McHale is a graduate in Computer Science of the Letterkenny Institute of Technology. He is currently employed in the Irish IT sector and his research interests include web service security. John O’Raw is a Senior Lecturer in Computer Science at the Letterkenny Institute of Technology. His research interests are in security and networks. Kevin Curran is a Reader in Computer Science at the University of Ulster, Northern Ireland. His research interests include indoor location navigation on network security. 1 Introduction The internet has become an invaluable tool, providing different applications for e-commerce, entertainment, information, communication, etc. Details on the actual number of active domains can vary but the number is somewhere between 124 million and 200 million (Verisign, 2010; Domain Tools, 2010). The popularity of the internet has led to an explosion in the number of malicious attacks against internet and web applications. Statistics show that the number of defacement attacks alone has increased from over 41,000 in April 2008 to over 60,000 in April 2009 up to over 95,000 in April 2010 (Almeida, 2010). Of more concern are malicious attacks on Enterprise IT infrastructures which have become a more serious threat with the growing importance of the internet to enterprise. These attacks can lead to monetary penalties and loss of customer base and goodwill. An important area of web security is to protect the information passed between web applications and web services. These messages are sent across the internet so the information within the messages is accessible to anyone with the knowledge to access it. The WS-Security OASIS standard has been developed to provide encryption and digital signing for SOAP messaging to ensure the information in the message is confidential and that the sender and receiver are who they say they are. The use of web services has become increasing prevalent within enterprise application development with a lot of the larger software companies hosting numerous web services in the cloud. Examples of this are Amazon Web Services and Google Maps API Web Services. Security is especially important when dealing with web services due to the fact that information is being sent across the internet which is inherently unsecure. New methods of securing information within messages have been developed specifically for use with web services. The large number of approaches available for implementing security has also led to interoperability issues between web services. As yet there is no definitive solution to this problem. During development a balance has to be reached between the level of security necessary to protect the information and the performance requirements. These decisions must be made as part of the requirements gathering phase of any development project. There have been tests and measurements done over the last number of years which have shown the large impact of implementing security in SOAP messaging however there have been advances in web service frameworks and improved Java APIs since these tests. For example the results measured by Liu et al. (2005) were achieved using Java 1.4.2. Apache Axis 1.3 and Java 1.5 were used by Moralis et al. (2007, 2009). There is a high performance overhead associated with the use of WS-Security in SOAP messages (Liu et al., 2005; Tang et al., 2006; Chen et al., 2007; Van Engelen and Zhang, 2008). The level of overhead depends on the security schemes chosen. Van Engelen and Zhang (2008) determined that using WS Security within SOAP messaging can be a factor of 100 slower than non-secured SOAP/XML messaging. Implementing SOAP security consists of two main tasks which can be described as cryptographic operations and XML processing (Liu et al., 2005). Cryptographic operations can be broken down into signing/verification and encryption/decryption. Signing refers to applying a digital signature to the SOAP message using XML-Signature processing (Bartel et al., 2008) to prove the authenticity of the message. Verification is the process of authenticating the sender of an already signed XML document. Encryption on the other hand, is the process of encrypting the contents of the message so that it cannot be read by anyone other than the intended recipient and is done using... XML-Encryption (Imamura et al., 2002). Decryption is then used to read the contents of the encrypted SOAP message. Previous studies by Liu et al. (2005), Tang et al. (2006) and Chen et al. (2007) have shown that XML signature and XML encryption add a significant overhead to SOAP messages, as much as a 1,500% increase in the response time in some cases. Both the CXF and Metro web service frameworks have been developed since and based on measurements by Sosnoski (2010) should provide improved performance handling. These studies demonstrated that signing was more expensive than encryption, especially when dealing with large numbers of messages, rather than fewer large messages. This is because the size of the message has no impact when signing. Each message must be signed so more signing is done when more messages are sent. They also demonstrated that both signing and encrypting a SOAP message was two to seven times slower than signing alone. There are significant performance improvements that can be achieved when using the Apache CXF framework compared with the Apache Axis Framework (Sosnoski, 2010). This study considered the affects of using the WS-I* Basic Profile and Basic Security Profile on the performance of WS-Security. The aim in this research was to test the performance impact of WS-Security when applied using the Apache CXF web service framework and Java. 2 Web service security Transport Layer Security (TLS) and its predecessor Security Socket Layer (SSL) are cryptographic protocols that provide security between web applications across the internet by using HTTP over TLS. TLS provides encryption, authentication and integrity to enable secure point-to-point message exchange between the applications. The goals of the TLS/SSL protocol, as described in RFC5246 are cryptographic security, interoperability, extensibility and relative efficiency. The cryptographic security is provided using a number of different protocols including the TLS Record Protocol, the TLS Handshaking Protocols and encryption algorithms such as RSA and Diffie-Hellman. Interoperability allows independent applications using TLS exchange security parameters without knowledge of the code in other applications. Extensibility allows new encryption methods to be incorporated easily into the framework without major re-work (Dierks and Rescorla, 2008). The final goal of TLS/SSL is to provide relative efficiency. Due to the extra computation associated with cryptography there is a performance cost when using TLS/SSL. Due to this cost the use of TSL/SSL is limited to security critical domains. As of January 2009, the number of TSL/SSL enabled websites was over one million representing only 0.5% of the total domains on the internet today, based on domain counts from Verisign (2010) and Domain Tools (2010). There is a relatively low uptake on the use of TLS/SSL, mainly due to the associated performance overhead. A high end CPU core can handle approximately 1,000 HTTPS transactions per second with 1,024-bit RSA while the same core can handle 10,000 plain HTTP transactions per second (Jang et al., 2010). The most expensive performance cost in TLS/SSL is the RSA computations (Coarfa et al., 2006). Performance improvements can be gained by using Graphics Performance Units (GPUs) to handle the RSA throughput (Jang et al., 2010) but this is still in the initial research stages. The performance overhead associated with TLS/SSL is still far lower than with WS-Security. A web service is a unit of managed code that can be invoked using HTTP. Web service frameworks have emerged as a means of publishing reusable functionality in which applications are exposed as services or business processes both within a single enterprise and across enterprise boundaries. With this approach applications can be developed by combining the business processes provided by already existing web services. This promotes the reuse of existing functionality and services when creating new services. Applications in a service oriented architecture (SOA) must declare their requirements and capabilities in an agreed, machine-readable format. Web services do this using WSDL. This allows any web service to use the capabilities of any other web service by binding the web services together. SOAP is the communication protocol used for sending messages between web applications. SOAP messages are based on XML. These specifications ensure that the web services architecture allows the integration of distributed and heterogeneous web applications that are independent of programming language, operating system and hardware. This architecture promotes loose coupling between the service provider and the consumer. One of the core functionalities of SOAP is to provide extensibility (Haas, 2003). This extensibility ensures that the SOAP protocol is easily maintainable and can avoid becoming obsolete too quickly. Interoperability is an essential part of enterprise web development. The Web Services Interoperability Organisation (WS-I) was established to promote interoperability. The goal of the WS-I is to establish best practices for web services interoperability, for selected groups of web services standards, across platforms, OSs and programming languages (WS-I, 2010). WS-I has produced a number of profiles to promote interoperability. The profile of interest during this study was the WS-I Basic Security Profile 1.1 (WS-I, 2010) which is specifically related to standardising the WS-Security protocol within SOAP messages to improve interoperability between web services. TLS and SSL provide very effective point-to-point message security. In the case of web service communication where only one hop is required TLS/SSL can be used effectively to provide confidentiality, authentication and integrity. Applying TLS/SSL as opposed to WS-Security can also significantly reduce the complexity and the performance overhead (Shirasuna et al., 2004). Web service messaging has the capability to traverse multiple applications and intermediary nodes before reaching an end point. TLS/SSL prevents message re-routing because the addressing information cannot be read within the message header at the intermediary nodes (Moralis et al., 2009). WS-Security on the other hand can provide end-to-end message level security (Web Services Security, 2006) and also allows cryptography to be applied to separate parts of the SOAP message. Therefore different combinations of body blocks, header blocks, etc. can be encrypted which allows intermediary nodes access certain parts of the message only (WSS, 2006). The full message can then be decrypted at the final destination. This provides end-to-end security which is not available when using TLS/SSL. SOAP was developed to exchange messages over a variety of underlying protocols. TLS/SSL is based specifically on the HTTP transport protocol. The capacity and application of web services would be limited if its security relied solely on this transport dependant technology. The mechanisms provided by WS-Security are applied directly to the SOAP message so the underlying protocol used has no impact on the security of the SOAP message (WSS, 2006). The release of SOAP version 1.2 further improved on the SOAP protocol. It was cleaner, faster, and more versatile and provided better web integration than its predecessor (Haas, 2003). There are 16 different algorithm suites supported by the WS-SecurityPolicy, all of which can be used for the encryption and signing of SOAP messages. The use of these is determined by the selection of a particular algorithm suite within the WSDL. However, of these 16 possible suites only four are recommended by the WS-I* Basic Security Profile (WS-I, 2010). Although the algorithm suites are not specifically mentioned in the profile the recommended algorithms and message digests are included. This information was used to determine the suites supported by WS-I*. The algorithm suites supported are Basic256, Basic128, TripleDes and TripleDesRsa15. Ichikawa et al. (2000) demonstrated that the RSA AES algorithm was faster than the DES algorithm and by extension also faster than the TRIPLEDES algorithm. It also provided enhanced security over the TRIPLEDES algorithm. Srirama et al. (2007) showed that there was only a slight difference in the transmission latency when using the encryption algorithms TRIPLEDES, AES128 and AES256, with TRIPLEDES providing the worst performance in most cases. These measurements used the asymmetric RSA 1024 algorithm to exchange the symmetric keys. These tests were done for mobile web service so this could possible explain the different findings between the two studies. 2.1 Transport layer security and secure socket layer security The WSS (2006) provides three main mechanisms for providing security within SOAP messages. These mechanisms are Security Tokens, XML Signature (Bartel et al., 2008) and XML Encryption (Imamura et al., 2002) which provide authentication, integrity, non-repudiation and encryption. These mechanisms are the building blocks used to create secure technologies. However, these mechanisms alone cannot guarantee security. The intent of the Basic Security Profile is to promote interoperability. While it does not define best security practices or guarantee security, it does use known security weaknesses to reduce choice and thus improve interoperability and security. This has the effect of improving message security if the standard is followed. In the end however, full security can only be guaranteed by implementing the required security mechanisms in the correct way. This handling is left to each particular application implementing web service security. SOAP messages can be signed and encrypted by multiple entities signing and encrypting overlapping elements. A different processing order can give very different results. For example, with signature before encryption the signer is known to have created or vouched for the plain text but there is no way to know whether the signer performed the encryption. Alternatively with encryption before signing, the signer is known to have vouched for the cipher text but it is not known by the receiver if the signer was aware of the plaintext. The Basic Security Profile defines the order for processing elements within the security headers. This ensures the receiver of the message will achieve the correct result during deciphering of the message if the order is followed. Davis (2001) described security holes and potential solutions with both of these approaches. In a production environment the recommendations by Davis should be followed. However, it was decided that this was not necessary in this case. For a single message that will be sent between a web service and a client, via a number of routers, WS-Security is the best approach for implementing security. This allows the use of numerous different security tokens including username, X.509 and Kerberos tokens for the encryption and signing of the XML SOAP messages. The OASIS standard Web Services Security: SOAP Message Security 1.1 (WSS, 2006) describes the format of SOAP messages when using WS-Security. Although possible to handle the encryption using synchronous keys it is recommended that asynchronous tokens such as X.509 or Kerberos are used. For cases where multiple messages are expected between the client and the web service, WS-SecureConversation 1.4 (2009) is the preferred approach. This is because the asynchronous approach is only used to share a synchronous key between the client and the server. After that the synchronous key is used for encryption of the message. This produces less overhead than using asynchronous keys for all the messages transmitted. 2.2 WS security and SOAP messaging performance Real world applications need to use both encryption and signing. However, there is a performance cost associated with this as shown by Liu et al. (2005) and Tang et al. (2006). If performance is an issue then possible options may be to keep the messages as small as possible or only sign and encrypt the sensitive parts of the message. XML processing is the second area that has a large impact on the performance of WS-Security. This includes parsing, validation, transformation and document tree traversal of the XML SOAP messages. Exclusive XML canonicalisation (Boyer et al., 2002) is the process of converting an XML document into a standard form. This is particularly important for XML-Signature because it removes issues caused by the flexibility of XML, which allows a document to be changed in certain ways but still be considered the same. For example, an XML document is still considered syntactically the same if additional white spaces are added. However, this would change the signature of the document so would affect the signing process in WS-Security. Van Engelen and Zhang (2008) show the performance impact associated with XML canonicalisation in some detail. The impact of XML processing and canonicalisation has not been considered for this research. The use of different security tokens can have an impact on the performance overhead of using WS-Security. Most of the studies done on this topic have based the measurements around the username and X.509 tokens. The username token is a symmetric key which provides a lower level of security than asymmetric keys such as X.509. For that reason it was not considered during this research. Tests completed by Moralis et al. (2007) compared the X.509 and Kerberos security tokens. The results showed that Kerberos can handle approximately 15–20% more messages per second than the X.509 certificate over a range of message sizes from 60 to 800 bytes. These tests also showed that Kerberos displayed up to a 28% packet throughput improvement over X.509 under full load conditions on the server. Further studies by Moralis et al. (2009) demonstrated that Kerberos consistently exhibited up to 50% message throughput improvement over X.509. However, it was shown by Van Engelen and Zhang (2008) that WS-Security message encryption and signing using HMAC symmetric keys can be an order of magnitude faster than using Kerberos, assuming the X.509 token profile is used. The disadvantage of using HMAC is that symmetric keys require a shared secret. This is not simple with SOAP messaging because unlike TLS, there is no handshake protocol in WS-Security. Van Engelen and Zhang (2008) showed how WS-SecureConversation could be used to overcome this problem. 2.3 WS-SecureConversation and SOAP messaging performance WS-SecureConversation is an OASIS specification which extends WS-Security (WS-SecureConversation 1.4, 2009). It enables the exchange of a symmetric key between a SOAP client and web service in an initial handshake message. This symmetric key can then be used to secure ongoing web service message exchanges with less processing overhead than WS-Security. It is a similar pattern to that used during a TLS handshake. The disadvantage of using WS-SecureConversation is the extra complexity and dependencies introduced into the system. Additional WS-Trust and WS-SecureConversation elements must be included in the WSDL and the SOAP messages to support the secure conversation. A decision on whether or not to use WS-SecureConversation would have to weigh the performance benefits against this additional complexity. The initial handshake between the client and the web service is handled by WS-Trust which also builds on top of WS-Security. It relies on a security token service (STS) to evaluate requests and issue a security context token (SCT). The issued SCT is then used to secure the messages during WS-SecureConversation. The most common usage of WS-SecureConversation is for the client to communicate with a single server. In this situation the STS and the web service can be co-located on the same server and therefore both have access to the one security context (SC). This was the approach taken during this research. The steps necessary for using WS-SecureConversation can be described with the aid of the diagram shown in Figure 1 (Bhargavan et al., 2007). At step 1 the client contacts the STS with a request security token (RST) message. At step 2 the STS generates a new SC, caches it, and replies to the client with a new request security token response (RSTR) message which includes an SCT. The SCT contains enough information for the client to calculate the same SC. This allows the client and server to exchange messages which are protected using the keys derived from the shared secret of the SC (step 3). Although it is possible to use the SCT for signing and encryption, it is recommended by the WS-SecureConversation 1.4 (2009) standard that “derived keys be used for signing and encrypting messages associated only with the security context”. Figure 1 Protocol using WS-Trust and WS-SecureConversation Experiments by Liu et al. (2005) have determined that the use of WS-SecureConversation is noticeably faster than using normal WS-Security. Further research by Van Engelen and Zhang (2008) on the performance impact of using WS-Security to sign and verify SOAP messages determined that the use of the symmetric HMAC algorithm was approximately seven times faster than DSA and eight times faster than RSA which are both asymmetric algorithms. The symmetric HMAC algorithm can only be used in conjunction with WS-SecureConversation because the symmetric algorithm must be agreed between the client and web service before use. This is done during the initial handshake. However, once the handshake has been completed the results show an order of magnitude performance improvement for all subsequent messages when using HMAC as opposed to the public key algorithms DSA/RSA, which must be used when only using WS-Security. 3 Performance framework Based on similar experiments in the past (Moralis et al., 2009; Tang et al., 2006; Liu et al., 2005) it was decided that the use of a simple web service and client was the best option for this research. This approach meant that other processing overheads that might distort the performance measurements could be ignored. All the testing was completed on a Pentium Dual Core 2.3GHz CPU with 4GB of RAM running a 32-bit Windows 7 Operating System. The Java version used was JDK 1.6.0_24. The Apache CXF web service framework using JAX-WS was used to handle the communication between the web service and the client. The BouncyCastle (2011) JCE provider was used to handle all the cryptographic functions. The jar file needed for this (i.e., bcprov... .jar) was included as part of the Apache CXF 2.3.3 installation. To remove the possible impact of results being affected by network latency all the tests were run with both the client and the web service hosted on the same machine. Both the web service and the client were kept small to reduce the possible impact of reduced CPU processing available for XML encryption and signing caused by the garbage collection of both the client and web service running side-by-side. To add some complexity to the web service a database was initially included as part of the web service. The MySQL database (version 5.5.8) was selected because it is a very popular and well documented open source database. The database was installed using the 32-bit .msi file. For initial development the standard configuration was selected during the installation process. The database was divided into the three tables. In each table the ID column was set as the primary key. The BOOKS table contained a list of all the books available to the application. The AUTHORS table contained all the authors used in the application and the PUBLISHERS table contained a list of all the publishers. A persistence layer was used to de-couple the persistent database of an application from the business logic. The use of a good persistence layer makes an application more maintainable. For example the database used in an application could be updated or completely changed without an impact to the business logic of the application. Hibernate is a popular and well documented open source persistence framework used primarily with Java applications. It was chosen to handle the persistence layer and the object relational mapping between the Java business logic and the relational database. For a description of installing, configuring and using Hibernate see King et al. (2011). This allows Java classes to be mapped to the different tables in a relational database. For this research version 3.3.2 of Hibernate was used. Version 3.4.0 of hibernate annotations was also used. A separate class was created to represent each of the tables within the database. These classes were `Book.java`, `Author.java` and `Publisher.java`. Annotations were used within each class to map the Java classes to the corresponding database tables. To promote loose coupling in the application, the `javax.persistence` annotations were used, rather than the Hibernate specific annotations. The benefit of this was that a different persistence framework could be incorporated into the application without having to change the Java code. The `@Entity` annotation was used to signify each class as an entity that would be mapped to the database and the `@Table` annotation was used to determine the specific table in the database. The `@Column` annotation was used to provide the name and other details of each column in the table. Note that in most cases each private field in the Java classes corresponded to a column in the corresponding database. The `@Id` annotation was used to determine the primary key for each table and the `@GeneratedValue` annotation ensured that the primary key was incremented sequentially each time a new record was added to the table. Finally, the `@ManyToOne` annotation was used to create links between the different tables. For example, this annotation was used to associate multiple books with a single author. It was also necessary to create a hibernate.cfg configuration file which was used to configure Hibernate. The database connection settings such as the location of the database and the username and password needed to access the database were set here. All the relevant classes corresponding to the database tables were mapped. The framework was also told which SQL language it should be using to access the database. ### 3.1 Web service frameworks Measuring the performance impact of using WS-Security and WS-SecureConversation was the main objective of this research therefore a number of test scenarios were developed to measure the performance impact. When developing the test scenarios a number of issues were considered. The first question was whether the client and the web service should both be run on the same machine. Liu et al. (2005) and Van Engelen and Zhang (2008) performed all the tests with both the client and the web service running on a single machine. Tang et al. (2006) and Chen et al. (2007) chose to host the client and the web service on separate machines while Moralis et al. (2007) and Shirasuna et al. (2004) had multiple clients, each located on a separate machine. These approaches provided a more realistic real world scenario and affected the measurements due to network latency. This approach also removed the potential impact of results being affected due to increased garbage collection of both applications running simultaneously on the one machine and allowed the client and server processing overhead to be evaluated separately. However, the benefit of using one machine to host the client and the web service was that it removed the issue of the performance results being affected by network latency, thus generating more consistent results. Juric et al. (2006) showed that performing the same WS-Security tests on a single machine or multiple machines can have a large impact on the results. Therefore it was decided to run the tests with both the client and the service on a single machine so that any measured differences could be related directly to the CPU processing in the client and the web service due to the selection of different web service security options. Another question was the method that should be used while running the tests. One approach by Shirasuna et al. (2004) was to send the message repeatedly for ten minutes. The average response time of the invocations and the number of invocations per second that the server processed were both measured. Liu et al. (2005), Juric et al. (2006) and Van Engelen and Zhang (2008) chose to resend each message between 100 and 100,000 times and measure the average CPU time. In all cases the first invocation was ignored from the measurements to omit one time initialisation costs. (Juric et al., 2006) also included the additional step of repeating each test 12 times, discarding the maximal and minimal times and taking the average of the remaining ten messages. It was decided that the best approach was to repeat the same message a set number of times. The response time for the first message was ignored so that the results would not be impacted by initialisation costs. The best performance was taken as the final result. The type of messages sent between the SOAP client and the web service provider was also an important consideration for this research. Different approaches to this question were used in previous performance evaluations of WS security. Van Engelen and Zhang (2008) used EchoString and EchoStringArray SOAP RPC-encoded arrays, which meant that a string or an array of strings was sent to the web service and simply echoed back to the client. Moralis et al. (2007) and Shirasuna et al. (2004) employed a similar approach by developing a web service that accepted a string and echoed the same string back to the sending client. Tang et al. (2006) used an alternative approach where the client sent a request and the web service responded by returning a specific amount of customer records. The approach taken by Tang et al. (2006) was designed to mimic more real world scenarios than that other approach which just echoed the received string back to the client. A similar approach was used in this research where an array of book objects were returned to the client based on the information contained in the request message. The size and frequency of the response message will also have an impact on the performance due to WS-Security (Sosnoski, 2010). When combining signing and encryption in the SOAP messages Sosnoski showed that the performance impact by WS-Security on a large number of small response messages was ~22 times larger than a plain message. However, the performance impact when using a smaller number of large messages was only ~13 times larger than the plain message. This was due to the overhead included in the header, which was the same regardless of the size of the message body. Due to these findings it was determined that the tests during this research would be repeated for a large number of small messages and a smaller number of large messages. The Java Cryptography Extension (JCE) (2002) provides a framework and implementations for encryption, key generation and key agreement and is necessary to provide security for SOAP messages. In a comparison done by Juric et al. (2006) between three different JCE providers it was discovered that there was very little difference between the performances of the three. The three JCE providers in question were BouncyCastle, Wedgetail JCSI and OpenSource HBCI Toolkit. As Juric et al. (2006), Liu et al. (2005), Moralis et al. (2009) all used the BouncyCastle JCE provider (BouncyCastle, 2011), it was decided that this JCE would be used for this research as well. Three of the main open source Java web service frameworks available today are Apache Axis2, Sun/Oracle Metro and Apache CXF. All of the web service frameworks support WS-Security and WS-SecureConversation as required here. However, performance tests have shown Apache CXF and Metro to be more than twice as fast as Apache Axis2 when WS-Security is used with XML-signature and XML-encryption (Sosnoski, 2010). These tests also demonstrated that Metro was slightly faster than Apache CXF. Results of similar tests using WS-SecureConversation showed that Metro provided the best performance (Sosnoski, 2010). Both Metro and Apache CXF were over 40% faster than Apache Axis2 across all the different configurations tested. Metro was approximately 12–15% faster than Apache CXF. It should be noted that these tests were carried out using Metro 2.0 and Apache CXF 2.1.7/2.1.8. The latest versions of Metro and Apache CXF are 2.0.1 and 2.3.2 respectively so these results may not be completely accurate any longer. Sosnoski determined that Apache CXF was the preferred framework for use with WS-Security (2010). This decision was based on a number of experiments where he compared the performance of the three main Java web service frameworks mentioned above. He also considered other issues such as simplicity of configuration. However, this decision was partially based on personal opinion and also considered issues such as simplicity of configuration. In the end there was very little to choose between Apache CXF and Metro. Due to the fact that the performance differences between and Apache CXF were relatively small it was decided that a decision on which framework to use would be made during implementation. During implementation it was discovered that Apache CXF was easier to configure, especially considering that Apache Tomcat was the application server that was being used. Due to this, CXF was chosen as the web service framework for the research. Version 2.0 of the WSDL standard was released in 2007. Despite the improvements that it introduced over the WSDL 1.1 standard (Christensen et al., 2001) it is still not widely used in the web services industry. As such there are no test tools available yet from the WS-I* group for validating that a WSDL 2.0 conforms to the WS-I* Basic Profile 2.0. A requirement of this research was that the WSDL and SOAP messages used would be WS-I* compliant. While it would be possible to conform to the standards by manually checking each WSDL and SOAP message it was not considered a viable approach. Therefore it was decided that WSDL 1.1 would be used through this research. It is possible to validate WSDL 1.1 using the WS-I* Basic Profile 1.1 profile tool which is bundled with the soapUI test tool. The other issue found during the implementation phase was that the existing test tools for validating WSDL 1.1 did not support the use of SOAP 1.2. This was determined through testing despite the fact that the soapUI test tool claims to support validation of SOAP 1.2. Therefore, for the validation the tool to be of any use it was necessary to use SOAP 1.1 throughout this research. This was not an ideal solution because of the advantages associated with SOAP 1.2 (Haas, 2003). ### 3.2 Design approach for the WSDL Java API for XML Web Services (JAX-WS) is a fundamental technology for developing SOAP-based web services (Metro Web Services, 2010). The JAX-WS API was designed to replace the JAX-RPC API and was introduced in JSR 224 (2007) and reflected the move in the industry away from the RPC-style towards document style web services. Therefore JAX-WS has been chosen for this research. JAX-WS uses Java annotations to provide a detailed mapping from a service defined using a WSDL to the Java classes that will implement that service. It allows for complex types defined in the WSDL to be mapped to Java classes using the Java Architecture for XML Binding (JAXB). The Service Endpoint Interface (SEI) is the java code that is exposed to the consumers of the web service. There are a number of different WSDL styles that can be used with JAX-WS web services. Butek (2005) provided a description of each of these styles and when each style might be used. Due to the requirement to be WS-I* compliant the document/literal wrapped WSDL style was chosen for this research. The recommended approach for developing a new web service is referred to as the ‘top down’ approach. This involves designing the services using WSDL first and then generating the code to implement the designed services. The benefit of this approach is that the interface is well defined before any development work begins. It also enforces the concept that the web service is implementation neutral. The top down approach was used for developing the web service and client during this research. 3.3 Implementing WS-security using Apache CXF CXF implements WS-Security by integrating Apache WSS4J. Apache WSS4J is an implementation of the OASIS WS-Security. Within CXF, WSS4J can be configured using either interceptors or WS-SecurityPolicy. However, the use of the WS-SecurityPolicy standard provided a method for configuring and controlling the security requirements of the application using industry agreed standards. Due to the requirement to follow the WS-I* standards it was decided that WS-SecurityPolicy should be used. When implementing WS-Security there are multiple approaches which can be used for authentication. Some of the approaches supported by Apache CXF are username tokens, Kerberos and X.509 certificates. The security provided by username tokens is limited so this authentication protocol was not used during the research. The token analysed during this research was X.509. The algorithm suite used by the WS-SecurityPolicy standard specified a number of different algorithm combinations that could be used in conjunction with the WSDL. The standard defines 16 supported suites, each offering different digest, encryption, key-wrap and key derivation algorithms, which are described in the WS-SecurityPolicy standard (WS-SecurityPolicy 1.3, 2009). Only some of the suites defined were valid for this research because only certain algorithms are recommended by the WS-I* Basic Security Profile. These were Basic256, Basic128 and TripleDes. Although the WS-I* Basic Security Profile does support SHA256, it recommends the use of SHA1 unless it is not suitable for some reason. Therefore it was decided not to use SHA256 in this research. The WS-I* Basic Security Profile also states that RSA-OAEP must be used for the transport of 128 and 256 bit keys. These recommendations meant that only Basic256, Basic128, TripleDes and TripleDesRsa15 were valid for this research. The X.509 standard uses a private key stored on the machine sending the message and a certificate containing a public key which is stored on the machine receiving the message. The public key is then used to decrypt and authenticate the received message. In a production application this certificate would be provided by a certification authority. However, in this research the private key and the certificate containing the public key were generated using Java keytool which manages a keystore of cryptographic keys and trusted certificates. The first step was to create the private keys for the web service and for the client using the commands shown in Figure 2. The command for the web service generated a key pair and wrapped the public key in an X.509 version 3 self-signed certificate. The certificate was stored in a single-element certificate chain. This certificate chain and the private key were then stored in the new keystore servicekeystore.jks identified by the alias myservicekey. The client’s private key and certificate chain containing the public key certificate were stored in the keystore clientkeystore.jks which was identified by the alias myclientkey. Figure 2 Keytool command to create private key store in web service and client ``` keytool -genkey -alias myservicekey -keyalg RSA -sigalg SHA1withRSA -keystore alpase -storepass alpase -keystore servicekeystore.jsks -storepass alpase -keystore clientkeystore.jsks keytool -genkey -alias myclientkey -keyalg RSA -sigalg SHA1withRSA -keystore clapske -storepass clapske -keystore servicekeystore.jsks -storepass clapske -keystore clientkeystore.jsks ``` - `alias` identified the created keystore. - `keyalg` specified the algorithm used when generating the key pair. In this case the RSA algorithm was used. - `sigalg` specified the algorithm that was used to sign the self-signed certificate. The algorithm used had to be compatible with `keyalg` so SHA1 with RSA was selected. - `keypass` denoted the password used to protect the private key. During this research a simple password was selected. In production a more secure password should be selected. - `storepass` denoted the password used to protect the keystore. Again, a more secure password should be selected for a production environment and it should be different to the `keypass` value. - `keystore` provided the location of the new keystore file that was created. - `dname` specified the X.500 distinguished name that was associated with the alias. This value was then used as the issuer and subject fields in the self-signed certificate. To set up two way trust between the SOAP client and the web service, the public key certificate of each was added to the keystore of the other. This was done using the commands listed in Figures 3 and 4. Figure 3 Add trusted certificate from client to service keystore ``` keytool -importcert -rfc -keystore clientkeystore.jsks -storepass alpase -alias myclientkey -file myclient.cert keytool -importcert -rfc -keystore servicekeystore.jsks -storepass alpase -alias myservicekey -file myservice.cert ``` Figure 4 Add trusted certificate from service to client keystore ``` keytool -importcert -rfc -keystore servicekeystore.jsks -storepass alpase -alias myservicekey -file myservice.cert keytool -importcert -rfc -keystore clientkeystore.jsks -storepass alpase -alias myclientkey -file myclient.cert ``` The attributes used for both the SOAP client and the service were `rfc` which ensured that the certificate was output in the printable encoding format defined by Internet RFC 1421 and `file` which was used to specify the name of the file where the exported certificate was stored temporarily. The keystore files containing the private key and the public certificate were then added to the `src/main/resources` folder of each project. Adding the public key certificate of both the SOAP client and the web service provider to the keystore of the other meant that messages encrypted and signed using the private key could be decrypted and authenticated in the receiving node using the appropriate public key. These certificates were self-signed, which was sufficient for this local environment. However, in a production environment it would be necessary to get the exported certificate signed by a valid Certification Authority (CA). The signed certificate would then be added to the keystore of the receiving node. This would ensure that the receiver could trust that the public key was valid and authentic. When sending or receiving a SOAP message it was necessary to access the private key contained in the keystore for decryption and signing. It was not possible to access the private key from the keystore without providing a password. The same rules apply for both the web service and the SOAP client. This was done by creating a class in both the SOAP client and the web service which implemented the CallBackHandler interface. The handle method was called when a request was made to retrieve the password for the private key stored in the keystore (i.e., when signing or decrypting a message). A check was made in the WebServiceCallBackHandler object to determine whether the request was for signing or decryption and if so the keystore password was then stored in the object so that it could be used to access the private key. A similar class was created in the SOAP client. Note that in this class the username and password for the private key were stored in a HashMap object that was created when the class was initially instantiated. In a production application this approach should not be used but it was considered sufficient for this research where it was the performance impact that was important. A number of other details such as correct error handling were also omitted for simplicity. 4 Performance results We present here the results of the WS-Security and WS-SecureConversation performance evaluation. All the testing was completed on a Pentium Dual Core 2.3GHz CPU with 4GB of RAM running a 32-bit Windows 7 Operating System. The Java version used was JDK 1.6.0_24. The Apache CXF web service framework using JAX-WS was used to handle the communication. The BouncyCastle (2011) JCE provider was used to handle all the cryptographic functions. The jar file needed for this (i.e., bcprov... .jar) was included as part of the Apache CXF 2.3.3 installation. To remove the possible impact of results being affected by network latency all the tests were run with both the client and the web service hosted on the same machine. Both the web service and the client were kept small to reduce the possible impact of reduced CPU processing available for XML encryption and signing caused by the garbage collection of both the client and web service running side-by-side. All tests were run using signing and encryption because in a real world scenario it is unlikely that one would be used without the other. The different technologies actually used in this research were Apache Ant version 1.8.2, Apache CXF version 2.3.3, Apache Tomcat version 6.0.29, BouncyCastle JCE provider version 1.45, Eclipse Helios Java EE version 1.3.1, Eclipse WTP plugin version 3.3.2, Hibernate version 3.3, Hibernate Annotations version 3.4, Java JDK version 1.6.0_24, MySQL version 5.1.15, Java Architecture for XML Binding (JAXB) version 2.2.1, Java API for XML Web Services (JAX-WS) version 2.2, SOAP, Spring version 3.0.5, WS-SecureConversation, WS-Security, WS-SecurityPolicy and WS-Trust. 4.1 Analysis of WS-Security for different message sizes The first test was designed to determine the performance impact of using WS-Security with different message sizes. WSS Encryption and WSS Signature were both included in the SOAP messages because of the necessity of using both in real world applications. All the WSS messages were encrypted and signed using the Basic256 algorithm suite. The different message sizes were achieved by returning a different number of books in the response message (i.e., number of books = 1, 2,500, 5,000, 7,500, 10,000, 12,500, 15,000, 17,500, 20,000, 22,500, 25,000). Each message size sequence was run multiple times with only the best time for each sequence kept. For each message sequence the response time for the plain SOAP message and the WSS SOAP message were recorded. The results can be seen in Figure 5. The performance impact of using WSS was calculated using the formula: \[ \text{Performance impact} = \frac{\text{SOAP}_{\text{wss}}}{\text{SOAP}_{\text{plain}}} \times 100 \] **Figure 5** WSS SOAP messages compared with plain SOAP messages The performance impact results based on this calculation are displayed in Figure 6. It was expected that the latency for the SOAP messages would be directly related to the message size and that the latency would increase in a linear fashion as the message size increased. The results from this test agreed with the expected results in almost all cases. The percentage performance impact associated with signing and encrypting a SOAP message containing only one book however was very large compared with the other results. This anomaly can be accounted for by the latency of a single plain SOAP message which came out at approximately 1ms. This low number was understandable considering the small amount of data sent between the client and web service. However, it resulted in a very low divisor in the formula which affected the result. **Figure 6** Percentage increase in latency when using WS-Security As expected there was a large performance drop when using WS-Security. Ignoring the anomaly with the measurement for one message the performance drop increased slowly as the size of the message increased. The performance impact ranged from a factor of 10 (i.e., 1,000%) to a factor of 15 (i.e., 1,500%) as the message size increased. This can be explained by the additional XML processing, XML canonicalisation and the increased computationally intensive work of generating digests and encrypting data that must be handled as the message size increases. 4.2 Analysis of algorithms supported by WS-I* Basic Security Profile There are 16 algorithm suites supported by the WS-SecurityPolicy standard (WS-I, 2010). To encourage interoperability the WS-I* Basic Security Profile recommends the use of only four of these suites. The purpose of these test cases was to measure the performance impact of these algorithm suites on WS-Security. The recommended algorithm suites are Basic256, Basic128, TripleDes and TripleDesRsa15. The first test was designed to measure the impact of the different algorithm suites on the performance impact caused by WS-Security. In this test each algorithm suite was used to sign and encrypt a range of different sized messages. The size of each message was determined by the number of books included in the response from the web service (i.e., number of books = 10, 5,000, 10,000, 15,000, 20,000). WS-Security was used to secure the SOAP messages. For each combination of message size and suite a number of requests were sent. Only the best result was recorded in each. The results of these measurements can be seen in Figures 7 and 8. These results show that there is a difference when using the different algorithm suites. As expected, based on the study by Ichikawa et al. (2000) the Basic128 and Basic256 suites provided better performance than the TripleDes and TripleDesRsa15 suites. The basic suites had a performance cost of that was a factor between 11 and 15 of a plain SOAP message. The TripleDes algorithms on the other hand ranged between 14 and 19. This is a major difference, especially considering the improved security provided by AES (used in the Basic suites) over TRIPLEDES. The results of the comparison between the Basic256 and Basic128 however were unexpected. The initial expectation was that Basic128 would have less impact on performance than Basic256. The results show that this is not the case with the impact of Basic256 actually less in some cases. This can be explained by considering the algorithms included in the basic suites. The main difference between Basic128 and Basic256 is the use of AES128 and AES256 respectively, both of which are symmetric algorithms. However, both algorithm suites use the same asymmetric algorithm (RSA) which was the algorithm used in WS-Security to wrap the symmetric algorithms as they passed between web service and client. This explained the similar results. The lower impact for Basic256 when sending 1,000 books was unknown. It should be noted that in Figure 8 the results for ten books were not included due to the skewed results caused by a latency of 1 ms (which gave an invalid result when used as the divisor). **Figure 9** Latency due to each suite over a range of request sets The second test in this section was designed to measure the performance impact of the different algorithm suites when using WS-SecureConversation to secure the SOAP message. In this case the message size was kept constant at 100 books. A small message size was chosen because WS-SecureConversation performs better with small messages. The different algorithm suites were tested against request sequences containing different numbers of requests (i.e., 10, 250, 500, 750 and 1,000). The total time was measured in this case, as opposed a single request/response in the previous test. Each sequence was run a number of times and the best result was recorded. The results of this test are shown in Figures 9 and 10. The results were as expected in this test case with the Basic suites providing better performance than the TripleDes suites. When comparing Basic128 and Basic256, the response time was 20% longer with Basic256 than with Basic128. This was due to the use of WS-SecureConversation in the second test case which uses symmetric encryption after the initial handshake. This meant that the lower processing needed for AES128 over AES256 was visible in this test. However, the difference between Basic128 and Basic256 was lower than expected. Figure 10 Factor increase of each suite over a plain SOAP message 4.3 Analysis of WS-Security versus WS-SecureConversation This test was designed to compare the performance impact of WS-SecureConversation against WS-Security. Encryption and signing were both included in the SOAP messages for both. All the messages were encrypted and signed using the Basic256 algorithm suite. A number of different request sequences were used and ranged from a large number of small messages to a small number of larger messages. These were: - 1,000 requests sent and 5 books in each response - 750 requests sent and 100 books in each response - 500 requests sent and 200 books in each response - 50 requests sent and 3,000 books in each response - 10 requests sent and 15,000 books in each response. Each sequence was run multiple times with only the best time for each kept in the results. The chosen sequences tested different performance characteristics of web service stacks. The first determined how quickly web service stacks process messages with small amounts of data. The last sequence measured the performance when processing large amount of data. The security configurations tested were – No security; WS-Security (signing and encryption using the Basic256 algorithm suite) and WS-SecureConversation (signing and encryption using the Basic256 algorithm suite). The expectation was that WS-SecureConversation would reduce the performance overhead associated with sending a number of secured messages and therefore reduce the latency for those messages. It was also expected that the improvement would be greater in the case where a large number of small messages was sent. The results in Figure 11 confirm the expected results. For the case of 1,000 small messages the performance due to WS-SecureConversation was almost three times better than with WS-Security. However, as the number of requests decreased the performance improvement also decreased. This was also expected because of how WS-SecureConversation works. Before any messaging can take place between the client and the web service there must be a handshake where the symmetric key is shared. Although the use of the symmetric key is faster for signing and encryption the initial handshake adds additional time that is not needed when using WS-Security. When only a small number of requests were sent the benefit of using the symmetric keys was counteracted by the additional time needed for the handshake. This was shown in the final sequence where only ten messages were sent and there was almost no performance gain from WS-SecureConversation. Figure 11 WS-Security vs. WS-SecureConversation A second test of WS-SecureConversation was designed to measure the impact of the message size on the performance. In this test the size of the response message was changed but the number of requests remained constant. 500 requests were sent to the web service and the responses returned from the web service contained 50, 200, 400 or 600 books. Each sequence of requests was run with no security, WS-Security and WS-SecureConversation on the SOAP message. The results are shown in Figures 12 and 13. Figure 12 Impact of message size on WS-SecureConversation ![Figure 11](image1.png) ![Figure 12](image2.png) These results show a direct correlation between the size of the message and the performance gain achieved with WS-SecureConversation over WS-Security. This is irrespective of the number of messages sent. As the size of the response messages increased, the performance gain fell from a factor of 2 down to 1.2. This result can be explained by the processes used for the encryption and signing of XML messages. During the encryption stage it is encrypted using the chosen algorithm. Therefore the symmetric key used with WS-SecureConversation will perform better than the asymmetric key used with WS-security. However, signing an XML message involves a number of steps. The first is to convert the XML message into a canonical form. Once done the XML is digested to generate the hash value. This hash value is the value included in the actual signature. Generating the signature is the only step where either a symmetric or asymmetric key is used. As the message size increases the processing needed to canonicalise the XML message also increases but the time taken for generating the signature remains relatively constant. Therefore the increased canonicalisation limits the performance gain provided by the symmetric key during encryption and generation of the signature. 4.4 Impact of WS-Security when accessing a database in the web service The inclusion of a database in the web service had a large impact on the WS-Security performance measurements due to the time spent accessing the database. This meant that any results measured when accessing a database did not give a true measure of the impact caused by the use of WS-Security to secure the SOAP messages. However, most enterprise applications use a database. Therefore, a simple test was prepared to determine the effects on WS-Security and WS-SecureConversation performance compared with no security when database processing was included. The MySQL 5.5 database was used in the web service and the persistence layer was implemented using Hibernate 3.3. Annotations were used to link the java objects to the database tables. X.509 certificates and the Basic256 algorithm suite were used for the encryption. The first test was designed to measure the impact of a database on the performance comparison between a SOAP message with no security and one that was signed and encrypted using WS-Security. A range of message sizes were chosen from very small to large (i.e., 1, WS-I* compliant web service SOAP message security performance The same number of books was returned for the results retrieved from the DB and those generated in memory. For each sequence the best response time was selected and recorded (in ms). The results of these measurements are shown in Table 1. A comparison of the performance impact between plain and WSS messages (for both the database and non-database web service) can be seen in Figure 14. The vertical axis displays the factor increase due to WS-Security. Table 1 Impact of DB on performance results <table> <thead> <tr> <th></th> <th>1 book</th> <th>2493 books</th> <th>5034 books</th> <th>20000 books</th> </tr> </thead> <tbody> <tr> <td>Database (plain)</td> <td>109</td> <td>124</td> <td>296</td> <td>1,109</td> </tr> <tr> <td>Database (WS-Security)</td> <td>93</td> <td>985</td> <td>1,593</td> <td>8,832</td> </tr> <tr> <td>No database (plain)</td> <td>1</td> <td>47</td> <td>109</td> <td>390</td> </tr> <tr> <td>No database (WS-Security)</td> <td>62</td> <td>735</td> <td>1,203</td> <td>6,523</td> </tr> </tbody> </table> Figure 14 Performance impact due to WSS for database and non-database web service (see online version for colours) As expected the results from this test show that the performance impact of using WS-Security to sign and encrypt SOAP messages was less when the additional database processing was included in the web service. This was due to the additional processing time of accessing the DB being included in the latency measurement irrespective of WSS. This had a larger impact on overall latency when no security was used but a smaller impact when WS-Security was used. Therefore, the overall performance impact was reduced. As can be seen from Figure 14 the performance impact was reduced from a factor of between 11 and 15 to a factor between 3 and 8. This was a substantial reduction in the impact of using WS-Security and would make its use far more favourable for enterprise applications. Note that the impact associated with a response message containing one book was ignored for the non-database case because the factor cannot be calculated accurately when the divisor is a value of 1. It should also be noted that these results would be valid regardless of the reason for the increased processing time in the web service. Any additional web service processing that increased the latency of a response from the web service would result in similar results. Therefore, the measurements for WSS impact represent more closely the actual performance impact of WSS. All the other WSS tests during this research have very little processing as part of the web service which explains the large difference in measured results in this case. 5 Conclusions As expected the results proved that there is a large performance impact when using WS-Security. The measurements taken during this research demonstrated that the performance impact of using WS-Security for a simple web service was between 1,000 and 1,500%. This was higher than expected compared with other studies but could possibly be explained by the low processing required in the web service. As can be seen from the fourth set of tests the inclusion of the database processing in the web service resulted in an impact of between 300 and 800%. The use of the Basic256 suite may also have increased the impact but as can be seen from the results of test two this would possibly have been negligible. These results show that when dealing with a large volume of messages between a web service and a single client WS-SecureConversation provides greater performance than WS-Security. In the case of 1,000 small messages the impact of using WS-Security was a factor of 13. However, the impact of using WS-SecureConversation was only a factor of 4.5. Moreover, the performance gain over WS-Security will improve further as the number of messages increases. However, for a small number of messages the performance impact of WS-SecureConversation can be greater than that of WS-Security due to the additional cost associated with the initial handshake. The other interesting feature is the fact that the performance gain is more pronounced when signing and encrypting small messages. Therefore large performance improvements from WS-SecureConversation over WS-Security can only be achieved when messages are kept small and there are large numbers of messages expected. When a database was queried as part of the web service the performance impact associated with WS-Security was reduced from a factor of between 11 and 15 to a factor of between 3 and 8. The reason for this was the latency impact of accessing the database, which remained relatively constant regardless of whether WS-Security was used. This reduced the factor difference between plain and WSS messages. An enterprise level web service would also have significantly increased processing requirements compared with the web service in this research. Therefore, although the use of WS-Security in an enterprise application would have an impact on performance, the effect would be less pronounced than the suggested by the results attained during this research. As was shown in test two, the cost of using the Basic256 algorithm suite compared to the Basic128 suite is negligible when using WS-Security. Therefore, due to the increased security provided by the Basic256 suite there would seem to be no reason to use the Basic128 suite at all. This is not the case when using WS-SecureConversation where the trade off from the improved security is an increased performance overhead. In all cases the better performance and security provided by the basic suites would suggest that the TripleDes suites should not be used, unless there is an underlying reason which means they must be used. References
{"Source-Url": "https://pure.ulster.ac.uk/ws/files/11427313/IJWS2012.pdf", "len_cl100k_base": 13757, "olmocr-version": "0.1.50", "pdf-total-pages": 25, "total-fallback-pages": 0, "total-input-tokens": 55086, "total-output-tokens": 17856, "length": "2e13", "weborganizer": {"__label__adult": 0.00043082237243652344, "__label__art_design": 0.000492095947265625, "__label__crime_law": 0.0008759498596191406, "__label__education_jobs": 0.001914024353027344, "__label__entertainment": 0.00015079975128173828, "__label__fashion_beauty": 0.0002137422561645508, "__label__finance_business": 0.0008254051208496094, "__label__food_dining": 0.0003275871276855469, "__label__games": 0.0006356239318847656, "__label__hardware": 0.0014810562133789062, "__label__health": 0.0007271766662597656, "__label__history": 0.000423431396484375, "__label__home_hobbies": 0.0001074671745300293, "__label__industrial": 0.0004799365997314453, "__label__literature": 0.0004954338073730469, "__label__politics": 0.0003845691680908203, "__label__religion": 0.0004546642303466797, "__label__science_tech": 0.231201171875, "__label__social_life": 0.0001970529556274414, "__label__software": 0.03363037109375, "__label__software_dev": 0.7236328125, "__label__sports_fitness": 0.0002448558807373047, "__label__transportation": 0.0006361007690429688, "__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, 74000, 0.04201]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 74000, 0.43527]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 74000, 0.93105]], "google_gemma-3-12b-it_contains_pii": [[0, 1236, false], [1236, 3478, null], [3478, 7288, null], [7288, 10779, null], [10779, 14669, null], [14669, 18351, null], [18351, 21807, null], [21807, 24192, null], [24192, 27915, null], [27915, 31649, null], [31649, 35594, null], [35594, 39301, null], [39301, 42935, null], [42935, 46224, null], [46224, 49643, null], [49643, 51246, null], [51246, 52783, null], [52783, 55612, null], [55612, 57572, null], [57572, 59059, null], [59059, 61492, null], [61492, 64156, null], [64156, 67553, null], [67553, 71269, null], [71269, 74000, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1236, true], [1236, 3478, null], [3478, 7288, null], [7288, 10779, null], [10779, 14669, null], [14669, 18351, null], [18351, 21807, null], [21807, 24192, null], [24192, 27915, null], [27915, 31649, null], [31649, 35594, null], [35594, 39301, null], [39301, 42935, null], [42935, 46224, null], [46224, 49643, null], [49643, 51246, null], [51246, 52783, null], [52783, 55612, null], [55612, 57572, null], [57572, 59059, null], [59059, 61492, null], [61492, 64156, null], [64156, 67553, null], [67553, 71269, null], [71269, 74000, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 74000, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 74000, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 74000, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 74000, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 74000, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 74000, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 74000, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 74000, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 74000, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 74000, null]], "pdf_page_numbers": [[0, 1236, 1], [1236, 3478, 2], [3478, 7288, 3], [7288, 10779, 4], [10779, 14669, 5], [14669, 18351, 6], [18351, 21807, 7], [21807, 24192, 8], [24192, 27915, 9], [27915, 31649, 10], [31649, 35594, 11], [35594, 39301, 12], [39301, 42935, 13], [42935, 46224, 14], [46224, 49643, 15], [49643, 51246, 16], [51246, 52783, 17], [52783, 55612, 18], [55612, 57572, 19], [57572, 59059, 20], [59059, 61492, 21], [61492, 64156, 22], [64156, 67553, 23], [67553, 71269, 24], [71269, 74000, 25]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 74000, 0.03015]]}
olmocr_science_pdfs
2024-12-02
2024-12-02
1a284dd23b9e377d8283d1abb2a384f2f341fe7c
An abstract domain combinator for separately conjoining memory abstractions * Antoine Toubhans¹, Bor-Yuh Evan Chang², and Xavier Rival¹ ¹ INRIA, ENS, CNRS, Paris, France ² University of Colorado, Boulder, Colorado, USA Abstract. The breadth and depth of heap properties that can be inferred by the union of today’s shape analyses is quite astounding. Yet, achieving scalability while supporting a wide range of complex data structures in a generic way remains a long-standing challenge. In this paper, we propose a way to side-step this issue by defining a generic abstract domain combinator for combining memory abstractions on disjoint regions. In essence, our abstract domain construction is to the separating conjunction in separation logic as the reduced product construction is to classical, non-separating conjunction. This approach eases the design of the analysis as memory abstract domains can be re-used by applying our separating conjunction domain combinator. And more importantly, this combinator enables an analysis designer to easily create a combined domain that applies computationally-expensive abstract domains only where it is required. 1 Introduction While there exist static analyses for the most common data structures such as lists, trees, or even overlaid lists and trees [10,4,14,11], it is uncommon for static analyses to efficiently support all of these simultaneously. For instance, consider the code fragment of Fig. 1 that simultaneously manipulates linked lists and trees, iteratively picking some value from the list and searching for it in the tree. Although verification of the memory safety and data structures preservation is possible with several tools (e.g. [18,20]), this will not take into account most efficient data-structure-specific algorithms (e.g. analysis for linked lists presented in [15] achieves polynomial complexity transfer functions). On the other hand, using only a linked-list-specific efficient analysis will lead to a dramatic loss of precision, as tree features are not supported. The general problem is much broader than just lists and trees: in real-world programs, it is common to find not only lists, trees, and overlaid lists and trees, but also buffers, arrays, and other complex heap structures, and therefore static analysis is either imprecise or inefficient. Instead of using one monolithic analysis, we propose to combine off-the-shelf data-structure-specific analyses that reason about disjoint regions of memory. The approach presented in this paper is in the context of abstract interpretation [6]. Therefore, combining analyses is realized by a separating combination of memory abstract domains called * The research leading to these results has received funding from the European Research Council under the FP7 grant agreement 278673, Project MemCAD and the United States National Science Foundation under grant CCF-1055066. the sub-domains. Combined memory abstract domains describe each disjoint memory region using one of its sub-domains. We show how separation (i.e. the fact that data structures do not share cell blocks) can be used to decompose a heterogeneous memory into several sub-instances that can be handled independently. This construction increases and eases the abstract domain design capabilities. Combined abstract domains are more extensible and flexible, as a sub-domain can be individually added, removed, strengthened, or weakened in the combination. Moreover, it allows paying the cost of complex algorithms that usually come with expressive abstract domains only in the memory region that really requires it. On the other hand, simpler light-weight abstract domains can be used to represent a significant part of the memory that does not contain complex structures. Such a combination poses several challenges. Because, even if disjoint in memory, concrete data structures can still be correlated (e.g. have shared values or pointers to each other), we need to carefully abstract the interface between memory regions in the combination. Maintaining a right partitioning (i.e. which memory region should be abstracted in which sub-domain) during the analysis process is also challenging. For example, when analyzing a memory allocation, the analysis decides which sub-domains should handle it. Even though any choice is sound, there are sub-domains more relevant than others in many cases. This approach has been successfully applied to numerical domains and made it possible to obtain scalable and precise analyses [3] and reusable abstract domains [13]. Our proposal brings, in a way, the same improvement to memory abstract domains. We justify this statement by the following contributions: – we introduce (Section 2) and formalize (Section 3.2) the separating combination functor that takes two memory abstract sub-domains matching the signature given in Section 3.1 and returns a new combined memory abstract domain; – we define an abstract domain for the interface between memory regions (Section 3.2) that carefully describes correlations between memory regions; – we set up the abstract transfer functions (Section 4) that compose abstract transfer functions of sub-domains and extract information from an abstract interface; – we give a heuristic for the decision of which sub-domain should handle a newly allocated block (Section 4.1); – we evaluate the separating combination functor by an implementation in the MemCAD analyzer (Section 5) and empirically verify that combined analyses remain efficient and precise while offering greater flexibility. 2 Overview In this section, we provide an informal description of our combined analysis (formal details are presented in Sections 3 and 4). We present an abstract interpretation [6] An abstraction of the memory using several memory abstract domains. The program manipulates a memory that can be decomposed in three disjoint regions (i) the list region (denoted $\bullet$), containing linked-list nodes (ii) the tree region (denoted $\circ$) containing tree nodes (iii) the region accounting for the rest of the memory that contains only bounded data structures (denoted $\mathcal{B}$). This naturally leads to the choice of a separating combination of three memory abstract sub-domains $M^*_L$, $M^*_T$, $M^*_B$ that will reason respectively about region $\bullet$, $\circ$ and $\mathcal{B}$. Fig. 2(a) shows the combined abstract memory computed by the analysis before line 11. Each thick black bordered boxes (labeled $\bullet$, $\circ$ and $\mathcal{B}$) contains an element $m^*_i \in M^*_L$, $m^*_j \in M^*_T$ and $m^*_k \in M^*_B$ called abstract sub-memories. Greek letters that appear in the sub-memories are called the symbolic names and are used by sub-domains to internally represent concrete values and heap addresses. The combined abstract memory represents a set of memories where variable $h$ (resp. $t$) points to the head (resp. the last element) of a linked list, variable $x$. points to the root of a tree, variable $z$ is the null pointer and content of variable $r$ can be any concrete value. Describing the interface between memory regions is crucial for precision. In particular, the combined abstract memory should account for (i) pointers from region $\bullet$ to regions $\circ$ and $\mathcal{B}$ and (ii) sharing of values between cells of different memory regions such as value $v$ in the last list node and the left tree node from the tree root. The interface abstract domain $I^\beta$ (Section 3.2) achieves this by maintaining a set of equalities between symbolic names of different abstract sub-memories. An equality between two symbolic names simply means that they represent the same concrete value. For instance, pointer $h$ crossing the memory regions $\bullet$ and $\circ$ is represented by (i) $\beta_0^\lambda$ representing the content of cell $h$ in the $m^*_L$, (ii) $\lambda_0^\beta$ representing the address of the head of the list in the $m^*_L$, and (iii) equality $\beta_0 = \lambda_0$ in the abstract interface. Thus, this combined abstract memory is a quadruple made of three abstract sub-memories $m^*_L \in M^*_L$, $m^*_T \in M^*_T$ and $m^*_B \in M^*_B$ and an abstract interface $i^\beta \in I^\beta$. In the two combined abstract memories shown in Fig. 2, abstract sub-memories are represented in gray inside the thick black boxes whereas dark blue edges and values depict the abstract interface. --- Fig. 2. Two combined abstract memories inferred during the analysis Combined analysis. The analysis automatically derives the post-condition shown in Fig. 2(b) from the pre-condition shown in Fig. 2(a) by composing abstract transfer functions for program statements between line 11 and 24. In the following, we demonstrate the key features of the combination of memory abstract domains by analyzing the two program statements at line 11 and 12. In particular, the assignment at line 11 involves a memory allocation but remains quite simple compared to the assignment at line 12 that requires post-condition computations to be distributed across sub-memories using the abstract interface. The first step when analyzing an assignment consists in evaluating its left and right-hand-sides, that is, finding symbolic names representing the address of the updated cell and the written value (Section 4.2). The right-hand side of the assignment at line 11 contains a memory allocation instruction, hence the analysis should decide which sub-domain is the most relevant for handling it. Indeed, even though any choice is sound for the analysis, a bad decision could lead to a loss in precision or in efficiency. While the three sub-domains could precisely handle the memory allocation, $M^{\#b}$ is expected to be more efficient for handling bounded data structures. Because of the type passed to `malloc`, the new cell will likely never be summarized as part of a list or a tree, $m^{\#b}$ should therefore handle the memory allocation. While not complete (C types cannot fully describe the programmer intended data structure), we find that this simple heuristic works well in practice. In Fig. 2(b), this sub-memory contains a new cell at abstract address $\beta_3$ (red background highlights created cells). The right-hand side is evaluated to $\beta_3$ and evaluation of the left-hand side is trivial and provides a symbolic name that is in $m^{\#b}$ so that both are evaluated in the same sub-memory. Therefore and thanks to the local reasoning principle, the post-condition can be computed only for abstract sub-memory $m^{\#b}$, using the sound abstract transfer function provided by $M^{\#b}$. In Fig. 2(b), the cell that correspond to $x$ has been updated to $\beta_3$ (green background highlights updated cells). Computing an abstract post-condition of the assignment at line 12 poses two main issues. First, the evaluation of its right-hand side crosses abstract sub-memories that involves a mechanism for extracting information from $i^\sharp$. Secondly, the left and right hand sides are not evaluated in the same sub-memories. Thus, accurately handling this assignment requires sound abstract transfer functions for $I^\sharp$. The right-hand side is evaluated iteratively over its syntax: (i) the content of cell $e$ is evaluated to $\beta_1$ in $m^{\#b}$ (ii) $\beta_1$ cannot be resolved as an address of a cell in $m^{\#b}$ (iii) equality $\beta_1 = \lambda_2$ can be extracted from the abstract interface $i^\sharp$, that allows the resolution to continue in $m^{\#l}$ (iv) the content of abstract address $\lambda_2$ at field `data` is $v$ in $m^{\#l}$. As $*x$ is evaluated to $\beta_3$ in $m^{\#b}$, the left and right-hand sides are evaluated respectively in $m^{\#b}$ and $m^{\#l}$. Thus, the post-condition will be computed (i) in $m^{\#b}$ as the written cell is abstracted in this abstract sub-memory (ii) in $i^\sharp$ as the written value is not represented in $m^{\#b}$. The cell whose abstract address is $\beta_3$ is updated to a fresh symbolic name in $m^{\#b}$, that is then set to be equal to $v$ in $i^\sharp$ using the abstract transfer function for $I^\sharp$. 3 The separating combination of memory abstract domains In this section, we first set up a general notion of a memory abstract domain (Section 3.1), before introducing the separating combination (Section 3.2). A memory abstract domain $M$ provides a representation for sets of concrete memories. Intuitively, it consists of a set of predicates describing memory quantified on symbolic names (denoted $N_M$) that represent concrete values (denoted $V$). Thus, concretization involves valuations mapping symbolic names to the value they represent. Once this general notion is formalized, we formally introduce the separating combination as a binary functor that takes as input two memory abstract domains $M_1$, $M_2$ and returns a new memory abstract domain $M_1 \triangledown M_2$. The functor can be iteratively applied in order to cope with more than two memory abstract sub-domains. The combined abstract domain describes disjoint memory regions using either predicates of $M_1$ or $M_2$. Moreover, correlations between regions are described by the interface abstract domain $I$ that maintains equalities between symbolic names quantified in different sub-memories. 3.1 Memory abstract domain Concrete memories. We let $A$ denote the set of concrete addresses, and we assume addresses to be concrete values (i.e. $A \subseteq V$). Henceforth, we adopt a standard model for concrete memories where a concrete memory $m$ is a finite map from addresses to values. Therefore, the set of concrete memories is defined by $M = A \leftarrow^{\text{fin}} V$. We let $F = \{f_0, f_1, \ldots\}$ denote the set of valid field names, and we treat them as numerical offsets so that for $a \in A$ and $f \in F$, $a + f$ denotes the address at field $f$ of the block at address $a$. As the separating combination is reasoning about disjoint memory region, we write $m_1 \cup m_2$ for the union of two disjoint memories (i.e. $\text{dom}(m_1) \cap \text{dom}(m_2) = \emptyset$, where $\text{dom}(m_i)$ denotes the domain of $m_i$ as a partial function). A memory abstract domain is a lattice of abstract memories $M$, together with a fixed infinite set of symbolic names $N_M$, a concretization function $\gamma_M$ and sound abstract transfer functions (detailed in Section 4). An abstract memory $m^s \in M$ internally utilizes symbolic names to represent concrete values. We define the set of valuations $V_M = N_M \leftarrow^{\text{fin}} V$. Intuitively, a valuation $\nu \in V_M$ relates symbolic names to concrete values when concretizing. Concretization is a function $\gamma_M : M \rightarrow P(M \times V_M)$ and $\gamma_M(m^s)$ collects a set of couples $(m, \nu) \in M \times V_M$ made of a concrete memory and a valuation that maps symbolic names quantified in $m^s$ to concrete values in $m$. Example 1 (Bounded structure abstract domain). As a first example, we describe a memory abstract domain that represents precisely block contents, but is unable to summarize unbounded regions such as list and tree data structures. This memory abstract domain can be considered an instantiation of $M_b$ seen in the overview (Section 2). The set of symbolic names consists of either symbols for addresses (denoted $\alpha_0^b, \alpha_1^b, \ldots$) or symbols for cell contents (denoted $\beta_0^b, \beta_1^b, \ldots$). Definitions of abstract memories and An abstract memory \( m^2 \) consists of a separating conjunction of atomic predicates \( \alpha^a \rightarrow \{ l : \beta^c \} \) abstracting a cell at address \( \alpha^a + l \) of content \( \beta^c \). Fig. 3 shows the abstract sub-memory \( m^2_b \) depicted in labeled box 1 in Fig. 2(a) and a pair \((m_b, \nu_b)\) that concretizes it. Properties about values and addresses are expressed in \( n^2 \), using a product with a numerical domain [5]. For instance, a numerical domain enabling linear equalities is used in Fig. 3(a). Besides, a product with a pointer domain may be used to capture, for example, aliasing relations. The memory abstract domain of [16] extends this basic layout (and handles unions, non-fixed cell sizes, etc.). **Example 2 (Separating shape graphs).** The separating shape graph abstract domain of [4] provides a second example of a memory abstract domain. An abstract memory is a separating conjunction [17] of predicates, which could be either points-to predicates (depicted as thin edges in Fig. 4(c)) and inductive predicates (depicted as bold edges) We define the set of symbolic names of the combined abstract domain as the \[ I \] Thus, the combined abstract domain is defined by \[ (\mathcal{M}_1 \otimes \mathcal{M}_2)(\mathcal{N}_1 \times \mathcal{N}_2) \] Regions and an abstract interface representing correlations between the sub-memories. We also define a judgment \( i \vdash \alpha \subseteq \mathcal{N}_1 \times \mathcal{N}_2 \) and an abstract interface \( i^2 \) is concretized into a set of pairs of valuations of \( \mathcal{M}_1 \) and \( \mathcal{M}_2 \) in the following way: \[ \gamma_{i^2}(i^2) \equiv \{ (\nu_1, \nu_2) \in \mathcal{V}_{\mathcal{M}_1} \times \mathcal{V}_{\mathcal{M}_2} \mid \forall (\alpha_1, \alpha_2) \in i^2, \nu_1(\alpha_1) = \nu_2(\alpha_2) \} \] We write \( I^2 \) instead of \( I^2(\mathcal{M}_1, \mathcal{M}_2) \) when there is no ambiguity about the choice of the memory abstract sub-domains. We also define a judgment \( i^2 \vdash \alpha_1 = \alpha_2 \) meaning that the pair \((\alpha_1, \alpha_2)\) belongs to the transitive closure of the relation induced by \(i^2\). Thus, it meets the soundness condition \( i^2 \vdash \alpha_1 = \alpha_2 \land (\nu_1, \nu_2) \in \gamma_{i^2}(i^2) \Rightarrow \nu_1(\alpha_1) = \nu_2(\alpha_2) \). The separating abstract domain combinator. Combined abstract memories consist of triples \((\mathcal{M}_1, \mathcal{M}_2, i^2)\) made of two abstract sub-memories describing disjoint memory regions and an abstract interface representing correlations between the sub-memories. Thus, the combined abstract domain is defined by \( \mathcal{M}_1 \otimes \mathcal{M}_2 \equiv \mathcal{M}_1 \times \mathcal{M}_2 \times I^2(\mathcal{M}_1, \mathcal{M}_2) \). We define the set of symbolic names of the combined abstract domain as the disjoint... (a) Combined abstract memory $(m_1^2, m_2^2, i^2)$ \[ m_1^2 = \alpha_2 \rightarrow \{ 0 : \beta_0 \} \ast \alpha_1 \rightarrow \{ 0 : \beta_1 \} \] \[ m_2^2 = \alpha_3 \rightarrow \{ 0 : \beta_2 \} \ast \alpha_4 \rightarrow \{ 0 : \beta_3 \} \] \[ \ast \alpha_3 \rightarrow \{ 0 : \beta_2 \} \ast \alpha_4 \rightarrow \{ 0 : \beta_3 \} \land h = \alpha_0 \land \ldots \] (b) Concrete memory $m_b \uplus m_i$ \[ \nu_b \uplus \nu_l : \mathcal{N}_{M_2^b \uplus M_2^l} \rightarrow V \] \[ (m_b^i : \alpha_0^i) \rightarrow 0x...b0 \] \[ (m_b^i : \alpha_1^i) \rightarrow 0x...a0 \] \[ (m_b^i : \alpha_2^i) \rightarrow 0x...a4 \] \[ (m_b^i : \alpha_3^i) \rightarrow 0x...a8 \] \[ (m_b^i : \alpha_4^i) \rightarrow 0x...a12 \] \[ (m_l^i : \alpha_0^i) \rightarrow 0x...c0 \] \[ (m_l^i : \alpha_1^i) \rightarrow 0x...c4 \] (c) Valuation $\nu_b \uplus \nu_l \in \mathcal{V}_{M_2^b \uplus M_2^l}$ **Fig. 6.** Combined memory abstract domain: $(m_b \uplus m_i, \nu_b \uplus \nu_l) \in \gamma_{M_2^b \uplus M_2^l}(m_1^2, m_2^2, i^2)$ as $(m_b, \nu_b) \in \gamma_{M_2^b}(m_1^b)$ (Fig. 3), $(m_i, \nu_l) \in \gamma_{M_2^l}(m_1^l)$ (Fig. 4) and $(\nu_b, \nu_l) \in \gamma_M(i^2)$ union of symbolic names of the abstract sub-domains. Formally: \[ \mathcal{N}_{M_2^b \uplus M_2^l} \equiv \{ (m_b^i : \alpha_1) \mid \alpha_1 \in \mathcal{N}_{M_2^b} \} \uplus \{ (m_l^i : \alpha_2) \mid \alpha_2 \in \mathcal{N}_{M_2^l} \} \] At the combined abstract domain level, $(m_b^i : \alpha_i)$ denotes symbolic name $\alpha_i$ of the abstract sub-domain $M_2^i$. To define the meaning of a combined abstract memory, we give a concretization function $\gamma_{M_2^b \uplus M_2^l} : M_2^b \uplus M_2^l \rightarrow \mathcal{P}(M \times V_{M_2^b \uplus M_2^l})$ that derives from concretization functions $\gamma_{M_2^b} : M_2^b \rightarrow \mathcal{P}(M \times V_{M_2^b})$ of the memory abstract sub-domains. To achieve this, we define a valuation combinator $\mathcal{V} : \mathcal{V}_{M_2^b} \times \mathcal{V}_{M_2^l} \rightarrow \mathcal{V}_{M_2^b \uplus M_2^l}$ that puts two valuations aside: \[ (\nu_1 \uplus \nu_2) : (m_b : \alpha_1) \overset{\text{def}}{=} \nu_1(\alpha_1) \] \[ (\nu_1 \uplus \nu_2) : (m_l : \alpha_2) \overset{\text{def}}{=} \nu_2(\alpha_2) \] Then, the concretization of a combined abstract memory is given by: \[ \gamma_{M_2^b \uplus M_2^l}(m_1^2, m_2^2, i^2) \overset{\text{def}}{=} \{ (m_1 \uplus m_2, \nu_1 \uplus \nu_2) \mid \forall i \in \{ 1, 2 \}, \nu_i \in \gamma_{M_i^i}(m_i^i) \} \] \[ \land \nu_1(\beta_i) = 0x...b0 \land \nu_0(\beta_i^c) = 0x...c0 \] **Example 3 (Separating combination of $M_2^b$ and $M_2^l$)**. We now consider an instantiation of the separating combination functor, with the bounded data structure domain $M_2^b$ (presented in Example 1) and the list-parameterized separating shape graph domain $M_2^l$ (presented in Example 2). Fig. 6(a) presents a combined abstract memory $(m_1^2, m_2^2, i^2)$ that combines abstract sub-memories already presented in Fig. 3(a) and Fig. 4(c) together with the abstract interface $i^2 = \{ (\beta_0^b, \lambda_0), (\beta_1^l, \lambda_1) \}$. We provide a pair $(m, \nu)$ in Fig. 6(b) and Fig. 6(c) concretizing $(m_1^b, m_1^l, i^2)$ obtained by combining the concrete pairs $(m_b, \nu_b)$ and $(m_l, \nu_l)$ presented in Fig. 3 and Fig. 4. Note that $(\nu_b, \nu_l) \in \gamma_M(i^2)$ as $\nu_0(\beta_0^b) = \nu_l(\lambda_0) = 0x...b0$ and $\nu_0(\beta_1^l) = \nu_l(\lambda_1) = 0x...c0$. 4 Analysis algorithms We now discuss the inference of invariants in the combined domain. A memory abstract domain \( M \) provides for each concrete memory operation \( f : M \rightarrow P(M) \), a counterpart abstract transfer function \( f^\sharp : M^\sharp \rightarrow M^\sharp \) that is sound (i.e. \( \forall (m, \nu) \in \gamma_M^\sharp (m^\sharp), \forall m' \in f(m) \exists \nu' \supseteq \nu. (m', \nu') \in (\gamma_M^\sharp \circ f^\sharp)(m^\sharp) \)). Abstract transfer functions may introduce new symbolic names but may not remove nor change the meaning of existing symbolic names. Hence, a valuation \( \nu' \) in the concretization of the post-condition must extend valuation \( \nu \) that concretizes the pre-condition. Abstract interpreters also require lattice operations (e.g. inclusion checking, widening) to achieve precise fixed point computations. In a combined abstract domain, abstract transfer functions should distribute computations to the sub-memories and the abstract interface, using abstract transfer functions provided by sub-domains. In this section, we detail this mechanism for abstract transfer functions handling memory allocations (Section 4.1), assignments (Sections 4.2, and 4.3), and for inclusion checking (Section 4.4). 4.1 Creation of memory cells Creation of new memory cells occurs either when a block for a new variable is created or when heap space is allocated at run time (e.g. malloc as at line 11 in Fig. 1). In a memory abstract domain \( M^\sharp \), this operation is handled by the abstract transfer function \( \text{new}_M^\sharp \), which is the abstract counterpart of the concrete transfer function \( \text{new} : \mathbb{Z} \times M \rightarrow P(\mathbb{Z} \times M) \) (defined in a standard way). Intuitively, \( \text{new}_M^\sharp \) takes as input an integer size \( i \) and an abstract memory \( m^\sharp \), and returns a pair consisting of a symbolic name \( \alpha \) representing the address of the allocated block and an abstract memory \( m^\sharp_{\text{post}} \) where the cell has been created. Therefore, it ensures that, if \( \text{new}_M^\sharp (\alpha, m^\sharp_{\text{pre}}) = (\alpha, m^\sharp_{\text{post}}) \) and \( (m, \nu) \in \gamma_M^\sharp (m^\sharp_{\text{pre}}) \), then the following holds: \[ (a, m') \in \text{new}(\alpha, m) \Rightarrow \exists \nu' \supseteq \nu. (m', \nu') \in \gamma_M^\sharp (m^\sharp_{\text{post}}) \land \nu'(\alpha) = a \] Creation of memory cells in a combined domain. Because of the separation principle (Section 3.2), a cell must be represented in exactly one sub-memory in a combined abstract memory \( m^\sharp = (m^\sharp_1, m^\sharp_2, i^\sharp) \). Therefore, we provide two possible definitions for \( \text{new}_M^\sharp \otimes M^\sharp_2 \) deriving from two symmetric rules New1 and New2 (New2 is shown in Appendix A.1). Intuitively, the abstract transfer function defined by rule New1 (resp. New2) always represents new cells using sub-domain \( M^\sharp_1 \) (resp. \( M^\sharp_2 \)). **New1** \[ \text{new}_M^\sharp (\alpha, m^\sharp_1) = (\alpha_1, m^\sharp_{1,\text{post}}) \] \[ \text{new}_M^\sharp \otimes M^\sharp_2 (\alpha, (m^\sharp_1, m^\sharp_2, i^\sharp)) = ((M^\sharp_1 : \alpha_1), (m^\sharp_{1,\text{post}}, m^\sharp_{2,\text{post}}, i^\sharp)) \] While both choices are sound, some sub-domains are more suitable than others. For instance, in \( M^\sharp_2 \otimes M^\sharp_1 \), it would be inappropriate to let the allocation of a cell expected to be summarized as part of a list be done in \( M^\sharp_1 \), where summarization cannot be achieved. We consider the abstract transfer functions handling operations such as assignments and reading. While not being critical for soundness, such empirical hints are important to avoid either a loss of precision or a slowdown in the analysis. ### 4.2 Evaluation of l-value and r-value expressions We consider the abstract transfer functions handling operations such as assignments and reading. These operations involve l-values $l \in \mathcal{L}_{\text{STM}}$ and r-values $r \in \mathcal{R}_{\text{STM}}$. Their syntax (shown in Fig. 7(a)) includes classical forms of expressions encountered in a C-like language (structure fields, dereferences, address of, etc.). In this section, we define a mechanism for evaluating l-value and r-value expressions. More formally, the evaluation of an l-value $l$ in abstract memory $m^\sharp$ returns a pair $\mathcal{L}_{\text{STM}}[l] m^\sharp = (\alpha, \underline{l})$ consisting of a symbolic name $\alpha$ and a field $\underline{l}$ such that $\alpha + \underline{l}$ denotes the address represented by $l$. Similarly, the evaluation of a r-value $r$ returns an symbolic expression $\mathcal{R}_{\text{STM}}[r] m^\sharp = e$ that denotes the value represented by $r$. A symbolic expression $e \in \mathcal{E}_{\text{STM}}$ is either of the form $\alpha + \underline{l}$ (where $\alpha \in \mathcal{N}_{\text{STM}}$ and $\underline{l} \in \mathcal{F}$) or a concrete value $v \in \mathcal{V}$. **Evaluation algorithm.** The computation of $\mathcal{L}_{\text{STM}}[l]$ and $\mathcal{R}_{\text{STM}}[r]$ proceeds by induction over the expressions syntax as shown in Fig. 7(b), assuming a read operation $\text{read}_{\text{STM}}$ is provided by memory abstract domain $\mathcal{M}^\sharp$, so as to “extract” the contents of a cell at the abstract level: partial function $\text{read}_{\text{STM}}$ inputs a symbolic name $\alpha$ representing the base address of a concrete block, a field \( \ell \) and an abstract memory state \( m^\ell \), and returns a symbolic expression representing the contents of that field. It may also fail to identify the cell and is then undefined (this may happen in a combined memory abstract domain when reading a cell in the “wrong” sub-memory). In some memory abstract domains (such as the separating shape graph domain presented in Example 2), \( \text{read}_{M^\ell} \) may need to perform unfolding \cite{4} and thus, return a finite set of disjuncts, however this issue is orthogonal to the present development, so we leave it out here. Overall, it should satisfy the following soundness condition: \[ (m, \nu) \in \gamma_{M^\ell}(m^\ell) \wedge \text{read}_{M^\ell}(\alpha, \ell, m^\ell) = \beta + g \implies m(\nu(\alpha) + \ell) = \nu(\beta) + g \] \[ (m, \nu) \in \gamma_{M^\ell}(m^\ell) \wedge \text{read}_{M^\ell}(\alpha, \ell, m^\ell) = v \implies m(\nu(\alpha) + \ell) = v \] **Read operation in the combined domain.** To read a cell at address \((M^1_1 : \alpha_1), \ell\) in a combined abstract memory \((m^1_1, m^2_2, i^2)\), the analysis first attempts to read cell at address \(\alpha_1, \ell\) in \(m^1_1\). Therefore, the read operation derives from the following rule: **ReadDirect1** \[ \text{read}_{M^1_1}(\alpha_1, \ell, m^1_1) = \beta_1 + g \] The symmetric rule \(\text{ReadDirect2}\) is shown in Appendix A.2. It may turn out that the cell at address \((M^1_1 : \alpha_1)\) is abstracted in sub-memory \(m^1_2\) in which case rule \(\text{ReadDirect1}\) cannot be applied. In fact, by the separation principle (Section 3.2), a cell is represented in exactly one sub-memory. To cope with this issue, the reading operation can retrieve the cell by looking for a symbolic name of sub-domain \(M^2_2\) that is bound to \(\alpha_1\) by the abstract interface. In such cases, the definition of \(\text{read}_{M^1_1 @ M^2_2}\) follows the rule: **ReadAcross1** \[ \text{read}_{M^1_1}(\alpha_2, \ell, m^1_2, i^2) = \beta_2 + g \] \[i^2 \vdash \alpha_1 = \alpha_2\] The symmetric case is handled by rule \(\text{ReadAcross2}\) shown in Appendix A.2. **Example 4 (An evaluation across sub-memories).** We consider the evaluation of the right hand side \(e \rightarrow \text{data}\) of assignment at line 12 in Fig. 1 on the following combined abstract memory that is computed by the analysis after assignment at line 11 (assignment is treated in Section 4.3). \[ m^1_1 = \alpha_0^1 \rightarrow \{0 : \beta_0^1\} \wedge \alpha_2^1 \rightarrow \{0 : \beta_2^1\} \wedge \alpha_3^1 \rightarrow \{0 : \beta_3^1\} \] \[ m^2_2 = \lambda_2 = 0x0 \rightarrow \text{data} \] \[ \lambda^1 = \{(\beta_0^1, \lambda_0), (\beta_2^1, \lambda_1)\} \] First, variable \(e\) is replaced by symbolic name \((M^2_2 : \alpha^1_1)\) denoting its address and its content is evaluated to \((M^2_2 : \beta^1_1)\). Then, reading cell at address \((M^2_2 : \beta^1_1) + \text{data}\) fails in \(M^2_2\) as the cell is actually abstracted in \(M^2_2\). Therefore, the reading operation retrieves that cell at address \((M^2_2 : \lambda_1) + \text{data}\), using the equality \((\beta^1_1, \lambda_1) \in \lambda^1\). Finally, the evaluation ends up with symbolic r-value \((M^2_2 : \lambda_3)\). 4.3 Abstract transfer function for assignment The analysis requires a set of abstract transfer functions handling operations such as assignment and test that need to evaluate l-value and r-value expressions [5]. Among those, the assignment is arguably the most sophisticated one, thus we describe only this operation here. The classical analysis of assignment \( l = r \) shown in [5] proceeds as follows: (1) the left hand side is evaluated to a pair \( L_M[l] m^l = (\alpha, l) \) representing the address of the cell that will be updated; (2) the right hand side is evaluated to a symbolic expression \( R_M[r] m^r = e \) representing the written value; and (3) the cell is updated in the abstract level, using the abstract cell write operation \( \text{write}_{M^l} \) provided by the memory abstract domain \( M^l \). Intuitively, \( \text{write}_{M^l}(\alpha, l, e, m^l) \) returns an abstract memory where the cell at address \( \alpha + l \) has been updated to \( e \). To state the soundness of this operation, we extend a valuation \( \nu \) to cope with symbolic expressions in a natural way by defining \( \text{val}(\alpha + l) \equiv \nu(\alpha) + l \) and \( \text{val}(v) \equiv v \). Therefore, \( \text{write}_{M^l} \) satisfies the condition: \[ (m, \nu) \in \gamma_{M^l}(m^l) \Rightarrow \exists \nu' \supseteq \nu, (m[\nu(\alpha)+l \leftarrow \text{val}(e)], \nu') \in \gamma_{M^l}(\text{write}_{M^l}(\alpha, l, e, m^l)) \] Cell write operation in a combined domain. A simple case occurs when left and right hand sides are both evaluated in the same sub-memory, in which case the cell write operation simply lifts computation to the corresponding sub-domain. However, a trickier case occurs when l-value and r-value are evaluated to different sub-memories, such as \((M^l_1 : \alpha_1, l)\) and \((M^l_2 : \beta_2) + g\). In this case, the cell writing is performed in \( m^l_1 \) as the cell requiring update is abstracted there. However, to avoid losing precision, the analysis needs a symbolic expression in \( m^l_1 \) to relate the new content. Therefore, two cases may be encountered: - \( \beta_2 \) is bound to a symbolic name \( \beta_1 \in \mathcal{N}_{M^l_1} \) by the abstract interface, in which case \( \text{write}_{M^l_1@M^l_2} \) is defined following the rule: \[ \begin{align*} \text{WRITEACROSS1} & \quad \text{write}_{M^l_1}(\alpha_1, l, \beta_1 + g, m^l_1) = m^l_{1, \text{post}}, \quad \beta_1 = \beta_2 \\ & \quad \text{write}_{M^l_1@M^l_2}(M^l_1 : \alpha_1, l, (M^l_2 : \beta_2) + g, (m^l_1, m^l_2, v)) = (m^l_{1, \text{post}}, m^l_2, v') \end{align*} \] - \( \beta_2 \) is not bound in the abstract interface, in which case a fresh variable \( \beta_1 \) is used to account for it in \( m^l_1 \). Then \( \text{write}_{M^l_1@M^l_2} \) is defined following the rule: \[ \begin{align*} \text{WRITEACROSSWEAK1} & \quad \text{write}_{M^l_1}(\alpha_1, l, \beta_1 + g, m^l_1) = m^l_{1, \text{post}}, \quad \beta_1 \text{ fresh in } m^l_1 \\ & \quad \text{write}_{M^l_1@M^l_2}(M^l_1 : \alpha_1, l, (M^l_2 : \beta_2) + g, (m^l_1, m^l_2, v)) = (m^l_{1, \text{post}}, m^l_2, v' \cup \{(\beta_1, \beta_2)\}) \end{align*} \] Example 5 (Assignment across sub-memories). We consider the computation of the post-condition of assignment \( *x = e \rightarrow \text{data} \) at line 12 in Fig. 1, from the pre-condition shown in Example 4. The left and right hand sides are respectively evaluated to \((M^l_1 : \alpha_2), 0\) and \((M^l_2 : \lambda_3)\) (as shown in Example 4). Moreover, there is no symbolic name in \( m^l_2 \) bound to \( \lambda_3 \) in \( m^l_1 \) by the abstract interface. Therefore, \( \text{write}_{M^l_1@M^l_2} \) Inclusion checking Fix-point computations [6] require widening and inclusion checking operators. In this section, we only detail the algorithm for inclusion checking as the widening algorithm is similar [5]. At a memory abstract domain $M$ level, the inclusion checking relies on the abstract comparison operator $\text{compare}_M$ that inputs two abstract memories $m_1^2$ and $m_2^2$ and returns a mapping $\Phi$ when it successfully establishes the abstract inclusion $m_1^2 \sqsubseteq m_2^2$. Intuitively, the returned mapping relates symbolic names in $m_1^2$ to symbolic names in $m_2^2$ that valuations should map to the same value for the inclusion to hold. More formally, the soundness condition states the following: $$ \text{compare}_M(m_1^2, m_2^2) = \Phi \land (m, \nu) \in \gamma_M(m_1^2) \implies (m, \nu \circ \Phi) \in \gamma_M(m_2^2) $$ Inclusion checking in a combined domain. To compare the two combined abstract memories $m_1^2 = (m_{1,1}^2, m_{1,2}^2, i_1^2)$ and $m_2^2 = (m_{2,1}^2, m_{2,2}^2, i_2^2)$, the analysis first invokes the abstract comparisons of the sub-domains respectively on $(m_{1,1}^2, m_{1,2}^2)$ and $(m_{2,1}^2, m_{2,2}^2)$. When both succeed and thus return $\Phi_1$ and $\Phi_2$, the analysis checks the inclusion of the abstract interfaces by: $$ i_1^2 \sqsubseteq_{\gamma_1} i_2^2 \iff \forall (\alpha_1, \alpha_2) \in i_1^2. \quad i_1^{\alpha_1} \vdash \Phi_1(\alpha_1) = \Phi_2(\alpha_2).$$ Therefore, the abstract comparison operator is defined by the following rule: $$ \begin{array}{c} \text{compare}_{\text{M}_1}(m_{1,1}^2, m_{1,2}^2) = \Phi_1 \\ \text{compare}_{\text{M}_2}(m_{2,1}^2, m_{2,2}^2) = \Phi_2 \\ \text{compare}_{\text{M}_1 \oplus \text{M}_2}((m_{1,1}^2, m_{1,2}^2), (m_{2,1}^2, m_{2,2}^2)) = \Phi_1 \oplus \Phi_2 \end{array} $$ Refinement using initial mappings. While sound, such a definition could lead to a loss of precision. For some memory abstract domains (such as the separating shape graphs domain), the abstract comparison operator internally initializes a mapping between symbolic names representing addresses of the same program variable (that valuations should clearly map to the same value). However, in a combined domain, a sub-memory with no such symbolic names is plausible (e.g. consider $m_1^2$ in the combined abstract memory of Fig. 6(a)), and the sub-domain abstract comparison will therefore likely fail to establish the inclusion. To cope with that issue, the analysis provides an initial mapping as hint to the unsuccessful abstract comparison, that derives from the relationship inferred by the successful abstract comparison. More precisely, if $\text{compare}_{\text{M}_1}$ succeeds and returns $\Phi_1$, the initial mapping defined by $\Phi_1^{\text{init}}(\beta_{2,r}) = \beta_{2,l} \iff \exists \beta_{1,r} \in N_{\text{M}_1}. \quad i_1^2 \vdash \beta_{1,r} = \beta_{2,r} \land i_1^2 \vdash \Phi_1(\beta_{1,r}) = \beta_{2,l}$ can be passed as optional argument to $\text{compare}_{\text{M}_2}$. Fig. 8. Analysis results (measured on a 2.2 Ghz Intel Core i7 with 8 GB of RAM): MAD is the memory abstract domain used (B stands for the bounded data structure domain, I<.> stands for the separating shape graphs domain instantiated with inductive definitions that are either list or tree, ⊗ stands for separating combination of domains), #P is the number of properties proven by the analysis, ∨ is average number of disjuncts at each program point, t is the total analysis time in seconds, % is the time of analysis compared to analysis using a monolithic domain, tCF (resp. tSD) is the time of analysis spent in the combination functor (resp. sub-domains), #R is the number of read operation calls and #RA is the number of read operations crossing sub-memories. 5 Implementation and empirical evaluation We test empirically the precision and efficiency of the combined analysis compared to a monolithic one and describe the results here. The separating combination described in this paper is implemented in the MemCAD analyzer\(^3\). The analysis is fully automatic. It takes as input C code and the desired structure of the memory abstract domain. The two analysis variants were applied to a set of over 15 micro-benchmarks, similar to the code fragment in Fig. 1. We verify memory safety properties, such as the absence of null pointer dereferences, as well as structural assertions (annotated in the code). In Fig. 8, we report on some representative analysis results relevant to questions in this paper. The C programs considered consist of data structure-manipulation routines (e.g. insertion, deletion, search) for lists and trees either called sequentially or interleaved. They can all be analyzed using a monolithic domain. First, we note that importantly the combined analyses retain the same level of precision as the monolithic analyses in terms of the number of properties that can be proven (column #P). For each program, the number of properties proven on the first line (monolithic) is the same as the number proven on the subsequent lines (various combinations). The key part of the combined analysis is the interface between sub-memories. Its necessity is demonstrated by the ratio of read operations that cross the sub-memories in the combined analyses (column #RA over #R). Next, we consider the relative efficiency of the various memory abstract domain combinations with respect to the monolithic version. Regardless of configuration, the MemCAD analyzer computes for each program point, a finite disjunction of abstract memories. We first observe that the use of a combined domain does not introduce an extra combinatorial factor as the number of disjuncts is the same for the monolithic and the combined analyses (column ∨). To probe into the overhead of our combination functor, we considered in search_list_tree.c decomposing the memory abstract domain into list- and tree-specific regions (I<list> ⊗ I<tree>). In this case, the list and tree do- --- \(^3\) http://www.di.ens.fr/~rival/memcad.html mains are instantiations of the same generic, parametric separating shape graph domain. Thus, this instantiation pays for the overhead of the separating combination without the benefit of an optimized sub-domain. We observe that there is an overhead, but it seems acceptable given that the separating combination offers the possibility of replacing the sub-domains with specialized and optimized versions (a ratio of 110%-120% in the two instances shown here). The win with our separating combination functor comes from applying it with an optimized sub-domain. In the variants with B ⊗ · · · , we use a bounded data structure domain to efficiently manage the bounded part of the memory (e.g. the top activation record in the call stack). This sub-domain is implemented efficiently knowing that it only needs to abstract bounded data structures. From Fig. 8, we see that separating out the bounded part of memory into a more efficient specialized domain is highly effective—noticeably decreasing the overall analysis times despite the overhead of combination (a ratio of around 60% in all cases). 6 Related work The first important abstract domain combination operation to be introduced is the reduced product [7], which has enabled constructing very expressive abstract domains from simpler ones. Intuitively, a property is decomposed into a conjunction of (possibly radically different) basic properties. This construction was applied to a wide range of analyzers, including ASTRÉE [3], where a large set of numerical abstract domains exchange information over a chain of reduced products [8]. The benefit of reduced product is even greater for libraries of abstractions with a common interface such as APRON [13]. It was also used to describe the Nelson-Oppen procedure [9]. Our contribution seeks to simplify abstract domain construction, while allowing greater expressiveness. It exploits separation [17], albeit in a different way than the numerous shape analyses that exploit it in the definition of their summarization predicates [10,2,4]. In these analyses, separation permits (hopefully all) updates to be handled as strong updates, which is crucial for both precision and efficiency. Our analysis exploits separation so as to combine independent memory abstract domains, so as to achieve at least the same precision and better efficiency by delegating the abstraction of particular data structures to the most appropriate sub-domains. Note that the sub-domains may (and in all the examples shown in this paper, do) also make use of separation as the aforementioned analyses. In [23], separation was used to represent distinct heap regions using heterogeneous abstractions, yet this work relies on code specifications transformed into sub-problems handled by different abstractions, and proceeds by verification, although our combinator allows inference of invariants. Other combinations of abstractions have been proposed so as to enhance memory analyses. In particular, [14] presents an approach that uses classical conjunction together with zone variables to relate corresponding regions. Moreover, [11] combines formulae by distinguishing per-field and per-object separating conjunctions. In [15], sets of sub-graphs are used to represent properties about non-correlated data structures and to realize a gain in performance. These analyses are based on problem specific de- compositions while our domain combinator is generic, in the sense that it does not make any assumptions on the way the memory properties are represented in the sub-domains. In previous work [22], we proposed a reduced product for memory abstractions as a generic abstract domain combinator. This combinator does not rely on separation and provides a different form of separation of concerns than our separating combinator: in [22], sub-domains express a collection of properties of the same structure whereas the separating conjunction operator combines domains representing distinct structures. Moreover, we introduced a hierarchical memory abstraction to abstract structures allocated inside other structures [21]; in that work the whole memory is abstracted in the main domain, and a sub-domain describes nested structures. These combinators are implemented as ML functors in the MemCAD analyzer and can be used together (although assessing such compositions is beyond the scope of this paper). 7 Conclusion In this paper, we introduced a combinator for separately conjoining memory abstract domains, enabling composite analyses that are precise, efficient, and flexible. Our proposal enables a separation of concerns when designing static analyses that need to deal with complex data structures, as very different domains can be combined to abstract disjoint memory regions. A natural extension of our study would be to integrate other memory abstractions, as found in 3-valued logic shape analyses [19,12], into our framework. References In this section, we give the rules for defining abstract transfer functions of a combined memory abstract domain $M_1^p @ M_2^p$, from the abstract transfer functions of memory abstract sub-domains $M_1^p$ and $M_2^p$. ### A.1 Cell creation operation **A rules for abstract transfer functions of the combined domains** In a combined domain, the cell creation should be handled by exactly one domain (to avoid violating the separation principle). Therefore, depending on which sub-memory is chosen to account for the new cell, we give two definitions for the cell creation operation. creation operation, that derives from the following rules: **NEW1** \[ \text{new}_{M_1}^n(s, m_1^n) = (\alpha_1, m_1^\text{post}) \] \[ \text{new}_{M_1 \otimes M_2}^n(s, (m_1^n, m_2^n, i^n)) = ((M_1^n : \alpha_1), (m_1^\text{post}, m_2^n, i^n)) \] **NEW2** \[ \text{new}_{M_2}^n(s, m_2^n) = (\alpha_2, m_2^\text{post}) \] \[ \text{new}_{M_1 \otimes M_2}^n(s, (m_1^n, m_2^n, i^n)) = ((M_2^n : \alpha_2), (m_1^n, m_2^\text{post}, i^n)) \] ### A.2 Read operation **read** : \( N_{M^2} \times F \times M^2 \rightarrow E_{M^2} \) The read operation (Section 4.2) extracts the content of a cell in the abstract level. In a combined domain, cell read operation first attempts to extract the content of a cell in the sub-memory where the symbolic name representing its address belongs. Therefore, the cell read operation is first defined by the two following rules: **ReadDirect1** \[ \text{read}_{M_2}^n(\alpha_1, f, m_1^n) = \beta_1 + \gamma \] \[ \text{read}_{M_1 \otimes M_2}^n((M_1^n : \alpha_1), f, (m_1^n, m_2^n, i^n)) = (M_1^n : \beta_1) + \gamma \] **ReadDirect2** \[ \text{read}_{M_2}^n(\alpha_2, f, m_2^n) = \beta_2 + \gamma \] \[ \text{read}_{M_1 \otimes M_2}^n((M_2^n : \alpha_2), f, (m_1^n, m_2^n, i^n)) = (M_2^n : \beta_2) + \gamma \] However, cell read operation of sub-domains may fail. In such cases, the cell read operation attempts to retrieve the cell using the abstract interface. It is then defined by the two rules: **ReadAcross1** \[ \text{read}_{M_2}^n(\alpha_2, f, m_2^n) = \beta_2 + \gamma \] \[ \text{read}_{M_1 \otimes M_2}^n((M_2^n : \alpha_2), f, (m_1^n, m_2^n, i^n)) = (M_2^n : \beta_2) + \gamma \] \[ \text{read}_{M_1}^n(\alpha_1, f, m_1^n) = \beta_1 + \gamma \] \[ \text{read}_{M_1 \otimes M_2}^n((M_1^n : \alpha_1), f, (m_1^n, m_2^n, i^n)) = (M_1^n : \beta_1) + \gamma \] ### A.3 Cell write operation **write** : \( N_{M^2} \times F \times E_{M^2} \times M^2 \rightarrow M^2 \) The analysis uses the cell write operation (Section 4.3) to compute post-condition of assignments. It updates the content of a cell in the abstract level. In a combined domain, several cases may be encountered depending on which sub-memory belong the address of the updated cell and the written content. When both are in the same sub-memory, the cell writing operation simply lifts the sub-domain operation: \[ \text{WriteDirect1} \\ \text{write}_{M_1^1} (\alpha_1, \beta_1 + g, m_i^1) = m_{1,\text{post}}^1 \\ \text{write}_{M_1^1 @ M_2^1} ((M_1^1 : \alpha_1), (M_2^1 : \beta_1)) + g, (m_i^1, m_j^1, i^2) = (m_{1,\text{post}}^1, m_{2,\text{post}}^1, i^2) \] \[ \text{WriteDirect2} \\ \text{write}_{M_1^1} (\alpha_2, \beta_2 + g, m_i^1) = m_{2,\text{post}}^2 \\ \text{write}_{M_1^1 @ M_2^1} ((M_2^2 : \alpha_2), (M_2^1 : \beta_2)) + g, (m_i^1, m_j^1, i^2) = (m_{1,\text{post}}^2, m_{2,\text{post}}^2, i^2) \] When the written content is a value \( v \), the cell reading operation is defined by the two following rules: \[ \text{WriteVal1} \\ \text{write}_{M_1^1} (\alpha_1, \underline{v}, m_i^1) = m_{1,\text{post}}^1 \\ \text{write}_{M_1^1 @ M_2^1} ((M_1^1 : \alpha_1), \underline{v}, (m_i^1, m_j^1, i^2)) = (m_{1,\text{post}}^1, m_{2,\text{post}}^1, i^2) \] \[ \text{WriteVal2} \\ \text{write}_{M_1^1} (\alpha_2, \underline{v}, m_i^1) = m_{2,\text{post}}^2 \\ \text{write}_{M_1^1 @ M_2^1} ((M_2^2 : \alpha_2), \underline{v}, (m_i^1, m_j^1, i^2)) = (m_{1,\text{post}}^2, m_{2,\text{post}}^2, i^2) \] The four following rules define read operation when the address of the updated cell and the written value are in different sub-memories. \[ \text{WriteAcross1} \\ \text{write}_{M_1^1} (\alpha_1, \underline{\beta_1}, m_i^1) = m_{1,\text{post}}^1 \\ \text{write}_{M_1^1 @ M_2^1} ((M_1^1 : \alpha_1), (M_2^1 : \beta_1)) + g, (m_i^1, m_j^1, i^2) = (m_{1,\text{post}}^1, m_{2,\text{post}}^1, i^2) \\ \] \[ \text{WriteAcross2} \\ \text{write}_{M_1^1} (\alpha_2, \underline{\beta_2}, m_i^1) = m_{2,\text{post}}^2 \\ \text{write}_{M_1^1 @ M_2^1} ((M_2^2 : \alpha_2), (M_2^1 : \beta_1)) + g, (m_i^1, m_j^1, i^2) = (m_{1,\text{post}}^2, m_{2,\text{post}}^2, i^2) \] \[ \text{WriteAcrossWeak1} \\ \text{write}_{M_1^1} (\alpha_1, \underline{\beta_1}, m_i^1) = m_{1,\text{post}}^1 \\ \text{write}_{M_1^1 @ M_2^1} ((M_1^1 : \alpha_1), (M_2^1 : \beta_2)) + g, (m_i^1, m_j^1, i^2) = (m_{1,\text{post}}^1, m_{2,\text{post}}^2, i^2 \cup \{\beta_1, \beta_2\}) \] \[ \text{WriteAcrossWeak2} \\ \text{write}_{M_1^1} (\alpha_2, \underline{\beta_2}, m_i^1) = m_{2,\text{post}}^2 \\ \text{write}_{M_1^1 @ M_2^1} ((M_2^2 : \alpha_2), (M_2^1 : \beta_1)) + g, (m_i^1, m_j^1, i^2) = (m_{1,\text{post}}^2, m_{2,\text{post}}^2, i^2 \cup \{\beta_1, \beta_2\}) \]
{"Source-Url": "http://www.di.ens.fr/~toubhans/papers/SAS14.pdf", "len_cl100k_base": 14360, "olmocr-version": "0.1.53", "pdf-total-pages": 19, "total-fallback-pages": 0, "total-input-tokens": 84723, "total-output-tokens": 16092, "length": "2e13", "weborganizer": {"__label__adult": 0.0003619194030761719, "__label__art_design": 0.00047206878662109375, "__label__crime_law": 0.00038695335388183594, "__label__education_jobs": 0.0005545616149902344, "__label__entertainment": 7.987022399902344e-05, "__label__fashion_beauty": 0.0001785755157470703, "__label__finance_business": 0.0003485679626464844, "__label__food_dining": 0.0003407001495361328, "__label__games": 0.0009741783142089844, "__label__hardware": 0.00324249267578125, "__label__health": 0.0004887580871582031, "__label__history": 0.0003833770751953125, "__label__home_hobbies": 0.00017595291137695312, "__label__industrial": 0.0007405281066894531, "__label__literature": 0.0002486705780029297, "__label__politics": 0.00032711029052734375, "__label__religion": 0.0005459785461425781, "__label__science_tech": 0.09637451171875, "__label__social_life": 8.189678192138672e-05, "__label__software": 0.0095977783203125, "__label__software_dev": 0.8828125, "__label__sports_fitness": 0.0003352165222167969, "__label__transportation": 0.0007338523864746094, "__label__travel": 0.0002491474151611328}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 51880, 0.03354]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 51880, 0.54995]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 51880, 0.81654]], "google_gemma-3-12b-it_contains_pii": [[0, 2910, false], [2910, 5758, null], [5758, 8502, null], [8502, 12130, null], [12130, 15480, null], [15480, 16571, null], [16571, 18353, null], [18353, 21819, null], [21819, 25439, null], [25439, 27337, null], [27337, 30618, null], [30618, 34297, null], [34297, 37298, null], [37298, 40328, null], [40328, 43721, null], [43721, 46622, null], [46622, 47208, null], [47208, 49315, null], [49315, 51880, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2910, true], [2910, 5758, null], [5758, 8502, null], [8502, 12130, null], [12130, 15480, null], [15480, 16571, null], [16571, 18353, null], [18353, 21819, null], [21819, 25439, null], [25439, 27337, null], [27337, 30618, null], [30618, 34297, null], [34297, 37298, null], [37298, 40328, null], [40328, 43721, null], [43721, 46622, null], [46622, 47208, null], [47208, 49315, null], [49315, 51880, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 51880, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 51880, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 51880, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 51880, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 51880, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 51880, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 51880, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 51880, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 51880, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 51880, null]], "pdf_page_numbers": [[0, 2910, 1], [2910, 5758, 2], [5758, 8502, 3], [8502, 12130, 4], [12130, 15480, 5], [15480, 16571, 6], [16571, 18353, 7], [18353, 21819, 8], [21819, 25439, 9], [25439, 27337, 10], [27337, 30618, 11], [30618, 34297, 12], [34297, 37298, 13], [37298, 40328, 14], [40328, 43721, 15], [43721, 46622, 16], [46622, 47208, 17], [47208, 49315, 18], [49315, 51880, 19]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 51880, 0.0]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
457c80b407cb123fa2e9bfa0386a47ac8551a4c5
Dynamic Scheduling This Set - Scheduling and Dynamic Execution Definitions From various parts of Chapter 4. - Description of Two Dynamic Scheduling Methods Not yet complete. (Material below may repeat material above.) - Tomasulo's Algorithm Basics Section 4.2 - Reorder Buffer and Tomasulo's Algorithm Sections 4.2 and 4.8 plus non-text material. Non-text material. - Sample Problems Scheduling: Organizing instructions to improve execution efficiency. Static Scheduling: Organizing of instructions by compiler or programmer to improve execution efficiency. Statically Scheduled Processor: A processor that starts instructions in program order. It achieves better performance on code that had been statically scheduled. Processors covered in class up to this point were statically scheduled. Dynamic Scheduling: [processor implementation] A processor that allows instructions to start execution . . . . . . even if preceding instructions are waiting for operands. Static scheduling advantage: time and processing power available to scheduler (part of compiler). Dynamic scheduling advantage: can execute instructions after loads that miss the cache (they will take a long time to complete). (Compiler cannot often predict load misses.) Can make up for bad or inappropriate (targeted wrong implementation) static scheduling. Scheduling Examples Unscheduled Code - `addf f0, f1, f2` - `subf f3, f0, f4` - `multf f5, f6, f7` - `ld f8, 0(r1)` - `addi r1, r1, #8` - `subi r2, r2, #1` Unscheduled Code on Statically Scheduled (HP Chapter-3) DLX <table> <thead> <tr> <th>Cycle</th> <th>0</th> <th>1</th> <th>2</th> <th>3</th> <th>4</th> <th>5</th> <th>6</th> <th>7</th> <th>8</th> <th>9</th> <th>10</th> <th>11</th> </tr> </thead> <tbody> <tr> <td>addf f0, f1, f2</td> <td>IF</td> <td>ID</td> <td>A0</td> <td>A1</td> <td>A2</td> <td>A3</td> <td>WB</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>subf f3, f0, f4</td> <td>IF</td> <td>ID</td> <td>-------&gt;</td> <td>A0</td> <td>A1</td> <td>A2</td> <td>A3</td> <td>WB</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>multf f5, f6, f7</td> <td>IF</td> <td>-------&gt;</td> <td>ID</td> <td>M0</td> <td>M1</td> <td>M2</td> <td>M3</td> <td>M4</td> <td>M5</td> <td>M6</td> <td>WB</td> <td></td> </tr> <tr> <td>ld f8, 0(r1)</td> <td>IF</td> <td>ID</td> <td>-&gt;</td> <td>EX</td> <td>MEM</td> <td>WB</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>addi r1, r1, #8</td> <td>IF</td> <td>-&gt;</td> <td>ID</td> <td>EX</td> <td>MEM</td> <td>WB</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>subi r2, r2, #1</td> <td>IF</td> <td>ID</td> <td>EX</td> <td>MEM</td> <td>WB</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> Execution has four stall cycles. Code Static Scheduled on Statically Scheduled DLX Instructions reordered by compiler or programmer to remove stalls. Execution has zero stall cycles. Dynamic Scheduling Overview Dynamic Scheduling with Register Renaming 1. After decoding instruction rename registers: - Assign a temporary name to destination register. (E.g., call r2 pr9.) - Look up temporary names, in ID register map, for source registers. 2. Move instruction out of ID. 3. Execute instruction when source operands available. 4. Fetch and decode continue even if instructions are waiting to execute. Dynamic Scheduling without Register Renaming 1. Decode instruction. 2. Stall if there are WAR or WAW hazards. 3. Move instruction out of ID. 4. Execute instruction when source operands available. 5. Fetch and decode continue even if instructions are waiting to execute. Most systems covered here do perform register renaming. Dynamic Scheduling Overview What a dynamically scheduled processor must do: - Provide storage for instructions waiting for operands. - Detect when operands for waiting instructions become available. *These will avoid stalls due to true dependencies.* What a dynamically scheduled processor may do: - Assign a new name to a register each time it is written - ... and use those names for source operands. *This will avoid stalls due to name dependencies.* Dynamic Scheduling Terminology **Issue**: [an instruction] Assignment of an instruction to a reorder buffer entry. **Initiate Execution**: a.k.a., **issue, dispatch** Movement of an instruction into an execution unit. **Complete**: [Execution] Movement of an instruction out of an execution unit with the result computed. **Commit**: (a.k.a. **retire, graduate**) Irreversibly write an instruction’s results to a register or memory. **In Flight**: The state of an instruction after being issued but before being committed. (Definitions will be illustrated in reorder buffer example.) Dynamic Scheduling Methods Three main methods described, differ in what temporary name refers to: - **Reorder buffer entry** number. - **Reservation station** number. - **Physical register** number. Common Features: - Use of **reorder buffer** for exception and misprediction recovery. - Use of **register map** to translate between architected (e.g., r1, f10) register name and temporary name. **Common data bus** used to broadcast instruction results. Method 1: Reorder Buffer Entry Naming Characteristics - Fastest and simplest method. Major Parts (N.B.: Parts used differently with other methods.) - **Reorder Buffer (ROB)**: A list, in order, of in-flight instructions. - **ID Register Map**: Used in place of register file. Provides value or ROB entry # for each register. - **Commit Register File**: Holds committed register values, used for recovery. - **Reservation Station**: A buffer where instructions wait to execute. 1 In some 20th century homeworks the reorder buffer is omitted. Stage name shown next to hardware used in that stage. Branch hardware, immediates, load/store hardware not shown. Connections used for recovery not shown. Hardware in ID stage spans several stages in real systems. Each entry holds information on an instruction: - **PC**: Program counter (address) of instruction. - **IR**: The decoded instruction. (Not used here.) - **Status**: Whether completed, and whether raised an exception. - **Value**: The result produced (if applicable). - **Dest**: The destination register to be written. An instruction “uses” the reorder buffer three times. Register Map Used in ID and WB stage. Indexed using architected register number. When an architected register number placed at **Addr** input ... ... provides the latest value or ... ... the ROB entry # of instruction that will produce latest value. Has four ports: - Two for reading source operands (during ID). - One for writing the new ROB # of the destination (during ID). - One for reading ROB # and (if necessary) writing results (during WB). Commit Register File Works like register file in statically scheduled (Chapter-3) implementation. Values written when instructions commit. Used to recover from an exception or misprediction. (Method 1) Reservation Station **Reservation Station:** A buffer where instructions wait to execute. Each functional unit has a set of reservation stations. In ID an instruction is assigned to a RS based on opcode. **Reservation Station Entry:** <table> <thead> <tr> <th>Op</th> <th>ROB#</th> <th>Dest</th> <th>Val1</th> <th>ROB#1</th> <th>Val2</th> <th>ROB#2</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> Op: Operation (May not be same as opcode, but specifies same operation.) ROB#: Reorder buffer entry holding instruction (name of result). Dest: Destination register number. Val1,ROB#1: Value of \( r_{s1} \) (operand 1) or ROB entry of instruction that will produce it. Val2,ROB#2: Value of \( r_{s2} \) or ROB entry of instruction that will produce it. --- (Method 1) Common Data Bus **Common Data Bus (CDB):** A bus connecting functional units to other parts of the processor, used to broadcast results. **Data on CDB:** <table> <thead> <tr> <th>Dest</th> <th>ROB#</th> <th>Status</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> Dest: Destination register. ROB #: Reorder buffer entry number. (Temporary name of dest.) Status: Happy ending, or an exception? Value: The result. Can’t forget that. --- (Method 1) Operation **Stages in execution of an instruction.** **IF:** Same as Chapter 3. (Will change later.) **ID:** Initialize new reorder buffer entry. Reorder buffer provides the new ROB #. Val can be set to anything, Status bits: complete, 0; exception, 0. Controller chooses reservation station. Read operands from register map. Result of read is either value or ROB #. Write ROB# (new name for destination) to register map. **RS/EX:** If both operands found in register map, start execution, otherwise wait in reservation station. If waiting in reservation station: “Listen” to CDB for ROB # of missing operands . . . . . . when “heard” copy value into RS entry. When both values available, execution can start. WB: When functional unit completes execution it tries to get control of CDB (contending with other units). When it gets control it places result and other information on the bus . . . ... instructions waiting in RS may copy the result (if they need it) . . . ... the result may be written into the register map . . . ... the status (hopefully complete, but there could have been an exception) is written into the reorder buffer. An instruction in WB reads the ROB # for the architected destination register from the ID map . . . ... if it matches the instruction’s own ROB # the result is written. C (Commit): When instruction reaches the head of the ROB . . . ... the controller checks the status. If execution complete and unexceptional: Value written into register file. If execution complete but encountered an exception: Recovery is initiated . . . ... All instructions in reorder buffer squashed, . . . ... the register file is copied to the register map, and . . . ... exception handler address loaded into PC. (Method 1) Comments Method for handling loads and stores covered later. Details, such as handling of immediates and branches omitted. If it’s the 21st century, ask for more examples. A value can be in several places: The register map, the reorder buffer, the register file, and a reservation station. This uses alot of storage and wires (which is expensive to implement) but has two advantages: Relatively simple to explain. Fast because values are stored at functional units (in RS). Method 2: Reservation Station Entry Naming Differences with method 1: Reservation station number, rather than ROB entry used to identify operands. Reservation station held by an instruction until it completes execution . . . ... to avoid name duplication. For example, addf below keeps RS 0 and subf is assigned RS 1. This way when addf finishes and writes RS 0 on the CDB to identify the result we can be sure no other instruction is using RS 0 for the result (as subf might have). <table> <thead> <tr> <th>Cycle</th> <th>0</th> <th>1</th> <th>2</th> <th>3</th> <th>4</th> <th>5</th> <th>6</th> <th>7</th> <th>8</th> <th>9</th> <th>10</th> </tr> </thead> <tbody> <tr> <td>addf</td> <td></td> <td>f0</td> <td>f1</td> <td></td> <td>f2</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>WC</td> </tr> <tr> <td>subf</td> <td></td> <td>f0</td> <td>f1</td> <td>f4</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>WC</td> </tr> <tr> <td>mulf</td> <td></td> <td>f5</td> <td>f0</td> <td>f6</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td>WC</td> </tr> </tbody> </table> No diagram for method 2 (since very similar to method 1). Method 3: Physical Register Naming Difference with method 1: A single register file, called the physical register file used to store values. Instructions wait in an instruction queue for execution. (No reservation stations.) A scheduler chooses instructions from queue to execute . . . . . . when chosen they read registers and in the next cycle . . . . . . move to an execution unit. Two register maps are used: **ID Register Map:** Provides physical register numbers for architected registers. Updated in ID, so physical registers might not yet have values. **Commit (C) Register Map:** Provides physical register numbers for architected registers. Updated at commit, so physical register holds a valid value. (Used for recovery.) **Free List** Holds list of unused physical registers. Branch prediction hardware not shown. Immediate handling and other small details not shown. Most recovery connections not shown. In real systems ID and Q span many more stages. Loads and Stores in Dynamically Scheduled Processors Load/Store Unit (LSU) Loads and stores done in two steps: 1. L1: Address computation, and 2. L2: Memory read or write. L2 may encounter a cache miss (data far away). Cache used with load/store unit can be **blocking** or **non-blocking**. If cache is **blocking** must wait for data to arrive before attempting other loads or stores. For example, ```plaintext ! Example: 0(r4) in cache, but 0(r2) not in cache. ! Cycle 0 1 2 3 4 5 6 ... 10 11 12 13 14 lw r1, 0(r2) IF ID L1 L2 -------... ---> WB lh r3, 0(r4) IF ID L1 -------... ---> L2 WB add r10, r10, r1 IF ID RS RS... RS EX --> WB sub r11, r11, r3 IF ID RS... RS RS RS EX WB ``` Because cache is blocking miss by *lw* forces *lh* (and *sub*) to wait, even though data cached. --- If cache is **non-blocking** can attempt other loads and stores while handling miss: With a non-blocking cache, instruction would not wait in L2 during cache miss. For example, ```plaintext ! Example: 0(r4) in cache, but 0(r2) not in cache. ! Cycle 0 1 2 3 4 5 6 ... 10 11 12 13 14 lw r1, 0(r2) IF ID L1 L2 RS -------... L2 WB lh r3, 0(r4) IF ID L1 L2 WB add r10, r10, r1 IF ID RS RS RS... RS EX WB sub r11, r11, r3 IF ID EX WB ``` Because cache is non-blocking miss by *lw* does not delay *lh* (or *sub*). --- Load and Store Dependencies Loads and stores have dependencies too. Consider: ```plaintext ! At cycle 5 we know 0(r1) != 0(r5), but the processor is not omniscient. ! Cycle 0 1 2 3 4 5 6 ... 10 11 12 13 14 lw r1, 0(r2) IF ID L1 L2 RS -------... L2 WB sw 0(r1),r3 IF ID RS RS... RS EX --> WB lw r4, 0(r5) IF ID L1 RS -------... RS L2 WB add r5, r4, r5 IF ID RS -------... RS RS EX --> WB ``` *sw* had to wait because of the true dependency on *r1*. Since *r1* not available the second *lw* has to wait because of ... ... a possible address dependency: 0(r1) # 0(r5). --- The situation is different when the store *address* is available: Consider: ```plaintext ! At cycle 5 we know 0(r3) != 0(r5), and the processor does too. ! Cycle 0 1 2 3 4 5 6 ... 10 11 12 13 14 lw r1, 0(r2) IF ID L1 L2 RS -------... L2 WB sw 0(r3),r1 IF ID L1 L2 WB lw r4, 0(r5) IF ID L1 L2 WB add r5, r4, r5 IF ID RS RS EX WB ``` Here, the second *lw* uses a different address than the *sw*, so it doesn’t have to wait. Load/Store Units for Non-Blocking Caches LSU maintains a queue of instructions in program order. It keeps track of which instructions are waiting for addresses. Store instructions write the cache when they commit. Load instructions can read (bypass) data from store instructions in the queue. The memory (L2) part of a load operation can proceed if... ...its address is available... ...addresses for all preceding queued store instructions are available... ...the load address does not match any preceding store instructions or... ...the address does match a store and the (latest) store data is available. Dynamic Scheduling Methods Scoreboard Avoids stalls due to true dependencies. Covered in text section 4.2, but not in class. Tomasulo’s Algorithm Avoids stalls due to name dependencies... ...by assigning a new name to (renaming) each destination register. Avoids stalls due to true dependencies... ...by holding instructions (in reservation stations) waiting for operands. Three variations covered in class. Widely used in real systems. Editorial Comment The slides that follow contain material that has not yet been integrated into the material above, and so it may seem repetitive or out of place. Tomasulo’s Algorithm Basics Implementation methods vary, a simple system described. Reservation Station (RS) Buffer area where instructions wait for operands and an execution unit. Each functional unit has several reservation stations. Common Data Bus (CDB) A bus connecting functional unit output to... ...register file (in some cases)... ...reservation stations... ...other devices awaiting instruction completion. CDB used to pass results from functional unit to... ...waiting instructions... ...and (in some cases indirectly) the register file. ### Tomasulo’s Algorithm Basics When an instruction is in ID (during issue): - A reservation station is assigned to the instruction. - A temporary name is chosen for destination register. - Following instructions refer to that temporary name. When an instruction completes execution: - Result broadcast on CDB along with temporary name and other information. - Result read from CDB by instructions in RS that need it. - Depending on variation result is... - ...written to register file (if it’s the latest value)... - ...or written to other storage area before reaching register file. ### Execution With Reservation Stations **Pipeline Execution Diagram Notation** - Instruction in reservation station $x$ indicated by: $x$:RS. - Instruction using RS 3 in stage 4 of multiply: 3:M4. **Timing** - Option 1: CDB to execution unit and RS. - Waiting instruction starts while dependent instruction in WB. - Option 2: CDB to RS, RS to execution unit. - Waiting instruction starts cycle after dependent instruction in WB. ### Example: Reservation station numbers: fp add unit, 0-3; fp mult unit, 4-5. Timing uses option 1, reservation station numbers will be used for temporary names. <table> <thead> <tr> <th>Cycle</th> <th>0</th> <th>1</th> <th>2</th> <th>3</th> <th>4</th> <th>5</th> <th>6</th> <th>7</th> <th>8</th> <th>9</th> <th>10</th> <th>11</th> <th>12</th> <th>13</th> </tr> </thead> <tbody> <tr> <td>multf</td> <td>f0, f1, f2</td> <td>IF</td> <td>ID</td> <td>4:RS</td> <td>1:RS</td> <td>1:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td></td> </tr> <tr> <td>subf</td> <td>f3, f0, f4</td> <td>IF</td> <td>ID</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td></td> </tr> <tr> <td>addf</td> <td>f0, f5, f6</td> <td>IF</td> <td>ID</td> <td>1:A1</td> <td>1:A2</td> <td>1:A3</td> <td>1:A4</td> <td>1:WB</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> In cycle 1 `multf` assigned RS 4 and it reads values for $f1$ and $f2$. RS 4 is the temporary name given to its result, $f0$. In cycle 2 `subf` assigned RS 0. It reads the value of $f4$ and the reservation station that will produce $f0$, RS 4. In cycle 3 `subf` sits in RS 0 waiting for `multf` to finish to get $f0$, a.k.a., RS 4. Meanwhile, in ID, `addf` is assigned RS 1, $f0$ will now be known as RS 1. Values for $f5$ and $f6$ are read. In cycle 4 `ltf` assigned RS 2. It reads a value for $f7$ but it will have to wait for RS 1 to finish to get $f0$. ($f0$ and $f7$ are source operands of `ltf`, the destination is the floating-point condition code register). In cycle 8 `addf` writes the common data bus, `ltf` copies the result and starts execution. In cycle 8 the register file is updated since RS 1 is the latest name of $f0$. (The register file would not be updated in this cycle if a reorder buffer were being used. See next example.) In cycle 9 `multf` writes the CDB, `subf` copies the result. In cycle 9 the register file is not updated since RS 4 is an outdated name for $f0$. Example, continued. <table> <thead> <tr> <th>Cycle</th> <th>0</th> <th>1</th> <th>2</th> <th>3</th> <th>4</th> <th>5</th> <th>6</th> <th>7</th> <th>8</th> <th>9</th> <th>10</th> <th>11</th> <th>12</th> <th>13</th> </tr> </thead> <tbody> <tr> <td>multf</td> <td>f0, f1, f2</td> <td>IF</td> <td>ID</td> <td>4:RS</td> <td>1:RS</td> <td>1:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td></td> </tr> <tr> <td>subf</td> <td>f3, f0, f4</td> <td>IF</td> <td>ID</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td></td> </tr> <tr> <td>addf</td> <td>f0, f5, f6</td> <td>IF</td> <td>ID</td> <td>1:A1</td> <td>1:A2</td> <td>1:A3</td> <td>1:A4</td> <td>1:WB</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> In cycle 8 `addf` writes the common data bus, `ltf` copies the result and starts execution. In cycle 8 the register file is updated since RS 1 is the latest name of $f0$. (The register file would not be updated in this cycle if a reorder buffer were being used. See next example.) In cycle 9 `multf` writes the CDB, `subf` copies the result. In cycle 9 the register file is not updated since RS 4 is an outdated name for $f0$. Example, continued. <table> <thead> <tr> <th>Cycle</th> <th>0</th> <th>1</th> <th>2</th> <th>3</th> <th>4</th> <th>5</th> <th>6</th> <th>7</th> <th>8</th> <th>9</th> <th>10</th> <th>11</th> <th>12</th> <th>13</th> </tr> </thead> <tbody> <tr> <td>multf</td> <td>f0, f1, f2</td> <td>IF</td> <td>ID</td> <td>4:RS</td> <td>1:RS</td> <td>1:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td></td> </tr> <tr> <td>subf</td> <td>f3, f0, f4</td> <td>IF</td> <td>ID</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td></td> </tr> <tr> <td>addf</td> <td>f0, f5, f6</td> <td>IF</td> <td>ID</td> <td>1:A1</td> <td>1:A2</td> <td>1:A3</td> <td>1:A4</td> <td>1:WB</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> Example: Reservation station numbers: fp add unit, 0-1; fp mult unit, 4-5, 6-9 integer unit. Add unit has one less reservation station than in last example. Timing uses option 2. Reservation stations will be used for temporary names. Because of CDB timing option 2, subf waits an extra cycle to start, during cycle 9. Because there are not enough add reservation stations, decoding stalls at cycle 5. Dynamic Scheduling with Tomasulo’s Algorithm Variations Three variations, differ in what “temporary name” refers to: - Reservation Stations Only Temporary name is reservation station number of instruction producing result. (Used in examples above.) - Reorder Buffer and Reservation Stations Temporary name is reorder buffer entry number of instruction producing result. - Reorder Buffer, Reservation Stations, Physical (Rename) Registers Temporary name is name of a special rename register. Second and third variations commonly used. Reorder Buffer A buffer holding information about instructions, kept in program order. Each instruction occupies a reorder buffer entry. Each entry has a unique number which can be used to identify the instruction. Reorder Buffer Use In ID reorder buffer entry created for instruction. Entry updated during instruction execution. Entry removed if . . . . . . it is the oldest entry . . . . . . and the instruction has completed execution. When an entry is removed . . . . . . the register file is written if the instruction writes a register . . . . . . memory is written if the instruction writes memory. When an entry is removed the instruction is said to commit. Hardware limits number of instructions that can commit per cycle . . . . . . usually the same as the number that can issue per cycle (1 so far). Commit shown in execution diagram with a WC or WB if it occurs during writeback or C if it occurs later. Removal of item from reorder buffer sometimes called retirement. Example: Reservation station numbers: fp add unit, 0-3; fp mult unit, 4-5. Timing uses option 1. Reorder buffer entry numbers will be used for temporary names. (Entry numbers not shown in diagram.) <table> <thead> <tr> <th>Cycle</th> <th>0</th> <th>1</th> <th>2</th> <th>3</th> <th>4</th> <th>5</th> <th>6</th> <th>7</th> <th>8</th> <th>9</th> <th>10</th> <th>11</th> <th>12</th> <th>13</th> <th>14</th> <th>15</th> </tr> </thead> <tbody> <tr> <td>multf</td> <td></td> <td>f0</td> <td>f0</td> <td>f2</td> <td>IF</td> <td>ID</td> <td>M1</td> <td>M2</td> <td>M3</td> <td>M4</td> <td>M5</td> <td>M6</td> <td>M7</td> <td>WC</td> <td></td> <td></td> </tr> <tr> <td>subf</td> <td>f3</td> <td>f0</td> <td>f0</td> <td>f4</td> <td>IF</td> <td>ID</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>0:RS</td> <td>A1</td> <td>A2</td> <td>A3</td> <td>A4</td> <td>WC</td> </tr> <tr> <td>addf</td> <td>f0</td> <td>f5</td> <td>f6</td> <td>IF</td> <td>ID</td> <td>A1</td> <td>A2</td> <td>A3</td> <td>A4</td> <td>A5</td> <td>A6</td> <td>A7</td> <td>A8</td> <td>A9</td> <td>A10</td> <td></td> </tr> </tbody> </table> RS assignment same as earlier examples however RS freed when execution starts. Note commit symbols in diagram. Table showing time of events during instruction execution: <table> <thead> <tr> <th>Instr</th> <th>Issue</th> <th>Initiate</th> <th>Ex.</th> <th>Complete Ex.</th> <th>Commit</th> </tr> </thead> <tbody> <tr> <td>multf</td> <td>1</td> <td>2</td> <td>3</td> <td>8</td> <td>9</td> </tr> <tr> <td>subf</td> <td>2</td> <td>9</td> <td>12</td> <td>13</td> <td></td> </tr> <tr> <td>addf</td> <td>3</td> <td>4</td> <td>7</td> <td>14</td> <td></td> </tr> <tr> <td>ltf</td> <td>4</td> <td>8</td> <td>11</td> <td>15</td> <td></td> </tr> </tbody> </table> Reorder Buffer and Exceptions Precise exceptions easily provided with a reorder buffer. Reorder buffer entry has an exception bit. Bit is tested when instruction reaches head of buffer (is oldest in buffer). If bit is set reorder buffer cleared and a trap instruction inserted in pipeline. Because bit tested when faulting instruction reaches buffer head . . . . . . all preceding instructions have executed and their registers and memory written. Because buffer cleared, none of the following instructions have written registers or memory. Therefore, exceptions are precise. Register Mapping Register Mapping (noun) The temporary name (RS, reorder buffer entry, or rename register) of an architecturally visible register. Register Mapping (verb) The process of finding the temporary name of an architecturally visible register. Method of Register Mapping (useful in all variations) Maintain a table indexed by architecturally visible register number . . . . . . the table can be part of the register file itself . . . . . . or use a separate memory device (easier to implement). The table provides the latest temporary name, if any. (If latest value is in register file, there is no temporary name.) Table called a register map. Dynamic Scheduling EE 4720 terminology notes: Before 1999, dynamic scheduling called dynamic issue in course materials. Rename registers were not used in problems before 1999. Do not confuse register renaming (assignment of a temporary name to a destination register) with rename registers (a set of additional registers to hold results until an instruction commits). 1998 Homework 4, Problems 4 and 5. 1997 Final Exam, Problems 2a and 2b. See also multiple-issue sample problems, at end of lecture notes sets 11 and 12. Reorder Buffer EE 4720 terminology note: before 1999 the term retire is used instead of commit. 1998 Homework 6, Problem 1. (Includes later material.) 1998 Final Exam, Problem 2. (Includes later material.)
{"Source-Url": "http://www.ece.lsu.edu:80/ee4720/2002/lsli10.4up.pdf", "len_cl100k_base": 8335, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 34578, "total-output-tokens": 8096, "length": "2e13", "weborganizer": {"__label__adult": 0.000316619873046875, "__label__art_design": 0.0003561973571777344, "__label__crime_law": 0.0003750324249267578, "__label__education_jobs": 0.0018606185913085935, "__label__entertainment": 6.335973739624023e-05, "__label__fashion_beauty": 0.00015807151794433594, "__label__finance_business": 0.0001926422119140625, "__label__food_dining": 0.00036215782165527344, "__label__games": 0.0010175704956054688, "__label__hardware": 0.0034084320068359375, "__label__health": 0.0003287792205810547, "__label__history": 0.0002567768096923828, "__label__home_hobbies": 0.00015556812286376953, "__label__industrial": 0.0008592605590820312, "__label__literature": 0.0001977682113647461, "__label__politics": 0.0002598762512207031, "__label__religion": 0.0005540847778320312, "__label__science_tech": 0.04205322265625, "__label__social_life": 7.992982864379883e-05, "__label__software": 0.00732421875, "__label__software_dev": 0.9384765625, "__label__sports_fitness": 0.00031447410583496094, "__label__transportation": 0.0006852149963378906, "__label__travel": 0.00016772747039794922}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 25132, 0.02871]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 25132, 0.29107]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 25132, 0.82331]], "google_gemma-3-12b-it_contains_pii": [[0, 2066, false], [2066, 2982, null], [2982, 5057, null], [5057, 6301, null], [6301, 8250, null], [8250, 10603, null], [10603, 11873, null], [11873, 13893, null], [13893, 15673, null], [15673, 19932, null], [19932, 21893, null], [21893, 24401, null], [24401, 25132, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2066, true], [2066, 2982, null], [2982, 5057, null], [5057, 6301, null], [6301, 8250, null], [8250, 10603, null], [10603, 11873, null], [11873, 13893, null], [13893, 15673, null], [15673, 19932, null], [19932, 21893, null], [21893, 24401, null], [24401, 25132, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 25132, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 25132, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 25132, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 25132, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 25132, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 25132, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 25132, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 25132, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 25132, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 25132, null]], "pdf_page_numbers": [[0, 2066, 1], [2066, 2982, 2], [2982, 5057, 3], [5057, 6301, 4], [6301, 8250, 5], [8250, 10603, 6], [10603, 11873, 7], [11873, 13893, 8], [13893, 15673, 9], [15673, 19932, 10], [19932, 21893, 11], [21893, 24401, 12], [24401, 25132, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 25132, 0.10448]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
c62eeaa7d37f46bfa625f95a2a2afd4c0ab17f67
[REMOVED]
{"Source-Url": "http://www.staff.science.uu.nl/~jeuri101/homepage/Publications/ViewsMPC.pdf", "len_cl100k_base": 16062, "olmocr-version": "0.1.50", "pdf-total-pages": 26, "total-fallback-pages": 0, "total-input-tokens": 83556, "total-output-tokens": 19256, "length": "2e13", "weborganizer": {"__label__adult": 0.0003421306610107422, "__label__art_design": 0.0002923011779785156, "__label__crime_law": 0.0002415180206298828, "__label__education_jobs": 0.0005865097045898438, "__label__entertainment": 4.953145980834961e-05, "__label__fashion_beauty": 0.00013709068298339844, "__label__finance_business": 0.00015723705291748047, "__label__food_dining": 0.0003566741943359375, "__label__games": 0.00043892860412597656, "__label__hardware": 0.0005331039428710938, "__label__health": 0.0004396438598632813, "__label__history": 0.00020134449005126953, "__label__home_hobbies": 7.778406143188477e-05, "__label__industrial": 0.00028705596923828125, "__label__literature": 0.00024700164794921875, "__label__politics": 0.0002219676971435547, "__label__religion": 0.0004892349243164062, "__label__science_tech": 0.006389617919921875, "__label__social_life": 7.832050323486328e-05, "__label__software": 0.003353118896484375, "__label__software_dev": 0.984375, "__label__sports_fitness": 0.0002758502960205078, "__label__transportation": 0.0004227161407470703, "__label__travel": 0.00019931793212890625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 68038, 0.01037]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 68038, 0.65238]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 68038, 0.80756]], "google_gemma-3-12b-it_contains_pii": [[0, 2469, false], [2469, 5533, null], [5533, 7752, null], [7752, 10956, null], [10956, 13897, null], [13897, 17162, null], [17162, 20354, null], [20354, 23004, null], [23004, 26261, null], [26261, 29016, null], [29016, 32016, null], [32016, 35036, null], [35036, 37639, null], [37639, 40443, null], [40443, 42449, null], [42449, 43841, null], [43841, 46491, null], [46491, 48589, null], [48589, 49874, null], [49874, 52459, null], [52459, 53271, null], [53271, 56136, null], [56136, 59109, null], [59109, 62519, null], [62519, 65431, null], [65431, 68038, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2469, true], [2469, 5533, null], [5533, 7752, null], [7752, 10956, null], [10956, 13897, null], [13897, 17162, null], [17162, 20354, null], [20354, 23004, null], [23004, 26261, null], [26261, 29016, null], [29016, 32016, null], [32016, 35036, null], [35036, 37639, null], [37639, 40443, null], [40443, 42449, null], [42449, 43841, null], [43841, 46491, null], [46491, 48589, null], [48589, 49874, null], [49874, 52459, null], [52459, 53271, null], [53271, 56136, null], [56136, 59109, null], [59109, 62519, null], [62519, 65431, null], [65431, 68038, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 68038, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 68038, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 68038, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 68038, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 68038, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 68038, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 68038, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 68038, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 68038, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 68038, null]], "pdf_page_numbers": [[0, 2469, 1], [2469, 5533, 2], [5533, 7752, 3], [7752, 10956, 4], [10956, 13897, 5], [13897, 17162, 6], [17162, 20354, 7], [20354, 23004, 8], [23004, 26261, 9], [26261, 29016, 10], [29016, 32016, 11], [32016, 35036, 12], [35036, 37639, 13], [37639, 40443, 14], [40443, 42449, 15], [42449, 43841, 16], [43841, 46491, 17], [46491, 48589, 18], [48589, 49874, 19], [49874, 52459, 20], [52459, 53271, 21], [53271, 56136, 22], [56136, 59109, 23], [59109, 62519, 24], [62519, 65431, 25], [65431, 68038, 26]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 68038, 0.0]]}
olmocr_science_pdfs
2024-12-01
2024-12-01
4c70ceaa5da97a842f99ca8477bb33c3dd8602e7
Benchmarking Ontology-Based Query Rewriting Systems Martha Imprialou\textsuperscript{1}, Giorgos Stoilos\textsuperscript{2} and Bernardo Cuenca Grau\textsuperscript{1} \textsuperscript{1}Department of Computer Science, University of Oxford, Oxford, UK \texttt{martha.imperialou@balliol.ox.ac.uk} \texttt{bernardo.cuenca.grau@cs.ox.ac.uk} \textsuperscript{2}School of Electrical and Computer Engineering, National Technical University of Athens, Greece \texttt{gstoil@image.ece.ntua.gr} Abstract Query rewriting is a prominent reasoning technique in ontology-based data access applications. A wide variety of query rewriting algorithms have been proposed in recent years and implemented in highly optimised reasoning systems. Query rewriting systems are complex software programs; even if based on provably correct algorithms, sophisticated optimisations make the systems more complex and errors become more likely to happen. In this paper, we present an algorithm that, given an ontology as input, synthetically generates “relevant” test queries. Intuitively, each of these queries can be used to verify whether the system correctly performs a certain set of “inferences”, each of which can be traced back to axioms in the input ontology. Furthermore, we present techniques that allow us to determine whether a system is unsound and/or incomplete for a given test query and ontology. Our evaluation shows that most publicly available query rewriting systems are unsound and/or incomplete, even on commonly used benchmark ontologies; more importantly, our techniques revealed the precise causes of their correctness issues and the systems were then corrected based on our feedback. Finally, since our evaluation is based on a larger set of test queries than existing benchmarks, which are based on hand-crafted queries, it also provides a better understanding of the scalability behaviour of each system. Introduction An important application of ontologies is data access, where an ontology provides the knowledge describing the meaning of application’s data as well as the vocabulary used to formulate user queries. In this setting, query languages are often based on conjunctive queries (CQs), and the answers to queries reflect both the application’s data and the knowledge captured by the ontology (Calvanese et al. 2007; Poggi et al. 2008; Glimm et al. 2007; Lutz, Toman, and Wolter 2009; Ortiz, Calvanese, and Eiter 2006). The need for efficient query answering in ontology-based data access applications has motivated the development of (families of) lightweight ontology languages, such as DL-Lite (Calvanese et al. 2007) (which underpins the OWL 2 QL profile (Motik et al. 2009)), DLP (which underpins the OWL 2 RL profile), as well as (fragments of) datalog\textsuperscript{±} (Cali et al. 2010). These languages are tailored such that query answering becomes tractable in data complexity (and even in logarithmic space in the case of the logics underlying OWL 2 QL). In this setting, query rewriting is a common reasoning technique of choice. Intuitively, a rewriting of a query \( Q \) w.r.t. an ontology \( T \) is another query (typically a union of CQs or a datalog query) that captures the information in \( T \) relevant for answering \( Q \) w.r.t. \( T \) and arbitrary data. Due to the growing interest in ontology-based data access, many rewriting algorithms have been proposed in recent years and implemented in (both commercial and non-commercial) reasoning systems. Examples of such systems include QuOnto (Acciari et al. 2005), Requiem (Pérez-Urbina, Horrocks, and Motik 2009), Presto (Rosati and Almatelli 2010), Nyaya (Gottlob, Orsi, and Pieris 2011), Rapid (Chortaras, Trivela, and Stamou 2011), and IQAROS.\textsuperscript{1} Despite being based on provably correct algorithms, sophisticated optimisations needed in practice make these query rewriting systems rather complex and error-prone software programs. Consequently, both system and application developers would greatly benefit from practical and reliable benchmarking approaches to query rewriting. To the best of our knowledge, little work has been done so far towards the systematic benchmarking of ontology-based query rewriting systems, and developers have relied mostly on “hand-crafted” ontologies and queries for evaluating their systems and comparing them to others. An example of a popular benchmark for query rewriting, which was first used in (Pérez-Urbina, Horrocks, and Motik 2009), consists of nine ontologies and five hand-crafted queries for each of them; systems are evaluated regarding the size of the computed rewritings and the rewriting computation time. Existing benchmarks, however, have several important limitations. First, they are ad hoc: test queries are manually generated for each specific ontology using the developers’ personal knowledge about the ontologies in the benchmark. Second, given a test query \( Q \) and ontology \( T \), it is currently not possible to automatically check whether the relevant systems are sound (i.e., they compute only actual query answers to \( Q \) w.r.t. \( T \) and arbitrary data) and complete (i.e., they compute all answers to \( Q \) w.r.t. \( T \) and arbitrary data). In this paper, we present a novel approach for addressing \textsuperscript{1}http://code.google.com/p/iquaros/ these important limitations. First, we present an algorithm that synthetically generates test queries for an ontology \( T \). Our algorithm is generic, in the sense that it is applicable to a wide range of ontologies and, in particular, to (Horn) ontologies that can be captured by existential rules (Baget et al. 2011; Calì et al. 2010). Furthermore, our algorithm is fully automatic and hence does not require experts’ involvement. Most importantly, each generated query is relevant to \( T \), in the sense that it can be used to verify whether a system correctly performs a certain set of “inferences”, each of which can be traced back to axioms in \( T \). Second, we present techniques that allow us to determine whether a given system is unsound and/or incomplete for given \( Q \) and \( T \); these techniques are easy to implement and in many cases help detect errors with marginal manual effort. Our evaluation shows that most publicly available query rewriting systems are unsound and/or incomplete, even on commonly used benchmark ontologies; most importantly, our techniques revealed the precise causes of their unsoundness and incompleteness issues, and as a result some of the evaluated systems were actually corrected by their developers based on our feedback. Finally, since our collection of tests queries is more “exhaustive” than those in existing benchmarks, our evaluation provides further insights into the scalability behaviour of each system. **Preliminaries** We use standard notions of first-order constants, (free and bound) variables, function symbols, terms, substitutions, predicates, atoms, (ground) formulae, and sentences. A fact is a ground atom, and an instance is a finite set of facts. For \( \phi \) a formula, with \( \phi(\vec{x}) \) we denote that \( \vec{x} \) are the free variables of \( \phi \), while for \( \sigma \) a substitution, \( \phi[\sigma] \) is the result of applying \( \sigma \) to \( \phi \). Satisfiability and entailment are defined as usual. **Ontologies** We use description logics in the wider framework of first order logic, and identify a DL TBox \( T \) with a finite set of first order sentences. Specialised DL syntax will sometimes be used in examples, and we assume that the reader is familiar with the basics of such syntax (Baader et al. 2002). **Existential Rules** An existential rule (Baget et al. 2011; Calì et al. 2010) is a sentence of the form \[ \forall \vec{x}. \forall \vec{z}. [\phi(\vec{x}, \vec{z}) \rightarrow \exists \vec{y}. \psi(\vec{x}, \vec{y})] \] (1) where \( \phi(\vec{x}, \vec{z}) \) and \( \psi(\vec{x}, \vec{y}) \) are conjunctions of function-free atoms and \( \vec{x} \) and \( \vec{z} \) are pair-wise disjoint. Function \( \phi \) is the body, function \( \psi \) is the head, and universal quantifiers are often omitted. Note that, by definition, existential rules are safe—that is, all variables in \( \vec{x} \) occur both in the body and the head. If \( \vec{y} \) is empty, the rule is datalog. Finally, the instantiation of a datalog rule \( r \) w.r.t. a substitution \( \sigma \) mapping all variables in \( r \) to constants is the instance \( I_\sigma \) consisting all facts \( B\sigma \) with \( B \) a body atom in \( r \). If \( \sigma \) is an injective mapping, then \( I_\sigma \) is an injective instantiation of \( r \). Many popular DLs (e.g., those underlying the OWL 2 profiles (Motik et al. 2009)) can be captured by existential rules. **Queries** A query \( Q \) is a finite set of sentences containing a distinct query predicate \( Q \). A tuple of constants \( \vec{a} \) is an answer to \( Q \) w.r.t. TBox \( T \) and instance \( I \) if the arity of \( \vec{a} \) agrees with the arity of \( Q \) and \( T \cup I \cup Q \models Q(\vec{a}) \). We denote with \( \text{cert}(Q, T \cup I) \) the answers to \( Q \) w.r.t. \( T \cup I \). A query \( Q \) is a union of conjunctive queries (UCQ) if it is a set of datalog rules containing \( Q \) in the head but not in the body. In this case, we sometimes abuse notation and use \( Q \) to denote the head atom, rather than the head predicate. A UCQ is a conjunctive query (CQ) if it has exactly one rule. **Query Rewriting** Intuitively, a rewriting of \( Q \) w.r.t. \( T \) is another query that captures all the information from \( T \) relevant for answering \( Q \) over an arbitrary instance \( I \) (Calvanese et al. 2007; P`erez-Urbina, Motik, and Horrocks 2010; Gottlob, Orsi, and Pieris 2011). UCQs and datalog are common target languages for query rewriting; furthermore, virtually all TBoxes to which existing rewriting techniques are applicable can be captured by existential rules. **Definition 1.** A datalog rewriting of a CQ \( Q \) w.r.t. \( T \) is a tuple \( \langle R_D, R_Q \rangle \) with \( R_D \) a set of datalog rules not mentioning \( Q \) and \( R_Q \) a UCQ with query predicate \( Q \) whose body atoms mention only predicates from \( T \), and where for each \( I \) using only predicates from \( T \) we have \[ \text{cert}(Q, T \cup I) = \text{cert}(R_Q, R_D \cup I). \] The rewriting \( \langle R_D, R_Q \rangle \) is a UCQ rewriting if \( R_D = \emptyset \). **The Chase** Given a set of existential rules \( R \) and an instance \( I \), CQ answering over \( R \cup I \) can be characterised using the chase: a technique that computes a (possibly infinite) set chase \( \text{chase}(R \cup I) \) of facts implied by \( R \) and \( I \) in a forward-chaining manner; the result is a universal model over which the CQ can then be evaluated. Although many chase procedures have been proposed in the literature (Fagin et al. 2005; Deutsch, Nash, and Remmel 2008; Marnette 2009), all variants of the chase satisfy the following basic properties: - \( \text{cert}(Q, R \cup I) = \text{cert}(Q, \text{chase}(R \cup I)) \) for all \( Q, R, I \). - For each ground fact \( \alpha \) mentioning only constants and functions from \( R \cup I, R \cup I \models \alpha \) if \( \alpha \in \text{chase}(R \cup I) \). **Query Rewriting Systems** Many optimised query rewriting systems for various ontology languages have been developed in recent years (Calvanese et al. 2007; Rosati and Almatteli 2010; Chortaras, Trivela, and Stamou 2011; Gottlob, Orsi, and Pieris 2011). To abstract from the implementation details, and focus only on the properties of the system that we want to test for, we introduce an abstract notion of a query rewriting system. **Definition 2.** A query rewriting system \( \text{rew} \) for a DL \( L \) is a computable function that, for each TBox \( T \in L \) and each CQ \( Q \) with head predicate \( Q \) computes in a finite number of steps a tuple \( \text{rew}(Q, T) = \langle R_D, R_Q \rangle \) where \( R_D \) is a set of datalog rules not containing \( Q \) and \( R_Q \) is a UCQ with head predicate \( Q \) whose body atoms mention only predicates from \( T \). The system \( \text{rew} \) is \( (Q, T) \)-sound if \( \text{cert}(R_Q, R_D \cup I) \subseteq \text{cert}(Q, T \cup I) \) for every instance \( I \) containing only predicates from \( T \). It is \( (Q, T) \)-complete if \( \text{cert}(Q, T \cup I) \subseteq \text{cert}(R_Q, R_D \cup I) \) for every instance \( I \) containing only predicates from \( T \). Most query rewriting systems are based on algorithms whose behaviour on input $\mathcal{T}$ and $Q$ can be characterised by the application of the following two steps: 1. **Pre-processing**, where the input TBox $\mathcal{T}$ is transformed into a set $\mathcal{R}_\mathcal{T}$ of existential rules. 2. **Query rewriting**, where a calculus (often a variant of resolution) is used to derive $\mathcal{R}_D$ and $\mathcal{R}_Q$ from $\mathcal{R}_\mathcal{T}$ and $Q$. Consequently, two main sources of implementation errors for rewriting systems can be identified, namely those caused by either an incorrect pre-processing, or an incorrect implementation of the calculus. **Example 3.** Let $\mathcal{T}$ consist of the following DL axiom: $$\text{Student} \equiv \text{Person} \cap \exists \text{enrolled.Course} \quad (2)$$ TBox $\mathcal{T}$ can be translated into the following set $\mathcal{R}$ of equivalent existential rules: $$\text{Student}(x) \rightarrow \text{Person}(x) \quad (3)$$ $$\text{Person}(x) \land \text{enrolled}(x, y) \land \text{Course}(y) \rightarrow \text{Student}(x) \quad (4)$$ $$\text{Student}(x) \rightarrow \exists y. (\text{enrolled}(x, y) \land \text{Course}(y)) \quad (5)$$ Some rewriting systems that would accept $\mathcal{T}$ as a valid input do not handle qualified existential restrictions (i.e., concepts such as $\exists$enrolled.Course). If pre-processing $\mathcal{T}$ naively, one such system $\text{rew}_1 \equiv \text{ignore}$ the conjunction involving sub-concept $\exists$enrolled.Course and translate $\mathcal{T}$ into $\mathcal{R}_\mathcal{T}$ consisting only of rule (3) and rule $\text{Person}(x) \rightarrow \text{Student}(x)$. Such system would be unsound for $\mathcal{T}$: given query $\mathcal{Q}_1 = \text{Student}(x) \rightarrow Q(x)$, it would compute the UCQ rewriting $\langle \emptyset, \{ Q_1, Q'_1 \} \rangle$, with $Q'_1 = \text{Person}(x) \rightarrow Q(x)$, which for instance $I_1 = \{ \text{Person}(c) \}$ leads to the incorrect answer $c$. Consider now a system $\text{rew}_2$ that can handle qualified existential restrictions, but which, due to an implementation error, translates $\mathcal{T}$ into $\mathcal{R}_\mathcal{T}$ consisting of rules (3), (4), and rule $\text{Student}(x) \rightarrow \exists y. (\text{enrolled}(x, y))$, thus leaving out conjunction $\text{Course}(y)$ in rule (5). Such system is incomplete for $\mathcal{T}$, as witnessed by $\mathcal{Q}_2 = \text{enrolled}(x, y) \land \text{Course}(y) \rightarrow Q(x)$ and $I_2 = \{ \text{Student}(d) \}$. As described later on in our evaluation section, the aforementioned normalisation issues are related to actual errors we detected in the Rapid system (Chortaras, Trivedi, and Stamou 2011) using our approach, and which were not revealed by existing benchmarks. Finally, as already mentioned, state of the art implementations of rewriting calculi are highly optimised. As described later on, our approach also allowed us to detect several correctness issues in implemented optimisations; these include errors in ordering criteria for query atoms in IQAROS, and issues with subsumption optimisations in Requiem (Pérez-Urbina, Horrocks, and Motik 2009), among others. Example 3 suggests that implementation errors in both pre-processing and rewriting steps can be effectively “uncovered” by a suitable choice of test queries and subsequent analysis of the systems’ outputs for such relevant queries. In what follows, we present an algorithm for computing test queries that are relevant to a TBox. We then present techniques for checking systems’ correctness for a test query. **Algorithm 1 QueryGeneration($\mathcal{R}, bound, \Sigma$)** input: Existential rules $\mathcal{R}$; integer bound. 1: $I_0 := \emptyset$ and root := $\emptyset$ 2: for all $r \in \mathcal{R}$ do 3: \[ I'_r := \text{injective instantiation of } r \text{ to fresh const. } \vec{a} \] 4: \[ I_0 := I_0 \cup I'_r \] 5: root := root $\cup \{ \vec{a} \}$ 6: end for 7: $I_c := I_0$ 8: repeat 9: \[ I_c := I_c \cup \text{applyChaseRule}(\mathcal{R}, I_c) \] 10: until terminate($I_c, bound$) 11: $I := I_c \setminus I_0$ and $\mathcal{CQ} := \emptyset$ 12: for all $\vec{a} \in \text{root}$ do 13: \[ \text{for all } I' \in \text{paths}(\vec{a}, I, \Sigma) \text{ do} \] 14: \[ \text{Let } \sigma \text{ map each constant in } I' \text{ to fresh variable} \] 15: \[ \mathcal{CQ} := \mathcal{CQ} \cup \{ \bigwedge_{P(\vec{b}) \in I'} P(\sigma(\vec{b})) \rightarrow Q(\sigma(\vec{a})) \} \] 16: end for 17: end for 18: return $\mathcal{CQ}$ **Test Query Generation** Virtually all TBoxes to which state of the art rewriting systems are applicable can be captured by existential rules containing only unary and binary predicates. Thus, we only consider such TBoxes $\mathcal{T}$ in this section. Translation of $\mathcal{T}$ into existential rules $\mathcal{R}$ can be performed using well-known structural transformations, which might introduce “fresh” symbols $\Sigma$ (e.g., see (Motik, Shearer, and Horrocks 2009)). Algorithm 1 can then be used to compute test queries from $\mathcal{R}$. The algorithm directly exploits the chase technique, and works in three main stages: 1. **Chase initialisation**, via instantiation of body atoms in $\mathcal{R}$. 2. **Chase expansion**, up to a pre-defined bound. 3. **Query generation**, by “navigating” the expanded chase while replacing ground terms by fresh variables. **Chase initialisation** For each rule $r \in \mathcal{R}$, Algorithm 1 instantiates all body atoms using fresh constants, which are marked as *root constants*, thus constructing an instance $I_0$ that “triggers” the application of each rule in $\mathcal{R}$ (lines 2–6). For the rules in Example 3 we obtain the following initial instance, where root $= \{ a, (b, c) \}$: \[ I_0 = \{ \text{Student}(a), \text{Person}(b), \text{enrolled}(b, c), \text{Course}(c) \} \] **Chase expansion** A chase procedure is then used to materialise new implied facts from existing ones by forward chaining application of rules in $\mathcal{R}$ (lines 8–10). Intuitively, when initialised with $I_0$, the properties of the chase ensure that each rule application represents an inference that is relevant to derive some answer to some query $\mathcal{Q}$ w.r.t. some input instance (and for the given, fixed, TBox $\mathcal{T}$). \[ \text{Note that rules (3) and (5) share the same body, so it suffices to instantiate one of them.} \] Since the chase might not terminate, the algorithm accepts an integer bound (e.g., maximum number of generated facts), which can be used as a termination condition. Alternatively, one can use any of the available acyclicity conditions for existential rules (e.g., (Fagin et al. 2005; Marnette 2009)), which analyse the information flow between the rules to ensure that no cyclic generation of fresh terms occurs. If \( \mathcal{R} \) satisfies any such condition, the chase terminates, and one can dispense with the input bound. In our example, chase expansion would lead to the following instance \( I_c \), where \( a_1 \) and \( b_1 \) are fresh constants generated by the application of rule (5). \[ I_c = I_0 \cup \{ \text{Person}(a), \text{enrolled}(a, a_1), \text{Course}(a_1) \\ \text{Student}(b), \text{enrolled}(b, b_1), \text{Course}(b_1) \} \] **Query generation** Instance \( I = I_c \setminus I_0 \) contains all facts that have been derived from \( I_0 \) during chase expansion. The properties of the chase ensure that \( I \) is forest-shaped. More precisely, since \( I \) contains only unary and binary predicates, we can define \( G(I) \) as the graph whose nodes are the constants in \( I \) and which contains an (undirected) edge between \( c \) and \( d \) iff \( c \) and \( d \) occur together in a fact from \( I \); then \( G(I) \) consists of a set of disconnected trees each of which is rooted at an individual from root. Algorithm 1 generates queries by traversing \( G(I) \) (lines 12–17) along “paths”. More precisely, paths \((\vec{a}, I, \Sigma)\) (see line 13) is the set of all instances \( \vec{I}' \subseteq I \) not containing predicates from \( \Sigma \) and s.t. \( G(\vec{I}') \) is a path in \( G(I) \) involving a constant from \( \vec{a} \). Each such \( \vec{I}' \) is then transformed into a CQ by mapping each constant to a fresh variable s.t. root constants are mapped to answer variables in the head of the query. Clearly, all queries mentioned in Example 3 would be generated by Algorithm 1 for input rules (3)–(5). Note that, in the worst-case, Algorithm 1 might generate exponentially many queries w.r.t. the size of the input. As shown in our evaluation, however, the number of generated queries for commonly-used benchmark ontologies is relatively modest, and they can be computed in just a few seconds. Finally, note that relevant test queries could also be generated from \( I \) by considering instances \( \vec{I}' \subseteq I \) whose graph is a sub-tree of \( G(I) \), rather than simply a path; however, on the one hand, this results in a blowup in the number of queries in practice and, on the other hand, our evaluation suggests that path queries suffice for uncovering many errors in systems and for analysing and comparing their behaviour. **Testing Correctness** Algorithm 1 provides a flexible way for generating relevant test queries. In this section, we present practical techniques for testing soundness and completeness of a rewriting system for a given test query and a given TBox. **Testing Soundness** Assume that \( \text{rew}(Q) = (\mathcal{R}_D, \mathcal{R}_Q) \). Clearly, if we have \( \mathcal{T} \cup Q \models \mathcal{R}_D \cup \mathcal{R}_Q \), the properties of first-order logic entailment ensure that each answer to \( Q \) w.r.t. \( \mathcal{R}_D \cup \mathcal{R}_Q \) and an instance \( I \) is also an answer to \( Q \) w.r.t. \( \mathcal{T} \cup I \), and hence the query rewriting system \( \text{rew} \) is \( (Q, \mathcal{T}) \)-sound. Proposition 4 shows that \( \mathcal{T} \cup Q \models \mathcal{R}_D \cup \mathcal{R}_Q \) can be checked using any reasoner that is sound and complete for checking entailment of a fact by \( \mathcal{T} \) and an instance. For standard DLs, example such reasoners include HermiT (Motik, Shearer, and Horrocks 2009) and Pellet (Sirin et al. 2007). **Proposition 4.** Let \( \text{rew}(Q, \mathcal{T}) = (\mathcal{R}_D, \mathcal{R}_Q) \). Then, we have that \( \mathcal{T} \cup Q \models \mathcal{R}_D \cup \mathcal{R}_Q \) iff the following conditions hold: 1. \( \mathcal{T} \cup I_r \models H \sigma \) for each \( r \in \mathcal{R}_D \), where \( H \) is the head of \( r \) and \( I_r \) an injective instantiation. 2. \( \mathcal{T} \cup Q \cup I_r \models Q \sigma \) for each \( r \in \mathcal{R}_Q \), where \( Q \) is the head of \( r \) and \( I_r \) an injective instantiation. **Proof.** Since \( Q \) does not occur in \( \mathcal{R}_D \), we have that \( \mathcal{T} \cup Q \models \mathcal{R}_D \cup \mathcal{R}_Q \) iff \( \mathcal{T} \models \mathcal{R}_D \) and \( \mathcal{T} \cup Q \models \mathcal{R}_Q \). Furthermore, it is easy to check that a set \( F \) of sentences entails a datalog rule \( r \) with head \( H \) iff \( F \cup I_r \models H \sigma \) for \( I_r \) an injective instantiation; thus, since \( \mathcal{R}_D \) and \( \mathcal{R}_Q \) consist of datalog rules, we have \( \mathcal{T} \models \mathcal{R}_D \) iff Condition 1 holds and \( \mathcal{T} \cup Q \models \mathcal{R}_Q \) iff Condition 2 holds. □ In practice, however, checking soundness of \( \text{rew} \) using a fully-fledged DL reasoner, as suggested by Proposition 4, has the drawback that the process is subject to implementation errors of the DL reasoner. Although this problem can be alleviated by performing the required entailment tests using several DL reasoners to detect possible discrepancies, an alternative is to use a chase procedure, such as the one we used for query generation (see Algorithm 1). Such procedure does not need to be optimised, and consequently its implementation can be rather simple and transparent. The following proposition shows how to exploit the chase for checking \( (Q, \mathcal{T}) \)-soundness of \( \text{rew} \). **Proposition 5.** Let \( \text{rew}(Q, \mathcal{T}) = (\mathcal{R}_D, \mathcal{R}_Q) \) and let \( \mathcal{R} \) be a set of existential rules such that \( \mathcal{T} \) and \( \mathcal{R} \) are logically equivalent. The following conditions imply that \( \text{rew} \) is \( (Q, \mathcal{T}) \)-sound: 1. \( H \sigma \in \text{chase}(\mathcal{R} \cup I_r) \) for each \( r \in \mathcal{R}_D \), where \( H \) is the head of \( r \) and \( I_r \) an injective instantiation. 2. \( \vec{a} \in \text{cert}(Q, \text{chase}(\mathcal{R} \cup I_r)) \) for each \( r \in \mathcal{R}_Q \), where \( Q \) is the head of \( r \) and \( I_r \) an injective instantiation mapping the variables in \( Q \) to \( \vec{a} \). Furthermore, if Condition 2 does not hold, then \( \text{rew} \) is not \( (Q, \mathcal{T}) \)-sound. **Proof.** To show the first claim in the proposition, it suffices to prove that Condition 1 (resp. Condition 2) in the proposition implies Condition 1 (resp. Condition 2) in Proposition 4. Let \( r \in \mathcal{R}_D \), and assume that \( H \sigma \in \text{chase}(\mathcal{R} \cup I_r) \) with \( I_r \) an injective instantiation; since \( H \sigma \) mentions only individuals from \( I_r \) (recall that rules are assumed to be safe), the properties of the chase (see preliminaries) ensure that \( \mathcal{R} \cup I_r \models H \sigma \); but then, since \( \mathcal{T} \models \mathcal{R} \), we have \( \mathcal{T} \cup I_r \models H \sigma \), as required. Finally, let \( r \in \mathcal{R}_Q \) and let \( \vec{a} \in \text{cert}(Q, \text{chase}(\mathcal{R} \cup I_r)) \), where \( I_r \) is an injective instantiation mapping the variables in \( Q \) to \( \vec{a} \). The properties of chase ensure that \( \vec{a} \in \text{cert}(Q, \mathcal{R} \cup I_r) \), which implies \( \mathcal{R} \cup Q \cup I_r \models Q \sigma \). Since \( \mathcal{T} \models \mathcal{R} \), we then have \( \mathcal{T} \cup Q \cup I_r \models Q \sigma \), as required. To show proposition’s last claim, consider \( r \in R_Q \) and an injective instantiation \( I^*_{\sigma} \), where \( \bar{x} \) are the variables in \( Q \) and \( \bar{a} = \sigma(\bar{x}) \). Clearly, \( \bar{a} \in \text{cert}(R_Q, R_D \cup I^*_\sigma) \); furthermore, \( I^*_\sigma \) contains only predicates from \( T \). Next, assume \( \bar{a} \notin \text{cert}(Q, \text{chase}(R \cup I^*_\sigma)) \); then, the properties of the chase imply that \( \bar{a} \notin \text{cert}(Q, R \cup I^*_\sigma) \); finally, since \( R \models T \), we have \( \bar{a} \notin \text{cert}(Q, T \cup I^*_\sigma) \). Thus, \( \text{rew} \) is not \((Q, T)\)-sound. \( \Box \) Note that Proposition 5 provides only a sufficient condition for \((Q, T)\)-soundness of \( \text{rew} \); indeed, it may be the case that Condition 1 fails (i.e., \( H \sigma \notin \text{chase}(R \cup I^*_\sigma) \)) for some \( r \in R_Q \), but \( \text{rew} \) is \((Q, T)\)-sound. In contrast, as shown, failure of Condition 2 for some \( r \in R_Q \) provides a counter-example for \((Q, T)\)-soundness. Thus, if \( \text{rew} \) is a UCQ (i.e., \( R_D = \emptyset \)), Proposition 5 provides both a necessary and sufficient condition for \((Q, T)\)-soundness. **Example 6.** Consider TBox \( T \), rules \( R \), queries \( Q_1, Q'_1 \) and system \( \text{rew}_1 \) from Example 3. For \( Q_1 \) and \( T \), \( \text{rew}_1 \) computes \( \text{rew}_1(Q_1, T) = \{ \emptyset, \{ Q_1, Q'_1 \} \} \). Let \( I^*_{\sigma} = \{ \text{Person}(a) \} \) be an injective instantiation of \( Q^*_1 \) for \( \sigma = \{ x \rightarrow a \} \). Clearly, \( T \models R \) and \( a \notin \text{cert}(Q_1, \text{chase}(R \cup I^*_\sigma)) \). Thus, Proposition 5 implies that \( \text{rew}_1 \) is indeed unsound for \( Q_1 \) and \( T \). \( \Diamond \) In practice, to ensure \((Q, T)\)-soundness of \( \text{rew} \) it suffices to check that Conditions 1 and 2 in Proposition 5 hold already for a subset of the corresponding chase, in which case chase termination does not need to be ensured. On the one hand, these conditions involve checking whether a particular fact can be found in the chase (or whether a particular answer can be derived from the chase); on the other hand, chase construction is monotonic (i.e., derived facts are never deleted), so if a fact can be found in (or an answer can be derived from) a finite subset of the chase, then the fact (or answer) is guaranteed to hold in the final chase. To prove unsoundness, however, one needs to check failure of Condition 2, which requires the full expansion of \( \text{chase}(R \cup I^*_\sigma) \) for each relevant \( r \in R_Q \); thus, chase termination becomes an important issue. Our evaluation will show that these issues can be dealt with, and Proposition 5 can be used effectively to determine soundness and unsoundness in practice for typical benchmark ontologies. ### Testing Completeness Our strategy for detecting sources of incompleteness is to look for and (semi)automatically explicate “disagreements” between query rewriting systems for given \( Q \) and \( T \). The following definition provides the required notions to compare systems’ outputs for completeness evaluation purposes. **Definition 7.** Let \( \text{rew}_i(Q, T) = (R^i_D, R^i_Q) \) for \( i \in \{1, 2\} \). We say that \( \text{rew}_2 \text{ extends} \text{rew}_1 \) for \( Q \) and \( T \) if the following condition holds for each instance \( I \) mentioning only predicates from \( T \): \[ \text{cert}(R^1_Q \cup R^1_D \cup I) \subseteq \text{cert}(R^2_Q \cup R^2_D \cup I) \quad (6) \] If \( \text{rew}_2 \text{ extends} \text{rew}_1 \) and the inclusion in Condition (6) is proper for some \( I \), we say that \( \text{rew}_2 \text{ strictly extends} \text{rew}_1 \). Intuitively, if \( \text{rew}_2 \text{ strictly extends} \text{rew}_1 \), then it is “at least as complete as” \( \text{rew}_1 \) for the given \( Q \) and \( T \). Thus, when evaluating several systems in practice, if one of them extends all the others, we have strong evidence to believe that such system is \((Q, T)\)-complete. Furthermore, if a system \( \text{rew}_2 \) is \((Q, T)\)-sound and strictly extends \( \text{rew}_1 \) for \( Q \) and \( T \), we can conclude that \( \text{rew}_1 \text{ is incomplete for} Q \) and \( T \). The following proposition provides sufficient conditions for checking whether \( \text{rew}_2 \text{ (strictly) extends} \text{rew}_1 \); hence, when used in combination with Proposition 5, it allows us to draw conclusions about systems’ completeness. **Proposition 8.** Let \( \text{rew}_i(Q, T) = (R^i_D, R^i_Q) \) for \( i \in \{1, 2\} \). If both of the following conditions hold, then \( \text{rew}_2 \text{ extends} \text{rew}_1 \) for \( Q \) and \( T \): 1. \( H \sigma \in \text{chase}(R^2_D \cup I^*_\sigma) \) for each \( r \in R^1_D \) with head \( H \), where \( I^*_\sigma \) is an injective instantiation. 2. \( Q \sigma \in \text{chase}(R^2_Q \cup I^*_\sigma) \) for each \( r \in R^1_Q \) with head \( Q \), where \( I^*_\sigma \) is an injective instantiation. Furthermore, if \( R^1_D = R^2_D = \emptyset \), \( \text{rew}_2 \text{ strictly extends} \text{rew}_1 \) for \( Q \) and \( T \). **Proof.** Assume that \( H \sigma \in \text{chase}(R^2_D \cup I^*_\sigma) \) for each \( r \in R^1_D \); the properties of chase ensure that \( R^2_D \cup I^*_\sigma \models H \sigma \) for each \( r \in R^1_D \); but then, since \( I^*_\sigma \) is an injective instantiation of \( r \), this implies that \( R^2_D \models R^1_D \). Similarly, if Condition 2 holds, then we have \( R^2_Q \models R^1_Q \). As a result, (6) holds by the properties of entailment, as required. Finally, assume that \( R^1_D = R^2_D = \emptyset \) and \( r \in R^2_Q \) exists such that \( Q \sigma \notin \text{chase}(R^2_Q \cup I^*_\sigma) \) for \( I^*_\sigma \) an injective instantiation. The properties of the chase then ensure that \( R^1_Q \cup I^*_{\sigma} \notin Q \sigma \); since \( R^2_Q \cup I^*_\sigma \models Q \sigma \), and \( \text{rew}_2 \text{ extends} \text{rew}_1 \), the inclusion in (6) is indeed proper. \( \Box \) Note that \( R^1_D \) and \( R^2_Q \) consist of datalog rules; thus, the chase computations involved in Proposition 8 are guaranteed to terminate. Furthermore, if we determine that \( \text{rew}_2 \text{ strictly extends} \text{rew}_1 \), we can track the application of chase rules in the corresponding chase expansion to detect the source of the systems’ disagreement in a (semi)automatic way. As described in the evaluation section, this allowed us to detect the sources of incompleteness in practice. **Example 9.** Consider \( Q_2, T \) and \( \text{rew}_2 \) from Example 3 and let \( \text{rew}_2(Q_2, T) = (\emptyset, R^2_Q) \). Since \( \text{rew}_2 \) computes rewritings based on \( R^2_T \) in Example 3, we have \( Q'_2 \notin R^2_Q \) for \( Q'_2 = \text{Student}(x) \rightarrow Q(x) \). Let \( \text{rew}_3 \) be a sound system s.t. \( \text{rew}_3(Q_2, T) = (\emptyset, R^3_Q \cup \{ Q'_1 \}) \). \( \text{rew}_3 \) strictly extends \( \text{rew}_2 \) since \( Q(a) \notin \text{chase}(R^3_Q \cup I^*_\sigma) \) for \( I^*_\sigma = \{ \text{Student}(a) \} \); thus, \( \text{rew}_2 \text{ is not} (Q_2, T)\)-complete. \( \Diamond \) ### Experiments We have implemented a test query generator (see Algorithm 1) that is applicable to TBoxes in the DL $\mathcal{ELHI}$.\(^3\) We then applied our query generator to the benchmark ontologies described in (Pérez-Urbina, Horrocks, and Motik 2009). --- \(^3\)Available at http://code.google.com/p/sygenia/ For all test ontologies, except for A, AX, and S, the chase naturally terminated in just a few seconds. Instead of fixing an a priori integer bound for the “cyclic” ontologies (as required by Algorithm 1), our implementation annotates each skolem constant generated by the chase with the rules with existentials in the head that have been applied so far to generate them. If such a rule \( r \) is applicable to facts involving a skolem constant, but \( r \) has been used before in order to generate this particular skolem constant, then we detect a “cycle”; what we bound is the number of such detected cycles. Table 1 summarises our results. We can observe that test queries for all ontologies can be generated rather efficiently and the number of them is also relatively small. <table> <thead> <tr> <th>System</th> <th>Ontology</th> <th>#Queries</th> <th>Issue</th> </tr> </thead> <tbody> <tr> <td>Requiem</td> <td>AX</td> <td>8</td> <td>incomplete</td> </tr> <tr> <td>CGLLR</td> <td>AX</td> <td>8</td> <td>incomplete</td> </tr> <tr> <td>Rapid</td> <td>U</td> <td>36</td> <td>unsound</td> </tr> <tr> <td></td> <td>U</td> <td>18</td> <td>incomplete</td> </tr> <tr> <td>IQAROS</td> <td>S</td> <td>25</td> <td>incomplete</td> </tr> <tr> <td>Nyaya</td> <td>S</td> <td>82</td> <td>incomplete</td> </tr> <tr> <td></td> <td>U, UX</td> <td>23</td> <td>incomplete</td> </tr> </tbody> </table> Table 2: Statistics about unsoundness and incompleteness All systems, except for Rapid, were reported sound for all ontologies and queries using the results in Proposition 5. Rapid was reported unsound for ontology U; since Rapid compute a UCQ rewriting for ontology U and all test queries, we could prove unsoundness and find suitable “witness” instances by again exploiting Proposition 5. Further inspection of the problematic queries revealed that unsoundness was due to a normalisation error similar to the one described in Example 3. The error was reported to the developers of Rapid and fixed in a subsequent release of the tool. As shown in Table 2, all evaluated systems were found incomplete for some test ontologies and queries. In particular, we were able to exploit the results in Proposition 8 to detect discrepancies in the UCQ rewritings computed by each system; a more detailed inspection of the problematic queries and witness instances confirmed that discrepancies were indeed due to incompleteness issues. Rapid’s incompleteness was again due to normalisation issues similar to those described in Example 3. Incompleteness in both CGLLR and Requiem was due to an implementation bug in query subsumption and redundancy elimination optimisations. Incompleteness in IQAROS was due to implementation bugs in ordering criteria for query atoms. These errors were again reported to systems’ developers and fixed based on our feedback. **Performance Evaluation** Performance was evaluated by using the systems’ latest versions; in the case of CGLLR, Requiem, Rapid, and IQAROS, the latest versions include fixes for all the correctness issues we identified in our experiments. Table 3: Sum of rewriting times (seconds) for all test queries <table> <thead> <tr> <th>System</th> <th>CG</th> <th>Req</th> <th>Rap</th> <th>IQAROS</th> <th>Nyaya</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>65.4</td> <td>1.9</td> <td>1.6</td> <td>0.4</td> <td>662.2</td> </tr> <tr> <td>AX</td> <td>5,680.9</td> <td>10,442.2</td> <td>586.8</td> <td>64.2</td> <td>37.5</td> </tr> <tr> <td>P5</td> <td>163.0</td> <td>9.4</td> <td>0.2</td> <td>1.1</td> <td>0.4</td> </tr> <tr> <td>P5X</td> <td>310.0</td> <td>78.7</td> <td>4.8</td> <td>4.0</td> <td>5h</td> </tr> <tr> <td>U</td> <td>0.7</td> <td>0.6</td> <td>0.1</td> <td>0.4</td> <td></td> </tr> <tr> <td>UX</td> <td>0.3</td> <td>0.6</td> <td>0.06</td> <td>0.6</td> <td></td> </tr> <tr> <td>V</td> <td>2.3</td> <td>3.4</td> <td>0.7</td> <td>0.8</td> <td>5.7</td> </tr> </tbody> </table> Table 2 presents, for each ontology and each system, the total time that the system took to compute a UCQ rewriting for all test queries. We can observe that Rapid and IQAROS were significantly faster than the other systems. Moreover, Nyaya could not finish rewriting the test queries for ontologies AX and P5X after 5 hours. Finally, we have evaluated systems’ redundancy elimination mechanisms by measuring the size of the computed UCQ rewritings (i.e., the number of CQs they contain). Table 4 presents, for each ontology and each system, the sum of the sizes of all UCQ rewritings computed for all the test queries. We can observe that CGLLR presents the highest degrees of redundancy in its output, whereas Rapid and IQAROS computed the most succinct rewritings. --- 4http://www.cs.ox.ac.uk/projects/requiem/C.zip 5http://www.cs.ox.ac.uk/projects/requiem/home.html 6http://www.image.ece.ntua.gr/~achort/rapid.zip 7http://code.google.com/p/iqaros/ 8http://mais.dia.uniroma3.it/Nyaya/Home.html 9We do not present results for ontology P1 since it was trivial (under 50 milliseconds) for all systems. 10See Table 1 for total number of test queries for each ontology. Related Work and Conclusions To the best of our knowledge all benchmarks for ontology-based systems rely on hand-crafted test queries (Pérez-Urbina, Motik, and Horrocks 2010; Guo, Pan, and Heflin 2005; Ma et al. 2006). The work that is closest to ours is the formal study of incompleteness of ontology reasoners (Stoilos, Cuenca Grau, and Horrocks 2010; Cuenca Grau and Stoilos 2011), where the authors describe techniques for synthetic query generation; however, these were limited to very lightweight DLs (EL and DL-Lite) under very strict acyclicity conditions, and the queries were used to evaluate incomplete materialisation-based reasoners, such as Jena, Sesame, and OWLIM. In this paper, we presented a test query generation algorithm that can be applied to Horn ontologies. We also presented correctness evaluation techniques which have already been proved useful to uncover serious implementation errors in state of the art rewriting systems. These were not revealed by existing benchmarks and hence our techniques have already proved valuable to systems’ developers. Acknowledgements This work was supported by the EU FP7 project SEALS and by the EPSRC projects ConDOR, ExODA, and LogMap. B. Cuenca Grau is supported by a Royal Society University Research Fellowship. Giorgos Stoilos is supported by a Marie Curie FP7-Reintegration-Grants within European Union’s Seventh Framework Programme (FP7/2007-2013). References
{"Source-Url": "https://www.aaai.org/ocs/index.php/AAAI/AAAI12/paper/viewFile/4910/5270", "len_cl100k_base": 11685, "olmocr-version": "0.1.53", "pdf-total-pages": 7, "total-fallback-pages": 0, "total-input-tokens": 32079, "total-output-tokens": 13697, "length": "2e13", "weborganizer": {"__label__adult": 0.00044035911560058594, "__label__art_design": 0.0006775856018066406, "__label__crime_law": 0.0007305145263671875, "__label__education_jobs": 0.0035877227783203125, "__label__entertainment": 0.0002493858337402344, "__label__fashion_beauty": 0.0002892017364501953, "__label__finance_business": 0.0006852149963378906, "__label__food_dining": 0.0005645751953125, "__label__games": 0.0011768341064453125, "__label__hardware": 0.0008006095886230469, "__label__health": 0.000865936279296875, "__label__history": 0.0005946159362792969, "__label__home_hobbies": 0.00019240379333496096, "__label__industrial": 0.0006885528564453125, "__label__literature": 0.0016889572143554688, "__label__politics": 0.0005021095275878906, "__label__religion": 0.0008373260498046875, "__label__science_tech": 0.344482421875, "__label__social_life": 0.0002810955047607422, "__label__software": 0.029815673828125, "__label__software_dev": 0.609375, "__label__sports_fitness": 0.00034165382385253906, "__label__transportation": 0.0008778572082519531, "__label__travel": 0.0003063678741455078}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44027, 0.03368]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44027, 0.44185]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44027, 0.82014]], "google_gemma-3-12b-it_contains_pii": [[0, 5352, false], [5352, 12642, null], [12642, 19110, null], [19110, 26903, null], [26903, 34564, null], [34564, 39066, null], [39066, 44027, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5352, true], [5352, 12642, null], [12642, 19110, null], [19110, 26903, null], [26903, 34564, null], [34564, 39066, null], [39066, 44027, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 44027, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44027, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44027, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44027, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44027, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44027, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44027, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44027, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44027, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44027, null]], "pdf_page_numbers": [[0, 5352, 1], [5352, 12642, 2], [12642, 19110, 3], [19110, 26903, 4], [26903, 34564, 5], [34564, 39066, 6], [39066, 44027, 7]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44027, 0.08612]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
1503a6efee6a768ce7841861730d8cb3cdcb6b33
[REMOVED]
{"Source-Url": "https://wiki.rice.edu/confluence/download/attachments/4425835/84090040.pdf?api=v2&modificationDate=1393363446522&version=2", "len_cl100k_base": 13628, "olmocr-version": "0.1.49", "pdf-total-pages": 21, "total-fallback-pages": 0, "total-input-tokens": 78257, "total-output-tokens": 15850, "length": "2e13", "weborganizer": {"__label__adult": 0.000446319580078125, "__label__art_design": 0.0004553794860839844, "__label__crime_law": 0.0003993511199951172, "__label__education_jobs": 0.000507354736328125, "__label__entertainment": 7.677078247070312e-05, "__label__fashion_beauty": 0.00021016597747802737, "__label__finance_business": 0.0003371238708496094, "__label__food_dining": 0.0004091262817382813, "__label__games": 0.0010232925415039062, "__label__hardware": 0.0040740966796875, "__label__health": 0.0005869865417480469, "__label__history": 0.0003898143768310547, "__label__home_hobbies": 0.00015270709991455078, "__label__industrial": 0.0008330345153808594, "__label__literature": 0.00024437904357910156, "__label__politics": 0.0003924369812011719, "__label__religion": 0.0006585121154785156, "__label__science_tech": 0.0650634765625, "__label__social_life": 6.479024887084961e-05, "__label__software": 0.0058441162109375, "__label__software_dev": 0.916015625, "__label__sports_fitness": 0.0004630088806152344, "__label__transportation": 0.0009379386901855468, "__label__travel": 0.0003037452697753906}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 51937, 0.04784]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 51937, 0.59938]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 51937, 0.78877]], "google_gemma-3-12b-it_contains_pii": [[0, 2453, false], [2453, 5481, null], [5481, 7555, null], [7555, 10622, null], [10622, 13089, null], [13089, 15171, null], [15171, 18394, null], [18394, 21792, null], [21792, 23474, null], [23474, 26953, null], [26953, 28491, null], [28491, 30024, null], [30024, 32587, null], [32587, 34933, null], [34933, 37874, null], [37874, 40326, null], [40326, 42630, null], [42630, 44688, null], [44688, 47792, null], [47792, 50946, null], [50946, 51937, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2453, true], [2453, 5481, null], [5481, 7555, null], [7555, 10622, null], [10622, 13089, null], [13089, 15171, null], [15171, 18394, null], [18394, 21792, null], [21792, 23474, null], [23474, 26953, null], [26953, 28491, null], [28491, 30024, null], [30024, 32587, null], [32587, 34933, null], [34933, 37874, null], [37874, 40326, null], [40326, 42630, null], [42630, 44688, null], [44688, 47792, null], [47792, 50946, null], [50946, 51937, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 51937, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 51937, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 51937, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 51937, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 51937, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 51937, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 51937, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 51937, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 51937, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 51937, null]], "pdf_page_numbers": [[0, 2453, 1], [2453, 5481, 2], [5481, 7555, 3], [7555, 10622, 4], [10622, 13089, 5], [13089, 15171, 6], [15171, 18394, 7], [18394, 21792, 8], [21792, 23474, 9], [23474, 26953, 10], [26953, 28491, 11], [28491, 30024, 12], [30024, 32587, 13], [32587, 34933, 14], [34933, 37874, 15], [37874, 40326, 16], [40326, 42630, 17], [42630, 44688, 18], [44688, 47792, 19], [47792, 50946, 20], [50946, 51937, 21]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 51937, 0.26048]]}
olmocr_science_pdfs
2024-11-24
2024-11-24
1149b73531c7cdaed3755677a7b1c4d7f1b8ee98
Streams of Steam – The Steam Boiler Specification Case Study Manfred Broy, Franz Regensburger, Bernhard Schätz, Katharina Spies Institut für Informatik Technische Universität München email: {broy,regensbu,schaetz,spiesk}@informatik.tu-muenchen.de Abstract: FOCUS is a mathematics-based methodology for the development of distributed reactive systems. This paper sketches the expressiveness and the usefulness of the well-tuned concepts of FOCUS by its application of the requirements specification of a steam boiler, see [Abr96]. We demonstrate the support for non-specialists in formal methods by using user-friendly description techniques, here the state-oriented specification with table notation techniques, and a broad range of refinement techniques, here the concept of data and state refinement, which eases the explicit modeling of fault-tolerant behavior. Additionally we prove its adaptability in different domains by handling an example of the “control theory” application field. Because of complexity of the above mentioned aspects we do not give a complete and detailed specification, but rather concentrate on the control task starting from classical control theory, the conceptual formal model of FOCUS and its possibilities for formal modeling and system development. 1 Introduction Formal development methods like FOCUS or ProCoS, formal modeling techniques like TLA or UNITY and many others (see [ABL96] and [BMS96] for short descriptions and a comparison based on an example) have often been criticized for minor real-world usefulness. In fact engineers who recognized the need for more accurate and reliable description techniques during the development process ask for user-friendly, well-known notations and their applicability in different (industrially oriented) domains. The general aim of this paper is therefore to demonstrate how a structural approach for the development of a controller can profit from the use of a formal development method. The steamboiler controller is an example concerning control theory, a domain with a long tradition applied to physical systems that are “low-level” from (formal) software-engineer view. We show how user-friendly description-techniques can be used to formally and therefore concisely specify control theoretic behavior. FOCUS is a mathematical framework for the specification, refinement, and verification of distributed, reactive systems (see [BDD93], [Bro93a], or [Bro93b]). Recent developments in FOCUS concentrate on establishing a closer connection between its theoretical framework and more industry oriented approaches (see, for instance, [Fuc93], [Spi94], [SHB95], [PS97],[Spi98], [Hin98a], [Hin98b]) by integrating well-known description techniques, giving methodological hints and applying them to industrial case-studies. In this context, applying FOCUS to the steam boiler case study ([Abr96]) led us to a couple of questions re- quiring a closer look at certain especially methodological aspects. We concentrate on the following major contributions in this article: 1. **FOCUS** in a specific application domain: Control Theory 2. **FOCUS** with user-friendly description techniques: Tables and States 3. **FOCUS** for development of correct software: State Refinement Dealing with the first point we explore the modeling of control theoretic aspects with the semantic basics of FOCUS, the stream processing functions. Control theory (see, for example, [KK94]) has developed well-tuned models for the description of systems with the objective to regulate and control physical devices and processes on a hardware oriented level. Thus, it seems quite natural to exploit this knowledge and to combine it with the concept of reactive systems demonstrating a way for giving precise formalizations of control tasks. This is a first step towards forming a standard approach suitable for high-level and therefore more abstract treatment of controlled physical processes. After showing that the modeling of control theoretic aspects is possible within the framework of FOCUS, the second point deals with the user-friendly presentation of such specifications. We show how the requirements of such a control task can be expressed in a way accessible for the industrial user without losing the preciseness of the formal method. Engineers often use tables for specifying the behavior of mechanical or electrical devices. Tables allow a well-structured representation of large pieces of information and they are a well-known concept used in the process of clarifying the required system properties. Often, they are easier to comprehend and to communicate than logical formulas1. The steam boiler example shows that a large set of requirements can be expressed using a tabular notation. We give a semantics for tables in the mathematical model of FOCUS and apply them to the steam boiler controller. Furthermore, we show the limitation of this notation, and demonstrate how the general framework helps to overcome this by combining tables with general predicative description techniques. Based on a precise and formal but possibly very abstract description of the systems behavior, the concept of refinement allows the treatment of design decisions and the forming of more detailed specifications in a formal and correct way. Our third point deals with this important feature of FOCUS by demonstrating the handling of fault-tolerant behavior. While FOCUS offers a set of quite sophisticated refinement techniques, we will concentrate on two refinement notions, namely data refinement and state refinement. In particular, we demonstrate their embedding into the tabular framework and how the refinement concepts are adapted to the notation of states and tables explained by the steam boiler example. Specifications of systems behavior covers a very important point into the software development process because they form the communication medium between the application expert, the requirements engineer, the system designer and the implementer. Formal specifications provides the basis for formal verification and therefore for software with guaranteed correct behavior. The overall aim of this article is to demonstrate how FOCUS successively combines different aspects of the engineering process. We show some facettes of this very --- 1 See [WT94] for an intensive discussion of this subject. expressive framework, in particular how the requirements engineering process profits from a precise and mathematical basis combined with industrial-strength description techniques. However, we want to point out that this article merely offers an outline how the described concepts of FOCUS can be put to work. We are very well aware of the fact that this is not a sufficiently detailed and complete specification of the steam boiler controller to meet industrial requirements. The paper starts with a description of the steam boiler system. In section 3 we introduce the most essential concepts of control theory, and demonstrate their connection to the FOCUS mathematical model. In section 4 we explain how to use FOCUS in a state-based manner as well as using tables as a convenient notion. In section 5 we use the introduced concepts specifying the steam boiler controller. Using behavioral refinement techniques we extend the original behavior of the controller to cope with faulty sensorial input in section 6. Finally, we give a short conclusion in section 7. 2 The Steam Boiler System The general purpose of the steam boiler system, as shown in Figure 1, is to ensure a safe operation of the steam boiler. The steam boiler operates safely if the contained amount of water never exceeds a certain tolerance, thus avoiding damage to the steam boiler and the turbine driven by the produced steam. Basically, the steam boiler system consists of - the steam boiler itself, - a measuring device for the water level, - a pump to provide the steam boiler with water, - a measuring device for the pump status, - a measuring device for the amount of steam produced by the steam boiler, - an operator desk, - and a message transmission system for the signals produced. During operation, the water level is kept within the tolerance level as long as possible, using the measuring devices and the pump and producing status information for the operator desk. But even with some devices broken, the system can still successfully monitor the steam boiler. If no safe operation is possible any longer, control is handed over to the operator desk. Additionally, the operator can stop the system at any time via the operator desk. 3 Streams Go Control Theory One of the objectives of this case study, as mentioned above, is the modeling of a system that guarantees fault tolerance concerning its sensory input as one of its main features. In order to do so, we consider it necessary to model not only the system in question. We also model the environment of the system consisting of the controlled physical process as well as the physical devices like actors (pumps, valves) and sensors (steam flow measurement units, water throughput measurement units, water level measurement units). Together with the modeling of those components we are interested in the modeling of a possible failure of those components leading to natural definition of the requirements of a fault tolerant system. Since control theory has a long tradition in the treatment of those models we consider it worthwhile to take a short look at the techniques used there. Therefore we introduce the most basic concepts of control theory in section 3.1. Control theory is generally applied to physical, hardware oriented systems that are ‘low level’ from our point of view, since FOCUS mostly deals with more abstract, software oriented systems. Thus, it is furthermore necessary to express the control theoretic approach in a framework more suitable for a more abstract point of view. Since stream processing functions (see, for instance, [BDD93]) proved to provide a powerful basis for the modeling of reactive, distributed systems, we will use them as our formal model. Thus, after giving a short introduction to the concept of stream processing functions in section 3.2.1, we will map the control theoretic terms introduced in section 3.1 on appropriate concepts of the theory of stream processing functions. This is done in section 3.2.2. The main issue of this section is the general demonstration of the usefulness and usability of control theoretic concepts in the framework of stream processing functions. The problem specific questions that arise during the application of this approach to the development of the steam boiler controller will be discussed in section 5. 3.1 Terms from Control Theory In the control theoretic approach, a system always consists of four components, as depicted in Figure 2: - the controller, which is the component to be implemented, - the plant or physical process, which is the part of the environment which is to be controlled, - the control composer, which is the virtual component which adds noise to the controller output, - the feedback composer, which is the virtual component which adds noise to the sensory input of the controller. ![Control Theory System View](image) Figure 2: Control Theory System View This point of view as explained above arises from the fact, that the control task is viewed as a closed control loop. The controller has to manipulate a set of variables influencing the behavior of a physical process or plant (‘manipulated variable’) to tune this plant to a certain value. To do so, the controller relies on signals reporting the state of the plant (‘controlled output’). However, both the manipulating values as well as the reporting signals are distorted by noise (‘control noise’, ‘feedback noise’). The noise is added to the basic signals by corresponding composers (‘control composer’, ‘feedback composer’) to produce the resulting distorted signals (‘disturbed control signal’, ‘feedback signal’). Thus, noise can be used to model faulty or even broken controlling and measurement devices. Furthermore, also the internal state of the controlled process may change due to uncontrolled features (‘plant noise’). For simplification purposes we will, however, not regard the plant noise in the steam boiler example. At a first glance, it may look artificial to construct such a detailed model of the environment if all we are interested in is the specification of the system controlling the steam boiler. Nevertheless, in sections 5.2, 5.3, and 5.4, it will become obvious that this detailed view of the environment will lead to a more concise and application adequate description of the steam boiler requirements. In particular, it will lead to a requirements specification independent of a certain implementation strategy. Now, we relate the above scheme of a closed control loop to the steam boiler example. In order to do so, we have to instantiate - the controller component of Figure 2 to the steam boiler controller of Figure 1 to be implemented, - the plant or physical process of Figure 2 to the steam boiler facilities (like the steam boiler, the pumps, the valve, and the measurement devices) of Figure 1. Furthermore, we have to give a detailed description of - the virtual component adding noise to the control signal sent from the controller to the pumps and the valve, - the virtual component adding noise to the sensory signal send from measurement devices for the water level, water and steam through-put, and pump state to the controller. Since those components are virtual they have no real counterpart in the physical steam boiler system. Besides mapping the system components, we also have to define the messages exchanged between those components. Since our approach abstracts somewhat from specific features of the steam boiler (as, for instance, done in [Abr96]) like the number of pumps, we will only introduce the following messages: - **from the controller to the physical system**: this signal is a compound signal with the attributes - *pump control signal*, - *valve control signal*. - **from the controller to the operator desk**: here, only a simple signal is sent, indicating which state the controller or system is in; in our first approach, we only identify the states - *wait*, - *init*, - *normal*, - *emergency*. • from the physical system to the controller: this signal is a compound signal with the attributes: • water level, • steam throughput, • water throughput, • pump-state. • from the operator desk to the controller: here, only a simple signal is sent, indicating the issuing of a command from the operator desk; in our first approach, only the commands • init, • stop, • reset are identified. In fact, in our first approach to the steam boiler example we even abstract from the detailed description of the structure of both measurement signal and control signal. Since their structure does not have any impact on the specification on the most abstract level, we will leave out this fine-grained structure, and only make use of the description of the operator command signals and the status report signal. 3.2 Using the Framework of Stream Processing Functions As a formal basis for our approach we use stream processing functions as introduced originally in [Kah74]. Since for the understanding of this article only some basics are needed, we only give a short introduction of the elementary concepts as far as they do concern the case study. For a more complete introduction the reader is referred to the literature mentioned in section 1. Given the model of stream processing functions we apply it to the above-introduced section of control theory by mapping its terms on corresponding mathematical concepts. 3.2.1 A Short Introduction Stream processing functions are used to model components performing computations and communicating with their environment by exchanging messages using directed and unbounded buffering channels\(^2\). To describe a component, we therefore note which - possibly infinite - sequence of incoming (received) messages leads to which - possibly infinite - sequence of outgoing (sent) messages. If a component has more than one channel to receive or send messages, we use tuples of such sequences. Thus, a stream processing function can be seen as a function that maps sequences of messages received on its input channels onto sequences of messages sent on its output channels. \(^2\) This form of communication is often referred to as „message asynchronous“ communication. Nondeterministic behavior will be modeled by describing a component not only by one stream processing function but by a set of stream processing functions describing all the possible instances of its nondeterministic behavior. Given a set of messages \( M \), the set \( M^\omega \) of streams over these messages is defined to be the set of all finite or infinite sequences over \( M \). Furthermore, the following two elementary functions for the construction of streams will be defined: - \( \hat{\ } : \) the empty stream, that is, the stream that contains no message, - \( m \& s : \) the stream that has \( m \) as its first element and continued by stream \( s \). Together with these constructor functions we define a few selector functions to be used in the upcoming formulas: - \( \text{first} \): the function selecting the first element of a stream, which is defined by\(^3\) \[ \text{first}(\hat{\ }) = \bot \land \text{first}(m \& s) = m \] - \( \text{rest} \): the function selecting the rest of a stream chopping of the first element, which is defined by \[ \text{rest}(\hat{\ }) = \hat{\ } \land \text{rest}(m \& s) = s \] - \( \text{rest}(i,s) \): the function selecting the \( i \)-th rest of a stream which is defined by \[ \text{rest}(0,s) = s \land \text{rest}(i+1,s) = \text{rest}(i,\text{rest}(s)) \] On the basis of streams we can now define the model for a component receiving messages on \( m \) channels with each input channel \( j \) transporting messages of type \( I_j \), and sending messages on \( n \) channels with each output channel \( k \) transporting messages of type \( O_k \). The model of such a component is a subset of the set of all prefix monotonous and continuous functions from \((I_1^\omega \times \ldots \times I_m^\omega)\) to \((O_1^\omega \times \ldots \times O_n^\omega)\). Their functionality is written as follows\(^4\) \[ (I_1^\omega \times \ldots \times I_m^\omega) \rightarrow (O_1^\omega \times \ldots \times O_n^\omega) \] 3.2.2 Mapping Terms To conclude this section we show how to represent the model of control theory by the concepts of FOCUS. In order to do so, we will map the concepts introduced in section 3.1 on the concepts of 3.2.1. In Figure 3 we give a functional view of the steam boiler system by adding the necessary details to Figure 2. --- \(^3\) Here, \( \bot \) denotes the undefined element. \(^4\) We use “\( \times \)” to denote the Cartesian product. Before instantiating the functional units of the schematic control theory system (including the controller unit, the physical system, and the virtual components to add noise to the system), we have to define the message types used in the upcoming function specifications. As mentioned above, in the first approach we can ignore some details, and therefore define - **C** to be the set of control commands issued by the controller, as well as received by the actuators of the physical unit, with no further information about the structure, - **M** to be the set of measurement signals issued by the sensory units of the physical system, as well as received by the controller, with no further information about the structure, - **O** to be the set of commands issued by the operator desk, - **R** to be the set of commands issued by the controller to indicate the controller status, - **C Noise** and **M Noise** to be the set of noise values added to control or measurement signals by the virtual components. Based on these sets of messages, we can now define the functional components of the steam boiler system: - The **boiler controller** is modeled by a set of functions that receive measurement signals from the sensory units and commands from the control desk and send control signals to the physical system plus status report signals to the operator desk. Thus we define their functionality by $$b: (M^o \times O^o) \rightarrow (C^o \times R^o)$$ - The **physical environment** is mapped onto a set of functions that receive control command messages from the controller and produce measurement data. Physics in general only provide a model that relates current systems values (like water level, water- and steam through-put) and controlling input (like activation of the pumps and valves) with the system values of the next step\(^5\); using the above types, we therefore use functions \( es \) (environment step functions) of the functionality\(^6\) \[ es: M \times C \rightarrow M \] where the system state corresponds to \( C \). To lift this step-wise simulation of the environment up to a function continuously producing output receiving input, we have to embed this view in the stream-based approach which leads to functions \( e \) (environment functions) of functionality \[ e: C^\omega \rightarrow M^\omega \] This can be achieved using the following scheme of equations: \[ e(cs) = es_{\text{lift}}(i,cs) \] \[ \text{where } es_{\text{lift}}(s,c & cs) = es(s,c) & es_{\text{lift}}(es(s,c),cs) \] Here, \( i \in M \) is a possible initial physical state the environment can be in, and \( es \) a function from the set given above. Thus, the model of the environment is obtained by continuously applying the stepwise model \( es \) to the actual state and input, producing the new actual state and reporting this state as observable values. - The virtual components adding noise to the control and measurement signals are mapped to stream processing functions from signals and noise to signals: \[ (C^\omega \times (C \text{ Noise})^\omega) \rightarrow C^\omega \] and \[ (M^\omega \times (M \text{ Noise})^\omega) \rightarrow M^\omega \] respectively. In both cases, we will write \( n \) for such a noise-adding function. This completes the mathematical scheme to define the meaning for our system components. Thus, all necessary terms introduced in the control theory section are translated into the FOCUS framework by giving appropriate function types. However, no behavior is assigned to those functions so far. In the following section we use tables as a user-friendly way to formulize the requirements for the steam boiler controller. ### 4 Streams, States, and Tables As seen in section 3.2.1, stream processing functions provide a powerful and sophisticated framework. For the unfamiliar user it might sometimes appear quite complicated. To im- \(^5\) Since, as generally done with embedded systems, we use a discrete model of time, we can define the next step of the system execution to be the state at the next discrete time step. \(^6\) Since it might be impossible to obtain a realistic mathematical model of the physical environment using only the state information in \( C \), a more detailed state might be necessary. Such a state might not only consist of the actual values but also the derivates of steam and water through-put or water level. prove the comprehensibility and the acceptance, it is necessary to offer presentations that are at the same time precise and easily accessible by the non-formalist. Thus, in section 4.1 we introduce the notion of a state as a means to structure the specification and offer a tabular notation for state transitions. 4.1 Conceptual and Concrete States The use of states for specification purposes comes in two different flavors, conceptual states and concrete states. By the term “conceptual state” we characterize those states which are used to structure the specification, often called control states. They arise from the requirements specification by “clustering” situations that show similar behavior. Conceptual states are not understood as concrete states. Concrete states, on the other hand, are implementation states. In particular, these states have to be mapped to a realization using variables of various types. Concrete states are also often called data states. Depending on the notion of conceptual or concrete states, two different forms of specifications can be characterized: - specification of state-dependent stream processing functions, - state-based specification of stream processing functions. The first term characterizes stream processing functions which explicitly use states as arguments together with stream tuples. Formally, those functions can be characterized using predicates of the form \[ S \rightarrow ((( I_1^o \times \ldots \times I_m^o ) \rightarrow ( O_1^o \times \ldots \times O_n^o )) \rightarrow \mathbb{B} \] with \( S \) being a set of states, \( I_1, \ldots, I_m \) sets of input messages, \( O_1, \ldots, O_n \) sets of output messages, and \( \mathbb{B} \) the set of Boolean values. This class of specifications is discussed in detail, for instance, in [DW92], [Spi94] or [Den95]. Since this class, however, uses concrete states, these specifications require the implementation to be a certain state-based one. Since we are interested in more abstract specifications here, in the following we will use the second class of specifications. The second class characterizes those specifications, which are themselves parameterized with states, and characterize stream processing functions that are not necessarily state-based. Formally, this class can be described by the set of functions described by a predicate of the form \[ S \rightarrow ((( I_1^o \times \ldots \times I_m^o ) \rightarrow ( O_1^o \times \ldots \times O_n^o )) \rightarrow \mathbb{B} ) \] using the above set identifiers. This form of specification is also used in [Den95]. 4.2 Writing Tables In the introduction we have argued that the formal specification of the steam boiler system can be written in an easily readable and understandable but still precise manner by tables. In the following we describe how we use the tables in our specifications and which entries we allow in the tables.\footnote{The use of tables as formal description technique has been discussed using many different approaches; see, e.g., [Jan93], [Par92], or [Bro98].} A table consists of rows and columns in which the information is inscribed. Each table has a heading-line separated from the rest. Each entry in the heading-line encloses a short information about the column below and in which context the reader should interpret the column-entry. The tables that we use in the steam boiler specification describe transitions. They consist of the following columns: - one column (with the header “From”) for the actual state of the component before the transition, - one column-block (with the header “Input”) for the messages which are actually readable at the input-channels, - one column-block (with the header “Output”) for the messages which will be written to the output-channels as a reaction to the read input-messages, and - one column (with the header “To”) for the state of the component after the transition. For table entries we allow both single values for the states or the messages and sets of those values. Finally, we even allow using values for indexed entries, describing whole classes of entries. The parameters used are described following the header marked by a “with” statement. For the understanding of our tables it is essential that we read the input-messages in the actual state simultaneously from all input channels. We then write all output-messages simultaneously to the output-channels and change into the following state. In the presented steam boiler specification we use one table written in the form described above to specify the whole behavior of the controller component in all states to be specified at high level of abstraction. Once the table gets too large to comprehend, it is split up in tables for each state (as also, e.g., in [Spi94]). We use the following scheme for the above introduced table form; here, the column-blocks are distinguished by different shades of grey. \begin{tabular}{|c|c|c|c|} \hline From & Input & Output & To \\ \hline s1 & i11 & o11 & s2 \\ \hline s1 & i12 & o12 & s3 \\ \hline s2 & i21 & o21 & s1 \\ \hline s2 & i22 & o22 & s3 \\ \hline \end{tabular} Figure 4: Example Table ### 4.2.1 Formalizing Tables The formalization of tables, a quite straightforward task, has been carried out in several semantical frameworks (see, e.g., [Jan93], [Par92], or [Bro98]). Using stream processing functions as our formal basis, we will give a short formalization of tables fitting in our framework. The basic intuition underlying the formalization is to interpret each state $s$ by a predicate $P_s$ characterizing the stream-processing functions modeling the input output behavior of the component in the state $s$. In order to do so, each table entry of the form ``` <table> <thead> <tr> <th>From</th> <th>Input</th> <th>Output</th> <th>To</th> </tr> </thead> <tbody> <tr> <td>s1</td> <td>in</td> <td>out</td> <td>s2</td> </tr> </tbody> </table> ``` is translated into the predicate $$\exists f'. (P_{s2}(f') \land f(in \& is) = out \land f'(is))$$ stating the fact, that - given a function $f$, - which is receiving $in$ as next input, then - the characterized function will output $out$ as next output, - and then behave like a function $f'$ being in state $s2$. For the translation of the complete table, all of the predicates generated above associated to one particular state are grouped by conjunction. Here we assume that $i11 \neq i12$, that is, the transitions can be distinguished by the input messages. Thus, for the table depicted in Figure 4 we obtain the following formalization: $$P_{s1}(f) = \forall is. (\exists f'. (P_{s2}(f') \land f(i11 \& is) = o11 \land f'(is)) \land \exists f'. (P_{s3}(f') \land f(i12 \& is) = o12 \land f'(is)))$$ $$P_{s2}(f) = \forall is. (\exists f'. (P_{s1}(f') \land f(i21 \& is) = o21 \land f'(is)) \land \exists f'. (P_{s3}(f') \land f(i22 \& is) = o22 \land f'(is)))$$ So far we have explained the formalization of tables using single values as legal entries in the input and output message columns. Since in the upcoming example we will make use of the above mentioned set-valued entries, this translation scheme has to be extended. This adjustment is simply achieved by replacing the definition of the input and output variable $i$ and $o$. This transformation is demonstrated in the following formalization: $$(i \in \text{IN} \Rightarrow \exists f'. (P_{s2}(f') \land o \in \text{OUT} \land f(i \& is) = o \land f'(is)))$$ The corresponding table entry for this predicate is ``` <table> <thead> <tr> <th>From</th> <th>Input</th> <th>Output</th> <th>To</th> </tr> </thead> <tbody> <tr> <td>s1</td> <td>IN</td> <td>OUT</td> <td>s2</td> </tr> </tbody> </table> ``` with IN and OUT denoting sets of values. Finally, we can use parameterized entries; this is done using a free variable, which is defined in the header block of the table. Here each entry is translated into a parameter header; the corresponding predicate is obtained by quantifying over the free variable according to its definition in the header block. Thus, for the table <table> <thead> <tr> <th>From</th> <th>Input</th> <th>Output</th> <th>To</th> </tr> </thead> <tbody> <tr> <td>s1</td> <td>E11(p)</td> <td>A11(p)</td> <td>s2</td> </tr> </tbody> </table> where \( p \in P \) we give the translation \[ P_{s1}(f) = \forall p \in P \\forall i, is. ((i \in E11(p) \Rightarrow \exists f', o. \quad (P_{s2}(f') \land o \in A11(p) \land f(i & is) = o & f'(is))) \] As usual, the free variable \( p \) in the table is translated to universal quantification. This table scheme is used, for instance, section 5.3. 5 Approaching the Steam Boiler After the short introduction in the concepts of tables, we now formalize the requirements of the steam boiler controller to demonstrate the various facets of our approach. We present the translation between tables and formulas using the example of the steam boiler. We show that the table technique leads to a more readable form than the predicate logic formulas with stream processing functions. 5.1 Steam Boiler States To specify the requirements of the steam boiler controller we will use a state transition approach. As mentioned before, we will use conceptual states to structure the specification by clustering similar behavior. This will simplify the approach in two respects: - A major percentage of the requirements of the steam boiler controller can be described as simple transitions between the introduced conceptual states; thus, using an appropriate tabular or graphical representation, the major part of the functionality of the controller can be easily described. - The refinement of this first requirements specification can be achieved analogously by the introduction of new states; thus, even the refinement of the requirements specification can be performed in a structured way. To be able to demonstrate how refinement is performed in our approach, the first requirements specification will leave out the treatment of broken sensors. In the first approach, we will therefore identify the following four different states: 1. The **wait** state: The state the system is in after start-up, ready to receive the command to initialize the steam boiler. 2. The **initialization** state: The state the system is in during the initialization phase, when the controller is getting ready for the normal operation mode. 3. The **normal** state: The state the system is in if all components are working properly. 4. The **emergency** state: The state the system is in whenever it becomes uncontrollable, and control is handed over to the operator desk. As mentioned above, these states are conceptual states; in particular, these states have to be mapped onto concrete states for an implementation leading to a more complex state space where each state consists of a collection of values recorded from the sensory input signals. An efficient implementation of such a state space might collect relevant information like water level, steam and water throughput, and the corresponding derivatives, as well as the pump and valve state. Figure 5 gives an overview of the above-described states of the steam boiler controller.8 ![Figure 5: The Steam Boiler States](image) The figure relates the states by denoting the transitions between the states with input events. Those input events characterize sets of sensory input signals that will cause the controller to change to the corresponding state. The formal characterization is given in section 5.2. ### 5.2 Formalizing Transitions In the following table we will formalize a set of simple requirements that concern the step-wise behavior of the controller. We will start with the description of the initial wait state of the controller: - **Requirement 1**: Being in the state `wait`, the controller will change to the state `init` given a start command. - **Requirement 2**: Being in the state `wait`, the controller will change to the state `emergency` given a stop command. - **Requirement 3**: Being in the state `wait`, the controller will stay in the state `wait` given no command. --- 8 This form of graphical representation of state transition diagrams is, for instance, used in [HMS98]. The formalization of these requirements is straightforward and does not need any further explanation: <table> <thead> <tr> <th>From</th> <th>Operator</th> <th>Measure</th> <th>Report</th> <th>Control</th> <th>To</th> </tr> </thead> <tbody> <tr> <td>wait</td> <td>start</td> <td>M</td> <td>init</td> <td>C</td> <td>init</td> </tr> <tr> <td>wait</td> <td>stop</td> <td>M</td> <td>emergency</td> <td>C</td> <td>emergency</td> </tr> <tr> <td>wait</td> <td>o</td> <td>M</td> <td>wait</td> <td>C</td> <td>wait</td> </tr> <tr> <td></td> <td>where o ≠ start ∧ o ≠ stop</td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> Here and in the following tables, we use - o for an arbitrary operator command, - m for an arbitrary measured value out of M, - c for an arbitrary control value out of C. Of course, the set of possible input messages can be described more implicitly as done in the previous requirement. This is demonstrated in the description of some requirements of the init state. The corresponding requirements are: **Requirement 4:** Beginning in the state `init´, the controller will change to the state `emergency´ given a stop command. **Requirement 5:** Beginning in the state `init´ and receiving measurement input corresponding to a normal system state recorded without noise, the controller will change to state `normal´ and report this change if not aborted by an operator signal. Requirement 4 is just the corresponding rephrasing of requirement 2 and needs no further explanation. Requirement 5 however, makes use of a more implicit characterization of the set of possible input values. <table> <thead> <tr> <th>From</th> <th>Operator</th> <th>Measure</th> <th>Report</th> <th>Control</th> <th>To</th> </tr> </thead> <tbody> <tr> <td>init</td> <td>stop</td> <td>M</td> <td>emergency</td> <td>C</td> <td>emergency</td> </tr> <tr> <td>init</td> <td>o</td> <td>m</td> <td>normal</td> <td>C</td> <td>normal</td> </tr> <tr> <td></td> <td>where o ≠ stop where ∃ s mn. norm(s) ∧ ok(mn) ∧ m = n(s, mn)</td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> Here, we made use of the following auxiliary functions: - The boolean function \(\text{norm}: M \rightarrow T\) checks whether the state of the controlled system (the system parameters) are within the normal limits, thus describing a legal system state. • The Boolean function \( \text{ok}: M \text{ Noise} \rightarrow T \) checks whether no noise is added to the sensory data recorded by the measurement. It should be noted that the table and thus the corresponding specification are not complete in the sense that many possible situations are not covered that may occur during the execution of the controller. Nevertheless, the underlying semantics makes very clear what the meaning of such an under-specified situation is: \[ \text{If a reaction in a possible situation is not explicitly determined, since the table contains no restriction on the described system, every possible behavior is legal.} \] This follows quite naturally from the formalization. 5.3 Complex Transitions Not all properties of the steam boiler controller are simple state transitions according to the above scheme. Let us have a look at the following property: Requirement 6: If every possible output that may be produced by the controller will take the system out of the limits in absence of noise, then the controller must indicate this by producing `emergency´ and changing into state `emergency´. At first glance, this requirement does not look formalizable according the above-introduced scheme. Nevertheless, even those requirements can be formalized analogously. In order to do so, the point of view must be slightly changed. While the specification in [RSB95] used a global system view, the table specification is always restricted to the interface of the controller itself. Nevertheless, this does not restrict the formalization of the above requirement, if the requirement is restated in an appropriate way, restricting it to inputs and outputs of the controller: Requirement 6': If the measurement was produced by a noiseless recording of a legal system state, which will be changed into an illegal state by any possible noiseless manipulating controller output, then the controller must produce an arbitrary control signal as well as an `emergency´ report and then change to the `emergency´ state. Formally, this set of input values can be described by: \[ \{ m \mid \exists s mn. \forall \ c cn. \text{norm}(s) \land \text{ok}(mn) \land m = n(s,mn) \land \text{ok}(cn) \Rightarrow \neg \text{norm}(es(s,n(c,cn))) \} \] expressing the fact that • on the one hand the measurement message is obtained by adding no noise to an acceptable system state, while • on the other hand from this system state each control signal with no noise added will take the physical system to a state that is no longer acceptable. Thus, we get the following table entry: Another requirement, which is of similar complexity, concerning the set of possible output values is the following property: **Requirement 7**: If there is an output, which will keep the system within the limit, and there is no `stop´-signal issued by the operator, and there is no noise, then the controller has to produce such a manipulation signal, report a `normal´ state and remain in the state `normal´. According to the above case, Requirement 7 is restated in a way suitable for a table representation: **Requirement 7´**: If no `stop´ signal is issued by the operator, and the input is of a kind resulting from a measurement of a legal system state without noise, and the system can be kept in the legal limits by a noiseless manipulating signal, then the controller has to produce such a signal, report a `normal´ situation and remain in the state `normal´. Here, besides the characterization of the set of possible input values \[ \{ m \mid \exists s \ mn \ cs \ c. \ norm(s) \land ok(mn) \land m = n(s,mn) \land ok(cn) \land norm(es(s,n(c,cn))) \} \] also the set of possible output values \[ \{ c \mid \exists s \ mn \ cn. \ norm(s) \land ok(mn) \land m = n(s,n) \land ok(cn) \land norm(es(s,n(c,cn))) \} \] must be characterized appropriately. Thus, we obtain the following table entry: <table> <thead> <tr> <th>From</th> <th>Operator</th> <th>Measure</th> <th>Report</th> <th>Control</th> <th>To</th> </tr> </thead> <tbody> <tr> <td>normal</td> <td>o \ where \ o \neq \ stop</td> <td>m \ where \ \exists s \ mn \ cs \ c. norm(s) \land ok(mn) \land m = n(s,mn) \land ok(cn) \land norm(es(s,n(c,cn)))</td> <td>normal</td> <td>c \ where \ \exists cn. ok(cn) \land norm(es(s,n(c,cn)))</td> <td>normal</td> </tr> </tbody> </table> where \ s \in \ S \land norm(s) \) Note that we used an entry parameterized by the environment state \ s \ because the control output \ c \ does depend on the state \ s \ in form of the received measurement. In the above cases, the state environment state \ s \ could be defined locally, since the control output did not depend on \ s \ but was chosen arbitrarily. 5.4 Global Properties Besides requirements that basically consist of simple and complex state transitions there is a third class which cannot be formulated in such a table framework. This is due to the fact that these requirements do not describe properties of the steam boiler controller that can be formalized using one computation step. One of these properties is the description of the initialization phase: Requirement 8: During the initialization phase the controller issues a sequence of manipulating values that will eventually lead the physical system into a normal state in case there is no noise. It is remarkable that - again - this requirement can be stated without mentioning any possible realization of this sequence of initializing sequences. It can even be phrased in such an abstract way that it does not only apply to the steam boiler example, but to any similar control task. Here, too, the formal phrasing is quite straightforward: \[ ok^* (mns) \land ok^* (cns) \land nostop^* (hsin) \Rightarrow \exists m n c hsout. \] \[ (c, hsout) = b(mn(mns, m), hsin) \land \] \[ m = e(cn(cns, c)) \land \] \[ ok(nth(n,c)) \] Here we made use of some auxiliary functions: - The Boolean function \( ok^*: (M Noise)^\omega \rightarrow T \) checks whether the sequence of noise values added will leave the signals undisturbed. This function is defined to be \[ ok^* (mn) = \forall n.ok(nth(n,mn)) \] - The Boolean function \( nostop^*: O^\omega \rightarrow T \) checks whether the operator command sequence does not contain any stop command. \[ nostop^* (o) = \forall n.noth(n,o) \neq stop \] Both definitions make use of the function \( nth : \mathcal{F} \times A^\omega \rightarrow A \), selecting the n-th element of a stream if such an element exists. For a formal definition of \( nth \) see [Reg94]. This property, in contrast to the above introduced requirements, is a pure liveness property. Unlike the other properties, which are safety properties, it cannot be expressed by properties of the state transitions in a stepwise computation. Since these global requirements are not stated in the tabular notation as given before, we have to define how these two forms are formally combined. According to the definition of the formalization of table entries as given in section 0 each entry is translated into a predicate with the function co modeling the controller as its free variable. Since the above formalization of the global requirement is of the same form, the combination is straightforward: it just has to be combined by conjunction with the predicates obtained by the translations of the table entries. 6 Refinement of Data and States As pointed out in [Bro94] or [Bro93a], one of the major advantages of the model of stream processing functions is its modular refinement concept. It offers several notions of refinement like: - **Behavioral Refinement**: Refining the behavior of a system by adding more properties to its specification, restricting behavior in cases that were unspecified before. - **Glass Box Refinement**: Refining a system by breaking it up into components of communicating components (structural refinement) or by giving a concrete state transition system (state-based refinement). - **Interface Refinement**: Refining the interface that consists of the input and output channels of a component and the message sets communicated on them, by breaking up messages that have been atomic before. In the following we give a short introduction to the basic idea of refinement in the context of stream processing functions. Then, we demonstrate how the refinement of data and states is carried out within the framework of stream processing functions. Finally, we will apply these concepts to the above introduced tables and use the steam boiler controller as an example to demonstrate the techniques. 6.1 General Refinement Concepts The central purpose of refinement is the adding of implementation decisions and the modeling of additional system details. In the steam boiler approach two forms of refinement might be applied: - **Data Refinement**: This refinement technique describes the successive elaboration of details in the process of system modeling. In the steam boiler context, we can decide that the sensory input of the controller consists of measurements of the water level, water and steam throughput or the pump state. A further refinement might be to split up the pump into three pumps, requiring to split up the pump control and the pump measurement system into three streams of values. - **State/Transition Refinement**: This form of refinement describes the successive elaboration of behavioral details and thus the elimination of under-specification. In the steam boiler context, we might consider only behavior in case of undisturbed control and measurement signals, leading to simple states like *wait*, *init*, *normal*, and *emergency*. In a second step we might then add requirements for slightly disturbed signals introducing a *degraded* mode. Since refinement, in general, is a formal concept for specification manipulation, the basic concept behind every refinement notion should be as simple as possible to allow for sufficiently manageable proofs. Therefore we do not only introduce and demonstrate the above used refinement concepts, but also rephrase them in the setting of tabular specifications. Since, as mentioned above, the tabular notation is somewhat limited in its expressiveness, not all properties can be described that way. We therefore give a short outline about the applicability of this technique. 6.2 Data and State Refinement In the context of the steam boiler we will demonstrate the refinement technique using both data and state refinement. The corresponding setting will be the specification of the behavior in a case where the measurement units fail. Again, we see here our task in the specification of the requirements and not in the description of an implementation strategy. 6.2.1 Refinement of Messages Since we now want to talk about the potential failures of the water level measurement device we explicitly have to model this part of the sensory input to the controller. Thus, the set of input messages to the controller will be modeled by the set \[ M = W \times M' \] obtained by the Cartesian product of W and M', where - \( W \) is the set of possible values of the water measurement signal, and - \( M' \) is the set of possible values of the remaining sensory signals, again with further details ignored. Of course, also the corresponding noise has to be adapted defining \[ M\text{ Noise} = W\text{ Noise} \times M'\text{ Noise} \] Together with the refinement of the message types we have to give a refinement of the appropriate functions operating on these messages. Here, we just informally introduce these definitions which are necessary for the understanding of the following requirements - The boolean function \( \text{noisy}: M'\text{ Noise} \rightarrow [0,1] \) checks whether the noise added to the measured sensory data is significant. - The boolean function \( \text{ok}: W\text{ Noise} \rightarrow [0,1] \) checks whether no noise is added to the sensory data recorded by the water level measurement unit. - The boolean function \( \text{ok}: M'\text{ Noise} \rightarrow [0,1] \) checks whether no noise is added to the sensory data recorded by the measurement units other than the water level unit. Furthermore, to have a reasonable definition of absence of noise we have to define \[ \text{ok}((wn, mn')) = \text{ok}(wn) \land \text{ok}(mn') \] for all corresponding values of water level noise \( wn \) and all values of noise \( mn' \) of the remaining units. 6.2.2 Refinement of States After refining the messages, we are now ready of expressing the intended refinement of the controller’s behavior. The requirements specification introduced so far does not deal with the case of device failure. It will therefore be extended to describe a legal behavior in case the water level measurement device and control devices are unbroken. The behavioral restriction is expressed in the following four requirements: Requirement 9: If the measurement signal is distorted by significant noise, but the water level measurement and the controlling signal are undisturbed, if there is no ‘stop’-signal issued, and there is a control signal which keeps the system in the limits under these circumstances, then a controller in normal mode will produce such a signal, report the ‘degraded’ mode, and switch to ‘degraded’ mode. Requirement 10: If the measurement signal is distorted by significant noise, but the water level measurement and the controlling signal are undisturbed, if there is no ‘stop’-signal issued, and there is a control signal which keeps the system in the limits under these circumstances, then a controller in degraded mode will produce such a signal, report the ‘degraded’ mode, and remain in ‘degraded mode’. Requirement 11: If any possible noiseless control signal will take the system out of the limits, the controller in ‘degraded’ state must produce an arbitrary control signal as well as an ‘emergency’ report and then switch to ‘emergency’ mode. Requirement 12: If the control signal remains undisturbed, the system is in the limits, the water measurement devices is unbroken, and the controller reports ‘degraded’ state, the system is kept in the limits by the control signal. The tabular descriptions of Requirement 9, Requirement 10, Requirement 11, and Requirement 12 correspond to the tabular description of <table> <thead> <tr> <th>State</th> <th>Wait</th> <th>Init</th> <th>Normal</th> </tr> </thead> <tbody> <tr> <td>In normal</td> <td>start</td> <td></td> <td></td> </tr> <tr> <td>Out of limits</td> <td>stop</td> <td></td> <td></td> </tr> <tr> <td>Water ok</td> <td>noise</td> <td></td> <td></td> </tr> <tr> <td>Emergency</td> <td>Restart</td> <td></td> <td></td> </tr> <tr> <td>Out of limits</td> <td>stop</td> <td></td> <td></td> </tr> <tr> <td>Stop</td> <td>stop</td> <td></td> <td></td> </tr> </tbody> </table> Figure 6: Refined States 6.3 Refining Tables As shown in 6.2, refining a state based specification of a component by refining its messages or its conceptual states is quite straight-forward, but somewhat technical. Nevertheless, using these techniques in a restricted context, like tables, turns them into a much simpler approach. The addition of some new input messages gives a more detailed view of a component; so the specification must enclose the reactions of the component to these new input messages and the table must be expanded with these new cases. The reaction of the component to the new input messages will be described with possibly new output messages as well as new states in the “to”-column. Because the table specification should always give a complete specification of the behavior according to the actual abstraction degree we must complete the table specification with the new actual states in the “from”-column and their postulated behavior. In the following table we show these extensions of the steam boiler specifications. The reader will see that the elimination of under-specifications in the development of a system description with different abstraction degrees can be written as a simple extension of the tables with the new states. Therefore each refinement step gives a more complete version of the table. The underlying semantical framework stays the same as we have described in the previous chapters. <table> <thead> <tr> <th>From</th> <th>Operator</th> <th>Measure</th> <th>Report</th> <th>Control</th> <th>To</th> </tr> </thead> <tbody> <tr> <td>normal</td> <td>o where o ≠ stop</td> <td>m where (\exists) wn mn´ c cn. (\text{ok}(\text{wn}) \land \text{ok}(\text{cn}) \land \text{noisy}(\text{mn}´) \land m = n(s,(\text{wn},\text{mn}´) \land \text{norm}(es(s,\text{cn}(\text{c},\text{cn})))))</td> <td>degraded</td> <td>c where (\exists) cn. (\text{ok}(\text{cn}) \land \text{norm}(es(s,\text{cn}(\text{c},\text{cn})))))</td> <td>degraded</td> </tr> <tr> <td>degraded</td> <td>o where o ≠ stop</td> <td>m where (\exists) wn mn´ c cn. (\text{ok}(\text{wn}) \land \text{ok}(\text{cn}) \land \text{noisy}(\text{mn}´) \land m = n(s,(\text{wn},\text{mn}´) \land \text{norm}(es(s,\text{cn}(\text{c},\text{cn})))))</td> <td>degraded</td> <td>c where (\exists) cn. (\text{ok}(\text{cn}) \land \text{norm}(es(s,\text{cn}(\text{c},\text{cn})))))</td> <td>degraded</td> </tr> <tr> <td>degraded</td> <td>O</td> <td>m where (\exists) wn mn´ cn. (\text{ok}(\text{wn}) \land \text{ok}(\text{cn}) \land \text{noisy}(\text{mn}´) \land m = n(s,(\text{wn},\text{mn}´) \land \forall c.\neg \text{norm}(es(s,\text{cn}(\text{c},\text{cn})))))</td> <td>degraded</td> <td>C</td> <td>degraded</td> </tr> <tr> <td>degraded</td> <td>stop</td> <td>M</td> <td>emergency</td> <td>C</td> <td>emergency</td> </tr> </tbody> </table> where \(s \in S \land \text{norm}(s)\) 7 Conclusion and Outlook In the presented paper we gave an outline on how different aspects of the steam boiler example can dealt with main concepts of the FOCUS method. The treatment of the steam boiler example as given above is by no means complete. It rather concentrates on the modeling of the control task in FOCUS, on the representation of the specification by tables and on the stepwise refinement of the specification than treating all the properties in detail, thus modeling only some facets of the steam boiler. The aim of the article is not to give a complete specification of the steam boiler controller with all its states and features, as it is done in [ML96] or [LL96]. Instead, we tried to show how FOCUS offers a methodological approach for the development of an implementation of a control task beginning at a very high level of description and ending at the level of abstract implementation. The case study has shown several promising aspects. For a full evaluation of the usefulness, however, the steam boiler example has to be developed to a more detailed degree, and a comparison to the other approaches has to be drawn. Many aspects are not treated at all. Two of the most important aspects not treated here in sufficient detail are: the development of the failure model (which means mainly a design of a sophisticated state space), and the methodical development of state-transition systems using table-based techniques. See, for instance, [Bro98] for a more elaborated treatment of tables. Additional contributions of FOCUS supporting the development of applications in the control theory domain are, for instance, ANDL (Agent and Network Description Language see [SS95]), a formal syntax for the FOCUS specification language, a formal semantics based on HOLCF (see [Reg94]), the extension of Isabelle’s (see [Pau94]). HOL to LCF, as well as a translation of ANDL to HOLCF. Furthermore, a tool prototype for a development on graphical and state-based description techniques, called AutoFOCUS (see, for example, [HSS96], [HSE97], or [HMS98]), is implemented. Therefore, it might be interesting to rephrase the steam boiler case study in this context and to carry out several refinement steps using computer aided verification. As a whole the major contribution of this paper lies in the control theoretical approach, which made the formalization of several overall aims of the controller surprisingly simple, sufficiently abstract from any possible implementation, and alike to the textual phrasing of the requirements. Using further case studies it should be investigated whether this scheme can be generally applied to problems in the control theoretical domain. Acknowledgement It is a pleasure to thank Ursula Hinkel and Max Breitling for their helpful comments on earlier versions of this paper. Literature
{"Source-Url": "http://wwwbroy.informatik.tu-muenchen.de/publ/papers/BRSS97.pdf", "len_cl100k_base": 13200, "olmocr-version": "0.1.53", "pdf-total-pages": 26, "total-fallback-pages": 0, "total-input-tokens": 56499, "total-output-tokens": 15804, "length": "2e13", "weborganizer": {"__label__adult": 0.0003943443298339844, "__label__art_design": 0.0011072158813476562, "__label__crime_law": 0.0004351139068603515, "__label__education_jobs": 0.00226593017578125, "__label__entertainment": 0.00011092424392700197, "__label__fashion_beauty": 0.0002086162567138672, "__label__finance_business": 0.0006995201110839844, "__label__food_dining": 0.0006561279296875, "__label__games": 0.0008549690246582031, "__label__hardware": 0.0026531219482421875, "__label__health": 0.0007867813110351562, "__label__history": 0.0005559921264648438, "__label__home_hobbies": 0.00038552284240722656, "__label__industrial": 0.004547119140625, "__label__literature": 0.0005807876586914062, "__label__politics": 0.0003407001495361328, "__label__religion": 0.0006785392761230469, "__label__science_tech": 0.446533203125, "__label__social_life": 0.00013399124145507812, "__label__software": 0.01187896728515625, "__label__software_dev": 0.52197265625, "__label__sports_fitness": 0.00029969215393066406, "__label__transportation": 0.0014410018920898438, "__label__travel": 0.00024628639221191406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 63216, 0.01638]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 63216, 0.62994]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 63216, 0.87256]], "google_gemma-3-12b-it_contains_pii": [[0, 2935, false], [2935, 6394, null], [6394, 8618, null], [8618, 10128, null], [10128, 12058, null], [12058, 14411, null], [14411, 16634, null], [16634, 19099, null], [19099, 20727, null], [20727, 23502, null], [23502, 26305, null], [26305, 28666, null], [28666, 31085, null], [31085, 33638, null], [33638, 35468, null], [35468, 37599, null], [37599, 40198, null], [40198, 42217, null], [42217, 44854, null], [44854, 47821, null], [47821, 50385, null], [50385, 52892, null], [52892, 55982, null], [55982, 58984, null], [58984, 62229, null], [62229, 63216, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2935, true], [2935, 6394, null], [6394, 8618, null], [8618, 10128, null], [10128, 12058, null], [12058, 14411, null], [14411, 16634, null], [16634, 19099, null], [19099, 20727, null], [20727, 23502, null], [23502, 26305, null], [26305, 28666, null], [28666, 31085, null], [31085, 33638, null], [33638, 35468, null], [35468, 37599, null], [37599, 40198, null], [40198, 42217, null], [42217, 44854, null], [44854, 47821, null], [47821, 50385, null], [50385, 52892, null], [52892, 55982, null], [55982, 58984, null], [58984, 62229, null], [62229, 63216, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 63216, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 63216, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 63216, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 63216, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 63216, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 63216, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 63216, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 63216, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 63216, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 63216, null]], "pdf_page_numbers": [[0, 2935, 1], [2935, 6394, 2], [6394, 8618, 3], [8618, 10128, 4], [10128, 12058, 5], [12058, 14411, 6], [14411, 16634, 7], [16634, 19099, 8], [19099, 20727, 9], [20727, 23502, 10], [23502, 26305, 11], [26305, 28666, 12], [28666, 31085, 13], [31085, 33638, 14], [33638, 35468, 15], [35468, 37599, 16], [37599, 40198, 17], [40198, 42217, 18], [42217, 44854, 19], [44854, 47821, 20], [47821, 50385, 21], [50385, 52892, 22], [52892, 55982, 23], [55982, 58984, 24], [58984, 62229, 25], [62229, 63216, 26]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 63216, 0.09158]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
2c6507b7d473bfaf53ec7e9a9cbfb2a6f0c1a892
Knowledge Representation for Information Integration Marie-Christine Rousset, Chantal Reynaud University of Paris Sud - CNRS (L.R.I) & INRIA (Futurs) L.R.I, Building 490, 91405, Orsay Cedex, France Abstract An information integration system provides a uniform query interface to a collection of distributed and heterogeneous information sources, giving users or other agents the illusion that they interrogate a centralized and homogeneous information system. In this paper, we focus on the use of knowledge representation techniques for building mediators for information integration. A mediator is based on the specification of a single mediated schema describing a domain of interest, and on a set of source descriptions expressing how the content of each source available to the system is related to the domain of interest. These source descriptions, also called mappings because they model the correspondence between the mediated schema and the schemas of the data sources, play a central role in the query answering process. We present two recent information integration systems, namely Picsel and Xyleme, which are illustrative of two radically different choices concerning the expressivity of the mediated schema. Key words: mediator, mediated schema, rewriting queries using views, description logics, datalog rules, labelled trees, query trees, mappings 1 Introduction The emergence of the World-Wide Web has made available a multitude of autonomous data sources which can as a whole satisfy most of users information needs. However, it remains a tedious and long task for users to find the Email addresses: mcr@lri.fr (Marie-Christine Rousset,), cr@lri.fr (Chantal Reynaud). Preprint submitted to Elsevier Science 9 December 2002 data sources that are relevant to their request, to interact with each of those sources in order to extract the useful pieces of information which then have to be combined for building the expected answer to the initial request. Information integration systems are mediation systems between users and multiple data sources which can be syntactically or semantically heterogeneous while being related to a same domain (e.g., tourism, culture). An information integration system provides a uniform interface for querying collections of pre-existing data sources that were created independently. They are based on a single mediated schema in terms of which users pose queries, and the data sources to integrate are described. The source descriptions specify semantic relationships between the contents of data sources and the mediated schema. They are exploited by the query processor of the information integration system which must reformulate the original query into queries against the source schemas. Information integration systems must deal with large and constantly changing collections of data sources. This requires powerful languages and flexible mechanisms for describing and handling data sources which may have overlapping or contradictory contents, semantic mismatches, limited capabilities, etc ... In this paper, we discuss the advantages and the challenges of using rich knowledge representation formalisms for modeling the semantic relationships between source schemas through a mediated schema. We outline the impact of the choice of the knowledge representation formalism on the query reformulation problem, which is the core algorithmic problem for answering queries in an information integration system. Clearly, as the languages for describing data sources, the mediated schema, or the users’ queries become more expressive, the query reformulation problem becomes harder. The key challenge is then to identify formalisms offering a reasonable tradeoff between expressive power and good computational properties for the accompanying reformulation algorithm. In Section 2, after a survey of most of the existing information integration systems, we focus on two recent systems, PICSEL[18] and Xyleme[33,32], which are illustrative of two radically different tradeoffs between expressive power and the computational complexity of the accompanying reformulation algorithm. Section 3 and 4 summarize the approach underlying each of those two systems. Finally, in Section 5, we outline the central role of knowledge representation techniques that for making the promising vision of the Semantic Web a reality. 2 Overview of the mediator approach The general architecture of a mediator-based information integration system is given in Figure 1. User’s query: trip (Paris, London, Price, Date) ![Architecture diagram](image) **Fig. 1. Architecture of a mediator-based information integration agent** The existing mediator-based information integration systems can be distinguished according to: - the type of mappings between the mediated schema and the schemas of the sources (Global As Views versus Local As Views), - the languages used for modeling the mediated schema and the source descriptions, - the expressivity of the mediated schema. **2.1 Global As Views versus Local As Views** Information integration systems can be related to two main approaches for modelling inter-schemas correspondence: *Global As Views (GAV)* and *Local As Views (LAV)*. The GAV approach has been the first one to be proposed and comes from the Federated Databases world. The mediated schema is defined in function of the schemas of the sources to integrate, i.e., each relation of the mediated schema is defined as a view on the relations of the sources schemas. The advantage of this approach is the simplicity of query reformulation which simply consists of replacing each atom of the query by its definition in terms of the relations of the sources schemas. Its drawback is its lack of flexibility with respect to the addition or deletion of sources to the mediator: adding (or deleting) a source to the mediator may affect the definitions of all the relations of the mediated schema. The LAV approach is dual and has opposite advantages and drawbacks. It consists of describing the contents of the sources in function of the mediated schema. In such an approach, adding a new source is quite straightforward because each source is defined independently of each other. It simply requires to add some formulas to model the content of the new source as queries over the mediated schema. The price to pay for this flexibility is the difficulty of the query answering processing. Since both the users queries and the views describing the sources contents are expressed in terms of the mediated schema, the reformulation of the users queries in terms of the source relations cannot be done as a simple query unfolding as for the GAV approach. This requires a more complex process of rewriting queries using views (see [19] and [8] for more details on the problem of answering queries using extensions of views). 2.2 Relational versus object-oriented mediated schema The most representative information integration systems of the relational approach are: Razor ([15]), Internet Softbot ([14]), Informaster ([16]) et Information Manifold ([25]). They all follow a LAV approach. The Razor and Internet Softbot systems use DATALOG (without recursion) for modeling the mediated schema, the views describing the sources contents and the users queries. Informaster and Information Manifold are based on extensions of DATALOG. Informaster exploits integrity constraints in addition of DATALOG rules. Information Manifold extends DATALOG by allowing that some predicates used in the rules are concepts defined by using description logics constructors. This hybrid formalism is in fact a precursor of the CARIN language considered in this paper. The HERMES ([30]) system is a system of federated databases that can be seen as a mediator following a GAV approach and based on a Prolog-like query language with annotations for handling uncertainty and time. The most representative information integration systems of the object-oriented approach are: TSIMMIS ([28]), SIMS ([4,3]) OBSERVER ([27]) and MOMIS ([5]). TSIMMIS is based on the object-oriented language OEM for describing the mediated schema and the views, and on the OEM-QL query language. It follows a GAV approach. The SIMS and OBSERVER systems use a description logic for modeling the mediated schema, the views and the queries. They follow a LAV approach since the content of the source is described in function of the concepts described in the mediated schema. SIMS uses LOOM ([26]) while OBSERVER is based on CLASSIC ([7]). In those two systems, the problem of rewriting queries using views is handled as a planning problem and the completeness of the rewriting algorithms is not addressed. The MOMIS ([5]) system is based on the use of a very expressive description logic (ODL-B3) for describing the schemas of the sources to integrate. It follows a GAV approach since the mediated schema is inferred from the schemas of the sources. 2.3 Expressivity of the mediated schema Orthogonally to the LAV versus GAV and relational versus object-oriented distinctions, another criteria for distinguishing the information integration systems is the expressive power chosen for modeling the mediated schema. In this paper, we summarize two recent information integration systems, namely PICSEL and Xyleme, which are illustrative of two radically different choices concerning the expressivity of the mediated schema. In PICSEL[18], it has been chosen to offer a formalism combining the expressive power of rules and classes for designing a rich mediated schema, thus enabling a fine-grained description of the contents of the sources. Our aim was to build information integration agents related to application domains for which there exists many information sources containing closely related data. In such a setting, it is of primary importance to model the fine-grained differences between contents of sources if we want to be able to answer precise queries in an efficient way. PICSEL has been used for building a mediator in the tourism domain in collaboration with France Telecom R&D and the web travel agent Degri tour 1. This travel agent makes available on-line three databases that contain different types of touristic products (flights, tours, stays in different places), each of them having its own specificities. For example, the BonjourFrance database offers a large variety of touristic products but all of them are located in France. The so-called Degri tour database offers flights, stays and tours for a lot of destinations all over the world. Its specificity however is that all its offers correspond to a departure date which is within the next two weeks. As a counterpart, the corresponding prices are specially interesting. The Reductour database provides rather similar products but with a less strong constraint on the departure date: it just has to be within the next eight months. Other differences exist between the contents of those three databases. For instance, we might know that BonjourFrance can provide rooms in Bed&BBreakfast in 1 see http://www.degrifour.fr/ addition to hotel rooms, while the only housing places that are proposed in the two other sources are hotels, located exclusively out of France for Degritour, and located exclusively in Europe for Reductour. In Xyleme [32,33,1], the choice of a simple tree structure for mediated schemas has been guided by the goal of providing a very wide-area integration of XML sources that could scale up to the Web. The system architecture and the design choices have been motivated by “web search engine”-like performance requirements, i.e. supporting many simultaneous queries over a Web-scale XML repository. Xyleme is based on a simple data model with data trees and tree types, and a simple query language based on tree queries with boolean conditions. The main components of the data model are a mediated schema modeled by an abstract tree type, as a view of a set of tree types associated with actual data trees, called concrete tree types, and a mapping expressing the connection between the mediated schema and the concrete tree types. The simplicity of the mapping relation (correspondences between tree paths) eases automatic mapping generation and distributed storage. The query language is intended to enable end-users to express simple Query-by-Example tree queries over the mediated schema. In section 3, we describe the way the expressive power of the CARIN [21] language is exploited in the PICSEL information integration system, while maintaining the decidability of query rewriting using views and the tractability of query answering. In section 4, after describing the tree-based data model of Xyleme, we present a method for semi-automatically generating the mapping relation. For setting up semantic integration in Xyleme, the main difficulty comes from the very large number of data sources handled by Xyleme. As a consequence, the number of concrete data trees that have to be mapped to the abstract tree type makes impossible that the mapping relation is manually defined by some database administrator. We have therefore studied how to generate the mapping relation as automatically as possible, by combining syntactic, semantic and structural criteria. A prototype has been implemented and evaluated in the cultural domain 3 Overview of PICSEL In PICSEL, CARIN is used to represent both the mediated schema modeling a given domain of application, and the contents of information sources that are available and relevant to that domain. 3.1 Syntax and semantics of CARIN A CARIN knowledge base (KB) contains two components: a set $R$ of rules, and a set $T$ of Description Logics statements. Description logics statements are definition or inclusion statements about concepts and roles in the domain. Concepts and roles are unary and binary relations that can also appear in the antecedents of the rules. Relations that do not appear in the description logics statements are called ordinary relations. Ordinary relations can be of any arity. 3.1.1 Description Logics component in CARIN: The DL component of a CARIN knowledge base in PICSEL contains concept definitions and some kinds of concept inclusions, using the $\mathcal{ALN}$ DL. $\mathcal{ALN}$ contains the DL constructors of conjunction ($C_1 \cap C_2$), value restriction ($\forall R.C$), number restrictions ($\geq n R, \leq n R$), and negation ($\neg A$) restricted to basic concepts only. - Concept definitions are of the form $CN := ConceptExpression$, where $CN$ is a concept name and ConceptExpression is a concept expression. We assume that a concept name appears in the left hand side of at most one concept definition. Atomic concepts are those which do not appear in any left hand side of a definition. A concept name $CN$ depends on a concept name $CN'$ if $CN'$ appears in the definition of $CN$. A set of concept definitions is said acyclic if there is no cycle in the concept names dependency relation. In the setting of PICSEL, we consider only acyclic concept definitions. We can unfold an acyclic set of definitions by iteratively substituting every concept name with its definition. - The concept inclusions that are allowed in the PICSEL setting are of the form: - $A \sqsubseteq ConceptExpression$, where $A$ is a atomic concept, - or $A_1 \cap A_2 \sqsubseteq \bot$, where $A_1$ and $A_2$ are atomic concepts. 3.1.2 Rule component in CARIN: The rule component $R$ of a CARIN knowledge base contains a set of rules that are logical sentences of the form: $$\forall \bar{X}[p_1(\bar{X}_1) \land \ldots \land p_n(\bar{X}_n) \Rightarrow q(\bar{Y})]$$ where $\bar{X}_1, \ldots, \bar{X}_n, \bar{Y}$ are tuples of variables (included in $\bar{X}$) or constants. We require that the rules are safe, i.e., a variable that appears in $\bar{Y}$ must also appear in $\bar{X} \cup \ldots \cup \bar{X}_n$. As a shortcut, in the following, the variable quantifi- cation will be omitted. The relations \( p_1, \ldots, p_n \) may be either concept names or expressions, role names, or ordinary relations that do not appear in \( T \). The relation \( q \) must be an ordinary relation. The base relations are those which do not appear in any consequent of rules. In particular, any concept or role appearing in the rules are base relations. We call a base atom an atom \( p(\bar{X}) \) where \( p \) is a base relation. We call concept-atom an atom \( p(X) \) where \( p \) is a concept name or expression, and role-atom an atom \( r(X, Y) \) where \( r \) is a role name. An ordinary relation \( p \) is said to depend on an ordinary relation \( q \) if \( q \) appears in the antecedent of a Horn rule whose consequent is \( p \). A set of rules is said to be recursive if there is a cycle in the dependency relation among ordinary relations. In the setting of PicSEL, we consider non recursive rules. Since the rules are safe, without loss of generality, we can assume that in every rule, we have the disequality \( X \neq Y \) for every pair of distinct variables appearing in the rule. For clarity, we omit these atoms in our examples and algorithms. In addition, we allow constraints of the form: \[ p_1(\bar{X}_1) \land \ldots \land p_n(\bar{X}_n) \Rightarrow \bot. \] 3.1.3 Semantics of CARIN KBs: The semantics of CARIN KBs is the standard model-based semantics of first-order logic. An interpretation \( I \) contains a non-empty domain \( O^I \). It assigns to every constant \( a \) an object \( \alpha^I(a) \in O^I \), and a relation of arity \( n \) over the domain \( O^I \) to every relation of arity \( n \). In particular, it assigns a unary relation \( C^I \) to every concept in \( T \), and a binary relation \( R^I \) over \( O^I \times O^I \) to every role \( R \) in \( T \). The extensions of concept and role descriptions are given by the following equations: (\( \#S \) denotes the cardinality of a set \( S \)): \[ (C \cap D)^I = C^I \cap D^I, \\ (-A)^I = O^I \setminus A^I, \\ (\forall R.C)^I = \{d \in O^I \mid \forall e : (d, e) \in R^I \Rightarrow e \in C^I\} \\ (\geq n R)^I = \{d \in O^I \mid \#\{e \mid (d, e) \in R^I\} \geq n\} \\ (\leq n R)^I = \{d \in O^I \mid \#\{e \mid (d, e) \in R^I\} \leq n\} \] An interpretation \( I \) is a model of a knowledge base \((T, R)\) if it is a model of each of its components \( T \) and \( R \). An interpretation \( I \) is a model of \( T \) if \( A^I \subseteq D^I \) for every inclusion \( A \subseteq D \) in \( T \), \( CN^I = D^I \) for every concept definition \( CN := D \). If \( CE \) and \( DE \) are two concept expressions, we say that CE is subsumed by DE (modulo T), denoted \( CE \preceq DE \) (\( CE \preceq_T DE \)), if \( CE^I \subseteq DE^I \) in every interpretation \( I \) (model of \( T \)). A concept expression \( CE \) is satisfiable (modulo \( T \)) iff there exists an interpretation \( I \) (model of \( T \)) such that \( CE^I \) is not empty. An interpretation \( I \) is a model of a rule \( r : p_1(\bar{X}_1) \land \ldots \land p_n(\bar{X}_n) \Rightarrow q(\bar{Y}) \) if, whenever \( \alpha \) is a mapping from the variables \(^2\) of \( r \) to the domain \( O^I \), such that \( \alpha(\bar{X}_i) \in p_i^I \) for every atom of the antecedent of \( r \), then \( \alpha(\bar{Y}) \in q^I \). An interpretation \( I \) is a model of a constraint \( c : p_1(\bar{X}_1) \land \ldots \land p_n(\bar{X}_n) \Rightarrow \bot \) if there does not exist a mapping \( \alpha \) from the variables of \( c \) to the domain \( O^I \) such that \( \alpha(\bar{X}_i) \in p_i^I \) for every atom of the antecedent of \( c \). 3.2 Modelling the mediated schema in PicSEL Given a basic vocabulary denoting names of base relations that are meaningful for the application domain (e.g., tourism), CARIN is used for defining new relations that are significant for that domain and which can be defined over the base relations. In the setting of CARIN, there are two ways of defining complex relations: by rules, or by concept expressions. It is illustrated by the following example. **Example 1** Let us suppose that our basic vocabulary contains atomic concepts such as \( HousingPlace, Breakfast, CollectiveBuilding, PrivateBuilding \), which respectively denote the set of housing places and varied sets of services or buildings, and roles such as \( AssRoom, AssMeal \) and \( AssBuilding \), which denote binary relations between housing places and their associated buildings, room and meal services. We can define the two new concepts \( Hotel \) and \( Bed&Breakfast \) by the following DL definitions: \[ Hotel := HousingPlace \sqcap (\geq 5 AssRoom) \sqcap (\forall AssBuilding.CollectiveBuilding) \] \[ Bed&Breakfast := HousingPlace \sqcap (\geq 1 AssRoom) \sqcap (\geq 1 AssMeal) \\ \sqcap (\forall AssMeal.Breakfast) \sqcap (\forall AssBuilding.PrivateBuilding) \] Rules can be used to define new n-ary relations. For instance, the following rule defines the notion of flights combined with stays as a 4-ary relation \( FlightStay \). A stay combined with a flight is characterized by a departure city (denoted by the first variable \( Dcity \) in the consequent of the rule), an arrival city (denoted by the variable \( Acity \)), a departure date \( (Ddate) \), a return date \( (Rdate) \). The possible combinations of a flight to and back a given destination --- \(^2\) Distinct variables are mapped to distinct elements with a stay at that place obey some constraints that are expressed by the conditions in the antecedent of the rule. \[ \text{Stay}(S) \land \text{Flight}(V) \land \text{Assoc}(S, H) \land \text{Located}(H, \text{Acity}) \\ \land \text{ArrivalCity}(V, \text{Acity}) \land \text{DepartureCity}(V, \text{Dcity}) \land \text{DepartureDate}(V, \text{Ddate}) \\ \land \text{ReturnDate}(V, \text{Rdate}) \land \text{BeginningDate}(S, \text{Ddate}) \land \text{EndDate}(S, \text{Rdate}) \\ \Rightarrow \text{FlightStay}(\text{Dcity}, \text{Acity}, \text{Ddate}, \text{Rdate}) \] 3.3 Modelling the contents of the information sources in PICSEL Our approach for describing the information sources has been guided by the necessity of trading off expressive power against decidability of query answering. More precisely, each information source \( S \) is characterized by a set of source relations \( \mathcal{V}_S \) (also called views), and described by a CARIN knowledge base which contains: 1. a set \( \mathcal{I}_S \) of rules \( v(\bar{X}) \Rightarrow p(\bar{X}) \) that indicates which kind of data can be found in the source \( S \). The \( p \)'s are domain relations and there are as many source relations \( v \)'s in \( \mathcal{V}_S \) (and as many implications in \( \mathcal{I}_S \)) as domain relations whose instances can be found in the source \( S \), 2. a set \( \mathcal{C}_S \) of constraints on the instances of the source relations. We allow two types of constraints. Terminological constraints are of the form \( v \subseteq C \), where \( C \) is a concept expression. Integrity constraints are of the form \( l_1(\bar{X}_1) \land \ldots \land l_n(\bar{X}_n) \Rightarrow \bot \) where the \( l_i \)'s are source relations or negation of source relations, such that there is at most one negation in each constraint. A source atom (also called view atom) is an atom of the form \( v(\bar{X}) \) where \( v \) is a source relation. We encapsulate the terminological constraints within the definition of views associated with such constraints. **Definition 1 (View definition)** Let \( v \) be a view in \( \mathcal{V} \) appearing in the description \( \mathcal{I}_S \cup \mathcal{C}_S \) of a source \( S \), and such that \( v(X) \Rightarrow p(X) \in \mathcal{I}_S \). The definition of the view \( v \), denoted \( \text{def}(v) \), is: - \( \text{def}(v) = p \cap C \) if \( v \subseteq C \in \mathcal{C}_S \), - \( \text{def}(v) = p \) if \( v \) is not associated to any terminological constraint. As an example, we can have the following (partial, for this illustration) descriptions of the three information sources that we have previously mentioned (i.e., BonjourFrance, Degriftour and Reductour). **Example 2** The rules in the description of the three sources say that we can find instances of housing places and flights in all of them (together with instances of associated properties like their location, their departure cities and dates ...). The constraints contained in each description enable distinguishing between them: for instance, the housing places and flights that can be found in *Bonjour France* are restricted to be located in France; the housing places that can be found in *Reductour* are necessarily hotels. Some constraints serve to express that instances of some binary relations that can be found in a given source are exclusively related to some unary relations that can be found in the same source: for instance, the constraint \(v_{BF}^2(X, Y) \land \neg v_{BF}^1(X) \Rightarrow \bot\) in \(Descr(Bonjour\ France)\) expresses that the locations that can be found in the source *Bonjour France* (denoted by the source relation \(v_{BF}^2\) and the implication \(v_{BF}^2(X, Y) \Rightarrow Located(X, Y)\)) are only locations that are related to the housing places that can be found in the same source (denoted by the source relation \(v_{BF}^1\) and the implication \(v_{BF}^1(X) \Rightarrow HousingPlace(X)\)). <table> <thead> <tr> <th>(Descr(Bonjour\ France)) : (v_{BF}^1, \ldots, v_{BF}^n)</th> </tr> </thead> <tbody> <tr> <td>mappings: (\mathcal{I}_{Bonjour\ France})</td> </tr> <tr> <td>(v_{BF}^1(X) \Rightarrow HousingPlace(X))</td> </tr> <tr> <td>(v_{BF}^2(X, Y) \Rightarrow Located(X, Y))</td> </tr> <tr> <td>(v_{BF}^3(X) \Rightarrow Flight(X))</td> </tr> <tr> <td>(v_{BF}^4(X, Y) \Rightarrow Arrival\City(X, Y))</td> </tr> <tr> <td>(\ldots)</td> </tr> </tbody> </table> <table> <thead> <tr> <th>(Descr(Dege\ rif\ tour)) : (v_{D}^1, \ldots, v_{D}^n)</th> </tr> </thead> <tbody> <tr> <td>mappings: (\mathcal{I}_{D})</td> </tr> <tr> <td>(v_{D}^1(X) \Rightarrow Hotel(X))</td> </tr> <tr> <td>(v_{D}^2(X, Y) \Rightarrow Located(X, Y))</td> </tr> <tr> <td>(v_{D}^3(X) \Rightarrow Flight(X))</td> </tr> <tr> <td>(v_{D}^4(X, Y) \Rightarrow Arrival\City(X, Y))</td> </tr> <tr> <td>(\ldots)</td> </tr> </tbody> </table> Describing (Reductor): $v_R^1, \ldots, v_R^n$ <table> <thead> <tr> <th>mappings: $\mathcal{I}_R$</th> <th>constraints: $\mathcal{C}_R$</th> </tr> </thead> <tbody> <tr> <td>$v_R^1(X) \Rightarrow Hotel(X)$</td> <td>$v_R^1 \subseteq (\forall Located.Europe)$</td> </tr> <tr> <td>$v_R^2(X,Y) \Rightarrow Located(X,Y)$</td> <td>$v_R^3 \subseteq (\forall DepartureDate.NextEightMonths)$</td> </tr> <tr> <td>$v_R^3(X) \Rightarrow Flight(X)$</td> <td>$v_R^4(X,Y) \land \neg v_R^3(X) \Rightarrow \bot$</td> </tr> <tr> <td>$v_R^4(X,Y) \Rightarrow ArrivalCity(X,Y)$</td> <td>$\ldots$</td> </tr> </tbody> </table> Here are some view definitions that we get from this modeling: \[ \text{def}(v_{BR}^1) = HousingPlace \land \forall Located.France \] \[ \text{def}(v_D^1) = Hotel \land \forall Located.\neg France \] \[ \text{def}(v_E^1) = Hotel \land \forall Located.Europe. \] ### 3.4 Query processing in PicSEL The queries that we consider are conjunctive queries of the form $Q(\tilde{X}) : p_1(\tilde{X}_1, \tilde{Y}_1) \land \ldots \land p_m(\tilde{X}_m, \tilde{Y}_m)$, where the $p_j$'s are domain relations, some of which may be concept expressions or role names. The variables of $\tilde{X} = \tilde{X}_1 \cup \ldots \cup \tilde{X}_m$ are called the distinguished variables of the query: they represent the variables of the query which the user is interested in knowing the instances when he asks the query. The variables that are not distinguished (denoted by $\tilde{Y} = \tilde{Y}_1 \cup \ldots \cup \tilde{Y}_m$) are called existential variables of the query: they are existentially quantified and their use is to constrain the distinguished variables. For example, by the query $Q(X) : Hotel(X) \land Located(X,Y) \land France(Y)$, the user specifies that the answers he is interested in, are all the possible instances of $X$ that are hotels, and for which there exists instances of $Y$ (their locations) that are in France. Answering queries in PicSEL resorts to find conjunctions of source atoms (called rewritings) which, together with the mediated schema and the descriptions of the sources, entail the initial query. **Definition 2 (Rewriting)** Let $Q(\tilde{X}) : p_1(\tilde{X}_1, \tilde{Y}_1) \land \ldots \land p_m(\tilde{X}_m, \tilde{Y}_m)$ be a query expressed in term of domain relations, let $Q_V(\tilde{X}, \tilde{Z})$ be a conjunction of view atoms. $Q_V(\tilde{X}, \tilde{Z})$ is a rewriting of $Q(\tilde{X})$ iff: - $\{Q_V(\tilde{X}, \tilde{Z})\} \cup \mathcal{R} \cup \mathcal{T} \cup \mathcal{I}_V \cup \mathcal{C}_V$ is satisfiable, and Example 3 Coming back to Example 2, let us consider again the query: \[ Q(X) : Hotel(X) \land Located(X, Y) \land \text{France}(Y). \] The query \( Q_V(X) : v_2^1(X) \land v_1^1(X) \land v_2^2(X, Y) \) is a rewriting of \( Q(X) \) because, according to the definitions of \( v_2^1 \), \( v_1^1 \) and \( v_2^2 \), \( v_2^1(X) \) entails \( Hotel \land \forall \text{Located.Europe}(X) \) and \( v_1^1(X) \) entails \( HousingPlace \land \forall \text{Located.France}(X) \). Then, \( v_2^1(X) \land v_1^1(X) \) entails in particular \( Hotel(X) \land \forall \text{Located.France}(X) \). Therefore, according to the semantics of the \( \forall \) constructor, \( v_2^1(X) \land v_1^1(X) \land v_2^2(X, Y) \) entails that there exists \( Y \) such that \( Hotel(X) \land Located(X, Y) \land \text{France}(Y) \) is true, and thus \( Q_V \) is a rewriting of \( Q \). Note that this rewriting shows that answering the query \( Q \) using the available sources requires to integrate the information of the two sources \textit{Reductour} and \textit{BonjourFrance}: hotels and their location are found in the \textit{Reductour} source, but we have to intersect those data with housing places stored in the \textit{BonjourFrance} source to be sure to obtain hotels that are located in France. On the other hand, \( Q'_V(X) : v_2^1(X) \land v_1^1(X) \land v_2^2(X, Y) \) is not a rewriting because it is insatisfiable. It is due to the fact that from the definitions of \( v_2^1 \) (i.e., \( Hotel \land \forall \text{Located.} \neg \text{France} \)) and \( v_1^1 \) (i.e., \( HousingPlace \land \forall \text{Located.} \text{France} \)), it can be entailed that the location of \( X \) is on the one hand necessarily out of France, and on the other hand in France. Therefore, \( v_2^1(X) \land v_1^1(X) \land v_2^2(X, Y) \) entails the two contradictory facts \( \text{France}(Y) \) and \( \neg \text{France}(Y) \), and thus \( Q'_V \) is insatisfiable. A rewriting of a query \( Q(\bar{x}) \) can then be viewed as a specialized query that can be directly executed on the sources, and which provides relevant answers to the initial query. Query processing in \textit{PicSEL} can be summarized as follows. 1. **Normalization of the query.** We exhaustively apply to the body of the query the normalization rule: \( C(o) \land D(o) \rightarrow (C \land D)(o) \), where \( C(o) \) and \( D(o) \) are concept-atoms. Then, the resulting concept expressions are themselves normalized. Every concept expression is put in a normal form of a conjunction of concept expressions of the \textit{(simple)} form: \( A \) (atomic concept), \( \neg A \), \( (\geq n R) \), \( (\leq n R) \), or of the \textit{(complex)} form: \( \forall R_1 \forall R_2 \ldots \forall R_k.D \), where \( D \) is simple. 2. **Verification of the satisfiability of the query.** This consists of (a) checking the satisfiability modulo the terminology of each concept expression appearing in the query, and (b) applying a forward-chaining algorithm to the rules until \( \bot \) is obtained or no new atom can be obtained. If the query is insatisfiable, the query processing stops and the query is transmitted to a module of query relaxation described in [6]. 3) **Query unfolding.** This is an iterative process based on successive steps of unfolding using the rules. Let \( p(\tilde{X}) \) be an ordinary atom. Let \( r : p_1(\tilde{X}_1, \tilde{Y}_1) \land \ldots \land p_k(\tilde{X}_k, \tilde{Y}_k) \Rightarrow p(\tilde{X}') \) be a rule of \( \mathcal{R} \). Let \( \alpha \) be the most general unifier of \( p(\tilde{X}) \) and \( p(\tilde{X}') \), extended such that every variable \( Y_i' \) is assigned to a fresh variable that appears nowhere else. An unfolding of the query using the rule \( r \) is a conjunctive query obtained by replacing in the query the atom \( p(\tilde{X}) \) by the conjunction: \( p_1(\alpha(\tilde{X}_1'), \alpha(\tilde{Y}_1')) \land \ldots \land p_k(\alpha(\tilde{X}_k'), \alpha(\tilde{Y}_k')) \). The process is iterated on each satisfiable unfolding until getting conjunctive queries in which all the ordinary atoms are base predicates. Since the rules are non recursive, the process terminates. 4) **Computation of terminological approximations.** Depending on the variable binding within the body of each conjunctive query, it is possible that conjunctions of concept-atoms and role-atoms are entailed by a single concept-atom. It is important to determine such situations when they exist because they may lead to rewritings that could not be found otherwise. In [17], the conjunctions of concept-atoms and atom-roles that can be entailed by a single concept-atom are characterized by the structure of the binding graph of their variables. The binding graph of a conjunction of unary and binary atoms is defined as follows: its nodes are the variables appearing in the conjunction; there is an edge from \( U_1 \) to \( U_2 \) iff there exists a binary atom \( r(U_1, U_2) \) in the conjunction. In particular, it is shown that if a conjunction \( cj(X, \tilde{Y}) \) has a binding graph which is a tree rooted in \( X \), we can build its \( \mathcal{ALN} \) concept approximation which is the most general \( \mathcal{ALN} \) concept description \( C \) such that \( C(X) \models \exists \tilde{Y} \ cj(X, \tilde{Y}) \). **Example 4** Consider again the query \( Q(X) : \text{Hotel}(X) \land \text{Located}(X, Y) \land \text{France}(Y) \). Its body has a binding graph which is a tree rooted in \( X \). Its concept approximation is: \( \text{Hotel} \sqcap (\geq 1 \text{Located}) \sqcap (\forall \text{Located. France}) \). The query \( Q \) can then itself be approximated by the atomic query \( Q' \) obtained by replacing the body of \( Q \) by: \[ (\text{Hotel} \sqcap (\geq 1 \text{Located}) \sqcap (\forall \text{Located. France}))(X). \] \( Q'(X) : (\text{Hotel} \sqcap (\geq 1 \text{Located}) \sqcap (\forall \text{Located. France}))(X) \), is called a terminological approximation of \( Q \). For every satisfiable conjunctive query resulting from rule unfolding, we build their terminological approximations. They are obtained by replacing a conjunction \( cj(X, \tilde{Y}) \) of concept-atoms and role-atoms whose binding graph is a tree rooted in \( X \) by the single-concept atom \( C(X) \) where \( C \) is the concept approximation of \( cj(X, \tilde{Y}) \). For every resulting conjunctive query, we then proceed to the rewriting of each atom of its body separately, and we conjunct the results to get the final rewritings. 5) **Rewriting of each query, atom by atom.** Rewriting an ordinary atom or of a role-atom is trivial: the rewritings of a role-atom \( r(U_1, U_2) \) (or of an ordinary atom \( p(U) \)) are the view-atoms \( v(U_1, U_2) \) (or \( v(U) \)) such that \( v \in \mathcal{V} \) and \( def(v) = r \) (or \( def(v) = p \)). Rewriting concept-atom is much more complex. It is done by iterating the application of rewriting rules according to a strategy which guarantees termination of the rewriting process. Those rewriting rules are founded the following rules of entailment. - Rewriting of a concept-atom of the form \( \{ \prod_{i=1}^{n} C_i \}(U_0) \) : the rewritings of this type of atom are obtained by conjuncting the rewritings of the concept-atoms \( C_i(U_0) \). \[ (1) \quad \bigwedge_{i=1}^{n} C_i(U_0) \models (\prod_{i=1}^{n} C_i)(U_0). \] - Rewriting of a concept-atom of the form \( C(U_0) \) (where \( C \) is simple i.e., not a conjunction) is based on the following entailment rule where \( D \subseteq \mathcal{T} \): \[ (2) \quad (\forall r_1 \cdots (\forall r_n D))(U_n) \land \bigwedge_{i=1}^{n} r_i(U_{n+1-i}, U_{n-i}) \models C(U_0), \] This is a termination case for the rewriting algorithm. - Rewriting of a concept-atom of the form \( (\geq n \ r)(U_0) \) is based on the following entailment rule: \[ (3) \quad \bigwedge_{i=1}^{n} r(U_0, U_i) \land \bigwedge_{i=1}^{n} \bigwedge_{j=i+1}^{n} U_i \neq U_j \models (\geq n \ r)(U_0). \] The rewriting process is iterated on the role-atoms of the left hand side of the rule. - Rewriting of a concept-atom of the form \( (\forall r \ C)(U_0) \) is based on the following entailment rule: \[ (4) \quad (\leq n \ r)(U_0) \land \bigwedge_{i=1}^{n} (r(U_0, U_i) \land C(U_i)) \land \bigwedge_{i=1}^{n} \bigwedge_{j=i+1}^{n} U_i \neq U_j \models (\forall r \ C)(U_0). \] The rewriting process is iterated on the role-atoms and on the concept-atoms of the left hand side of the rule. **Example 5** Consider the atomic query: \( Q'(X) : (\text{Hotel} \cap (\geq 1 \text{Located}) \cap (\forall \text{Located.France}))(X) \) which is the terminological approximation of the conjunctive query: \( Q(X) : \text{Hotel}(X) \land \text{Located}(X, Y) \land \text{France}(Y). \) Consider the views described in Example 2. Based on Rule (1), rewriting \( (\text{Hotel} \cap (\geq 1 \text{Located}) \cap (\forall \text{Located.France}))(X) \) results in the rewritings of \( \text{Hotel}(X) \), \( (\geq 1 \text{Located})(X) \) and \( (\forall \text{Located.France})(X) \). Based on Rule (2), the rewriting of \( \text{Hotel}(X) \) is terminal and we get: Rewritings($\text{Hotel}(X)) = \{v^1_D(X), v^1_R(X)\}$. Based on Rule (3), we obtain the following rewritings of ($\geq 1 \text{Located}(X)$): Rewritings(($\geq 1 \text{Located}(X)$)) = \{v^2_{BF}(X,Y), v^2_R(X,Y), v^2_D(X,Y)\}. Finally, Rule (2) is used for getting the rewriting of ($\forall \text{Located.France}(X)$): Rewritings(($\forall \text{Located.France}(X)$)) = \{v^1_{BF}(X)\}. There are 6 ways of conjunctively combining the rewritings of the three atoms $\text{Hotel}(X)$, ($\geq 1 \text{Located}(X)$) and ($\forall \text{Located.France}(X)$): - $v^1_D(X) \land v^2_{BF}(X,Y) \land v^1_{BF}(X)$: not satisfiable. - $v^1_D(X) \land v^2_R(X,Y) \land v^1_{BF}(X)$: not satisfiable. - $v^1_D(X) \land v^2_D(X,Y) \land v^1_{BF}(X)$: not satisfiable. - $v^1_R(X) \land v^2_{BF}(X,Y) \land v^1_{BF}(X)$: satisfiable. - $v^1_R(X) \land v^2_R(X,Y) \land v^1_{BF}(X)$: not satisfiable. - $v^1_R(X) \land v^2_D(X,Y) \land v^1_{BF}(X)$: satisfiable. The rewritings of $Q'(X)$, and thus of $Q(X)$, are those which are satisfiable: $Q^1_{\land}(X) : v^1_R(X) \land v^2_{BF}(X,Y) \land v^1_{BF}(X)$ $Q^2_{\land}(X) : v^1_R(X) \land v^2_D(X,Y) \land v^1_{BF}(X)$. 4 Overview of Xyleme Xyleme is an integration system dealing with data sources that are XML documents. All XML documents are stored in a repository. In this way, the system is efficient even when several data issued from distributed sources must be combined to answer queries. A semantic module plays the role of interface between end-users and XML documents which, by definition, come from several sources and are semantically heterogeneous. Figure 2 presents the overall architecture of the system. ![Xyleme Architecture Diagram](image_url) **Fig. 2.** Xyleme architecture - The Repository and Index Manager module is the lowest level in Xyleme. It enables to store and index XML documents. - The Acquisition and Crawler module inspects the Web and collects all the XML documents, which are loaded in the repository by the Loader module. - The Change Control module is responsible of specific functionalities, such as monitoring of document changes, version management and subscription of temporal queries. - The Semantic module provides a homogeneous integrated and mediated schema on the heterogeneous XML documents stored in the repository. - The Query Processor module enables to query the XML repository as a database. In particular, it translates a query in terms of the semantic layer into another one computable on the stored documents. A general presentation of Xyleme is given in [33]. In this paper, we focus on the semantic module and the translation of abstract queries. A presentation of the other modules can be found in [20,22,24]. 4.1 A uniform tree-based data model The XML documents that are stored in the repository are instances of a DTD that defines their structure. From a data integration viewpoint, the data coming from different sources are the XML documents, and the DTDs are the schemas of the data sources. For example, here is the partial definition of the DTD MyDTD: ```xml <!ELEMENT MyDTD (Film*, Painting*)> <!ELEMENT Film (Casting, Character*,Title)> <!ELEMENT Casting (Actor*)> <!ELEMENT Painting (Title, Author, Museum?)> <!ELEMENT Actor (#PCDATA)> ............. ``` In our model, we abstract XML documents as being data trees. Our modelling simplifies real XML documents in several ways. For example, the model does not distinguish between attributes and elements. We consider unordered trees. We use also a simplified version of DTDs, which we call tree type, where the multiplicity of an element is not considered. Data trees and tree types are labelled unordered trees, where the labels correspond to the names of the elements and the attributes of the XML documents. A data tree $d$ is an instance of a tree type $t$ if there exists an homomorphism from $d$ onto $t$. For example, Figure 3 gives an example of a data tree. It is an instance of the tree type given in Figure 4. The aim of the semantic module is twofold: (i) to provide an homogeneous mediated schema over the data trees, in order to allow a natural expression of queries for the user without having to be aware of actual tree types that can have heterogeneous structures and labels; (ii) to define the connection between this semantic module and the tree types describing the actual data trees, in order to make possible query processing. The semantic module provides a simple description of domains (e.g. culture, tourism) in the form of an abstract tree type. An abstract tree type can be considered as an abstract merger of the DTDs associated with the set of XML documents of some domain. Figure 5 shows a fragment of an abstract tree type in the cultural domain. The label of the root is the domain name (Culture). The internal nodes are labelled with terms that represent either concepts of the domain (Art, Architecture, Cinema) or properties of those concepts (Name, Title). There are two main reasons for the choice of representing a mediated schema as a tree. First, it must be compatible with a real XML DTD, because it is intended to be the schema of all the XML documents of the domain. Next, the mediated schema must be simple enough, because it is the support of the visual query interface tool, intended to be used by non-programmer users. The links between a node and its sons in the abstract tree type have no strict semantics. They may correspond to a relation of specialisation between concepts, or to a relation of composition, or simply express different viewpoints on a concept. A link also exists between a concept and a property of it. We do not distinguish between those different types of links. In other words, a node labelled with a term $E_2$ being a son of a node labelled with $E_1$ just means that the term $E_2$ has to be interpreted in the scope of meaning of $E_1$. Thus, the different occurrences of a same term do not have the same meaning. This is obvious for terms that represent properties (e.g. Name can appear different times, and may represent the name of different entities), but it is also the case for terms representing concepts (e.g. Author under Movie means director, while Author under Painting means painter). Such representations are very simple and structured. They enable end-users to build semantic queries from different viewpoints in an easy and natural way, using both the vocabulary and the structure of the abstract tree type. This provides a homogeneous and simple user interface for querying a very large amount of heterogeneous XML documents stored in the repository. Using this interface, end-users must be able to obtain relevant answers for queries. For this, Xyleme has to identify the XML documents concerning each query issued against the semantic module. This requires the creation and maintenance of a correspondence between the labels of the abstract tree type and the elements of the concrete tree type that describe the structure of the XML documents. This way, each abstract query can be translated into a set of concrete queries over real documents, by simply replacing the abstract labels of the query with the corresponding concrete labels. In Xyleme, the correspondence is stated by a mapping relation between paths of the abstract tree type and paths of the tree types modeling the DTDs of the data stored in the repository. **Example 6** Here are some examples of meaningful mapping elements between the abstract tree type given in Figure 5 and the tree type given in Figure 4: - Culture/Cinema/Movie <-> MyDTD/Film - Culture/Cinema/Movie/ActorActress <-> MyDTD/Film/Casting/Actor Because of the number of concrete data trees that have to be mapped to the abstract tree type, the mapping relation cannot be manually defined by some database administrator. Some automatic help must be provided. In Section 4.3, we describe a semi-automatic method for generating the mapping relation that has been implemented in Xyleme and experimented. By accessing the abstract tree type through a user-friendly interface, end-users query a single tree structure summarizing many DTDs. The query language is also tree-based. The query tree on the left in Figure 6 models a query in the cultural domain asking the titles of all the films in which the actor Sean Connery is acting. The query tree on the right in Figure 6 asks the description of all impressionist works of art. These examples illustrate the basic method for building abstract queries: the user marks in the abstract tree type the nodes to be included in the result (selected nodes are marked with a S, e.g. Title, WorkOfArt) and the nodes constrained with conditions (conditional nodes are marked with a C, e.g. Actor-Actress, ArtStyle). The query itself is given by a tree query pattern built from the abstract tree type. Fig. 6. Example of user queries The Xyleme query language is a subset of XQuery, the W3C query language for XML data [31]. Unlike XQuery, the Xyleme query language does not allow joins or document transformation. Moreover, the language ignores ordering and random access through an ordinal number to the descendants of a tree node, features that exist in XPath [10], which is a part of XQuery. On the other hand, the Xyleme query language is more powerful than XPath, because it enables to extract any part of a subtree, while XPath can only extract a full subtree, identified by its access path. Notice that even if the abstract tree queries do not contain joins, the translation into concrete tree queries may produce joins based on links between concrete documents (see [11]). Notice also that the last version of the Xyleme query language, not presented here, was enriched with additional features such as joins (on values and on links) and simple document transformation. 4.2 Query processing The users queries are defined relatively to the mediated schema and not relatively to the actual tree types corresponding to the data stored in the repository. Therefore they cannot be directly evaluated against that data. The evaluation of an abstract query is then a two step process. First, the abstract tree Fig. 7. An abstract tree type, a concrete tree type and a data tree query is translated into concrete tree queries by using the mapping relation. Second, each concrete tree query has to be evaluated on the database. The translation process is described in detail in [11,13]. It relies on building trees consistent with the mapping relation. In this paper, we focus on illustrating by example the semantics of the queries and the query translation process. Consider the following database schema composed of an abstract tree type and a concrete tree type as given in Figure 7 with the following mapping relation: \[ \begin{align*} \text{Movie} & \leftrightarrow \text{Film} & \text{Movie/ActorActress} & \leftrightarrow \text{Film/Casting} \\ \text{Movie/ActorActress/Name} & \leftrightarrow \text{Film/Character} \\ \text{Movie/ActorActress/Name} & \leftrightarrow \text{Film/Casting/Actor} \\ \text{Movie/ActorActress/Role} & \leftrightarrow \text{Film/Character/Name} \end{align*} \] An instance of the database is also given in Figure 7 with only one data tree. Figure 8 gives three examples of abstract tree queries that are conform to the abstract tree type of Figure 7. Fig. 8. Example of tree queries The interpretation of the first one (Query Q₁) is: find all the data trees rooted at a node labelled by Movie, such that there exists a subtree rooted in a node labelled by ActorActress which contains two branches, the one rooted in a node labelled by Name must contain the string “Sean Connery” and the one rooted in a node labelled by Role must contain the string “Indiana Jones”; for those data trees returns the identity of subtrees rooted in the nodes labelled by Name and Role. The second one (Query $Q_2$) has a slightly different interpretation: find all the data trees rooted at a node labelled by $\text{Movie}$ such that there exists one subtree rooted in a node labelled by $\text{ActorActress}$ having a branch rooted in a node labelled by $\text{Name}$ which contains the string "Sean Connery", and there exists another (possibly distinct) subtree rooted in a node labelled by $\text{ActorActress}$ having a branch rooted in a node labelled by $\text{Role}$ which contains the string "Indiana Jones". The last tree query (Query $Q_3$) is an example where we have a non atomic boolean condition "Sean Connery" and "Indiana Jones". This boolean condition expresses that the corresponding data subtree must contain the two strings "Sean Connery" and "Indiana Jones". When talking about the interpretation of an abstract query, we must understand that these data trees exist only virtually. As explained in the database model, the real data trees are associated with concrete tree types. For the translation process, some nodes in the tree query are crucial: they are nodes with conditions, nodes that are selected, or “join” nodes. **Definition 3 (Necessary nodes in a tree query)** A node in a tree query is necessary iff it is the root, a selected node, a conditional node or a node (called a join node) which has, at least, two distinct descendants that are necessary nodes. For a tree query $Q$, we denote $N(Q)$ the set of its necessary nodes. The necessary nodes can be partially ordered by the relation $\prec$. Let $u$ and $v$ be two necessary nodes: $u \prec v$, iff $u$ is a descendant of $v$ and there is no necessary node $w$ such that $u \prec w \prec v$. The translation of an abstract query $Q$ into a concrete query can be summarized as follows. The concrete query has exactly the same tree structure as the translated abstract query but the nodes of the abstract tree query must be mapped by a function $h$ onto the nodes of the concrete tree query such that the labelling of necessary nodes of the abstract tree query and the concrete tree query is conform to the mapping relation. More precisely: for two necessary nodes $u$ and $v$ in $N(Q)$ such that $u \prec v$, their images by the translation $h$ must satisfy that $\text{path}(h(v))$ is a prefix of $\text{path}(h(u))$ (denoted $\text{path}(h(v)) \subset \text{path}(h(u))$). An abstract query can have more than one translation, depending on the mapping relation. It may also be possible that an abstract query has no translation, as it is illustrated in the following example. **Example 7** We are considering the abstract queries given in Figure 8 and the database composed of a unique data tree instance $d$ as presented in Figure 7. Each abstract path to any necessary node of the query must be con- verted into a concrete path using the mapping relation. For example, if we consider the abstract tree query $Q_1$, its necessary nodes, $u_1$, $u_2$, $u_3$, and $u_4$, respectively labelled by Movie, Actor/Actress, Name and Role, are such that: $u_3 < u_2$ and $u_4 < u_2$. The corresponding abstract paths leading to the necessary nodes are: Movie, Movie/Actor/Actress, Movie/Actor/Actress/Name, and Movie/Actor/Actress/Role. By the mapping relation given in Example ??, they must be mapped to the concrete paths Film, Film/Casting, Film/Casting/Actor (or Film/Character) and Film/Character/Name respectively. This suggests a candidate translation based on an homomorphism $h$ such that: $h(u_1)$ is labelled by Film, $h(u_2)$ is labelled by Casting, $h(u_3)$ is labelled by Actor or by Character, and $h(u_4)$ is labelled by Name. However, in order that candidate translation to be a real translation, since $u_4 < u_2$, $\text{path}(h(u_2))$, i.e., Film/Casting, should be a prefix of $\text{path}(h(u_4))$, which must be Film/Character/Name. Since Film/Casting is not a prefix of Film/Character/Name, there is no translation, and thus no answer, for the query $Q_1$. If we consider now the abstract query $Q_2$, its necessary nodes are $v_1$, $v_2$ and $v_3$, respectively labelled by Movie, Name and Role. The abstract paths leading to those necessary nodes are: Movie, Movie/Actor/Actress/Name, and Movie/Actor/Actress/Role. Based on the mapping relation, they can be converted respectively into Film, Film/Casting/Actor and Film/Character/Name. This leads to a translation $Q'_2$ corresponding to an homomorphism $h'$ such that $h'(v_1)$ is labelled by Film, $h'(v_2)$ is labelled by Actor and $h'(v_3)$ is labelled by Name. In this case, $h'$ satisfies the prefix property since: $v_2 < v_1$ and $\text{path}(h(v_1))$ (i.e., Film) is a prefix of $\text{path}(h(v_2))$ (i.e., Film/Casting/Actor), and $v_3 < v_1$ and $\text{path}(h(v_1))$ (i.e., Film) is a prefix of $\text{path}(h(v_3))$ (i.e., Film/Character/Name). The resulting concrete query $Q'_2$ is given in Figure 9. ![Fig. 9. The abstract query $Q_2$ and its translation $Q'_2$](image) It can then be evaluated against the data tree $d$: there exists a valuation $\sigma_d$, where the node labelled with Actor can be associated with the leaf of $d$ labelled by Actor and valued by "Sean Connery" and the other node labelled by Name can be associated with the leaf of $d$ labelled by Name and valued by "Indiana Jones". Therefore, the query $Q'_2$ has at least this answer. For the abstract query $Q_3$ the pattern of the translation $Q'_3$ is reduced to one node labelled with Film. The whole data tree $d$ matches also the query $Q'_3$ because it is rooted at a node labelled by Film which contains the strings "Sean Connery" and "Indiana Jones" by application of the closure valuation principle. 4.3 Automatic Generation of Mappings We have seen previously that the mapping relationship is a crucial element of the data model for translating abstract queries into concrete ones. In this section, we address the problem of automatically finding the elements of the mapping relation which states the correspondence between paths of concrete tree types and paths of the abstract tree type. We have to handle heterogeneous names and structures because concrete tree types come from various sources designed by different persons who made personal choices on the names of the labels and on the tree structures. Therefore, automatic mapping generation have to deal with semantic and structure heterogeneity. Below, we summarize the method for automatic mapping generation in Xyleme, which has been implemented in Java and experimented in the cultural domain [13]. It is based on two kinds of criteria: syntactic/semantic and structural. 4.3.1 Syntactic and Semantic Matching of terms Automatic mappings generation is based on term matching. The idea is that a mapping is generated only if the abstract and the concrete terms identified by the mapped paths are semantically related. We check two kinds of relations between terms: syntactic and semantic matching. Syntactic matching concerns the syntactic inclusion of a term, or of a part of a term, into another one. For example, the concrete term Actor is syntactically similar to the abstract term Actor-Actress. This method also includes techniques for detecting abbreviations, such as nb for Number, etc. For more details, see [29]. Semantic matching is based on the use of extra knowledge available through existing ontologies or thesauri. In our experimentation, we chose the WordNet thesaurus [23]. WordNet groups English nouns, verbs, adjectives and adverbs into sets of synonyms that are linked through semantic relations. Each set of synonyms (synset) represents a concept. A word may belong to several synsets, each one representing a particular sense. Our approach only exploits semantic links between nouns because we chose to use only abstract terms that are nouns. Syntactic / semantic matching between words is not enough to obtain precise mappings. The real meaning of a term depends on the place it occupies in the concrete tree type, which defines the interpretation context of the word. More precisely, a term may occur several times in the same concrete tree type with different senses. Its meaning may be influenced by the meaning of its predecessors in the tree (e.g. Name may be the name of an artist, of a museum, etc.). Our approach is based on a very simple hypothesis: the terms of a concrete tree type are either object names (e.g. Painting), or property names (e.g. Name). We consider that property names have a meaning only in the context of the object that they characterise. So, an object, which is characterised by a set of properties, defines the interpretation context of its properties. In order to decide if a term is an object or a property node, we use heuristics based on the translation of a concrete tree type into a conceptual database schema. We use conceptual schemas built according to the Entity-Relationship formalism, that naturally helps to determine the classes, called entities, in a domain. An entity is a class of instances that share the same properties called attributes. In our approach, we consider that object nodes are similar to entities and that property nodes are similar to attributes. Given a link A - B in the concrete tree type, one heuristics used in the translation process is that B may refer to an entity (according to the above definition) only if B has son nodes, these ones being interpreted as B's attributes. Such a heuristics leads to consider that leaves in a concrete tree type always are property nodes (they can't refer to entities, so they can't be object nodes). Other heuristics are used to qualify internal nodes in a concrete tree type, in order to decide if they are object or property nodes. The exhaustive translation mechanism is described in [29]. However, very often, internal nodes are object nodes. The basic idea underlying our structural constraints is that a mapping of a property node must be “compatible” with the mapping of the object node it characterizes. In other words, because the property and the object nodes in the concrete tree type are related (the object defines the context of the property), the corresponding abstract terms must be related in the same context-based manner. Thus, if a concrete path identifying a property name is mapped to an abstract path X, this mapping will be valid only if the object characterized by that property is mapped to a predecessor of X in the abstract tree type. This introduces a context constraint into the mapping generation process, because a property name P of an object O may only be mapped to the subset of abstract terms placed below the abstract terms mapped to O, i.e. the context of the object is transmitted to the property. This also means that mappings for object names must be computed first. For instance, in the concrete tree type MyDTD, the terms Title, Author and Museum are properties of the object Painting. The mappings: \[ \text{Culture/Art/WorkOfArt/Title} \leftrightarrow \text{MyDTD/Painting/Title} \] \[ \text{Culture/Art/WorkOfArt/Author} \leftrightarrow \text{MyDTD/Painting/Author} \] are valid, because there exists a mapping between the object MyDTD/Painting and the abstract term Culture/Art/WorkOfArt. Notice that this context-based constraint may seem too strong in some cases. For instance, the automatic generation algorithm will not find the mapping Culture/Art/Museum \(\leftrightarrow\) MyDTD/Painting/Museum if there is no mapping from MyDTD/Painting to a prefix of Culture/Art/Museum. Imagine that the system does not semantically match Painting with Art, then the “obvious” mapping Culture/Art/Museum \(\leftrightarrow\) MyDTD/Painting/Museum is missed. However, a more careful analysis of this case shows that the missed mapping is not so obvious, because it is not clear if Culture/Art/Museum is a museum with paintings. The structural, context-based constraints for automatic mapping generation significantly improve precision if mappings are correctly found for object nodes. On the other hand, an error at an object node will propagate to all its property nodes. 5 Conclusion and perspectives PICSEL and Xyleme are two mediator-based information integration systems that have been designed in very different settings. As a result, different choices have been done for designing the mediated schema and the semantic mappings between the mediated schema and the schemas of the sources. In PICSEL, a logical formalism combining the expressive powers of (non recursive) DATALOG rules and the \(\mathcal{ALN}\) description logic has been used for modeling the semantic relationships between source schemas through a rich mediated schema. It has proved very useful for expressing fine-grained differences between sources containing closely related data. This choice is appropriate for building specialized information servers over a reasonable number of data sources. Xyleme is representative of information integration agents that have to integrate a huge number of sources covering very broad topics. In such a setting, the mediated schema and the mappings must be simple because the challenging issue is to obtain them as automatically as possible. In particular, the number of mappings is too huge to build them manually. We have outlined the impact of the choice of the knowledge representation formalism on the query reformulation problem, which is the core algorithmic problem for answering queries in an information integration system. Clearly, as the languages for describing data sources, the mediated schema, or the users' queries become more expressive, the query reformulation problem becomes harder. The key challenge is then to identify formalisms offering a reasonable tradeoff between expressive power and good computational properties for the accompanying reformulation algorithm. Despite their differences, PicSEL and Xyleme both illustrate a centralized approach of mediation based on a single mediated schema. For scaling up to the Web, this centralized approach of mediation is probably not flexible enough, and distributed systems of mediation are more appropriate. The Semantic Web envisions a world-wide distributed architecture where data and computational resources will easily interoperate to coordinate complex tasks such as answering queries or global computing. Semantic marking up of web resources using ontologies is expected to provide the necessary glue for making this vision work. The de-centralized nature of the Web makes inevitable that communities of users or software developers will use their own ontologies to describe their data or services. In this vision of the Semantic Web based on distributed ontologies, the key point is the mediation between data, services and users, using mappings between ontologies. Complex mappings and reasoning about those mappings are necessary for comparing and combining ontologies, and for integrating data or services described using different ontologies. For an easy deployment of de-centralized systems of mediation at the scale of the Web, it will be essential to use expressive and declarative languages for describing semantic relationships between ontologies serving as schemas of distributed data or services. CARIN has the potential to be a useful modeling tool for expressing and reasoning on complex mappings between ontologies. Acknowledgments: We would like to thank the PicSEL and Xyleme teams for many fruitful discussions and particularly Serge Abiteboul, Bernd Aman, Sophie Cluet, Claude Delobel, Christine Froidevaux, Irini Fundulaki, François Goasdoué, Tova Milo, Brigitte Safar, Jean-Pierre Sirot, Pierangelo Veltri and Dan Vodislav. References http://www.w3c.org/TR/xpath. [12] C-web project. http://cweb.inria.fr. [31] XQuery 1.0: An XML Query Language. http://www.w3.org/TR/xquery/.
{"Source-Url": "https://abiteboul.com/gemoReports/GemoReport-273.pdf", "len_cl100k_base": 16196, "olmocr-version": "0.1.53", "pdf-total-pages": 30, "total-fallback-pages": 0, "total-input-tokens": 197029, "total-output-tokens": 19835, "length": "2e13", "weborganizer": {"__label__adult": 0.0004055500030517578, "__label__art_design": 0.001323699951171875, "__label__crime_law": 0.000583648681640625, "__label__education_jobs": 0.007167816162109375, "__label__entertainment": 0.0003261566162109375, "__label__fashion_beauty": 0.0002753734588623047, "__label__finance_business": 0.0012912750244140625, "__label__food_dining": 0.0005254745483398438, "__label__games": 0.0012311935424804688, "__label__hardware": 0.0009627342224121094, "__label__health": 0.0006799697875976562, "__label__history": 0.0010929107666015625, "__label__home_hobbies": 0.0002529621124267578, "__label__industrial": 0.0006284713745117188, "__label__literature": 0.001870155334472656, "__label__politics": 0.0005207061767578125, "__label__religion": 0.0007033348083496094, "__label__science_tech": 0.338134765625, "__label__social_life": 0.0003185272216796875, "__label__software": 0.08514404296875, "__label__software_dev": 0.55517578125, "__label__sports_fitness": 0.00023496150970458984, "__label__transportation": 0.0008292198181152344, "__label__travel": 0.0004968643188476562}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 71665, 0.01659]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 71665, 0.64264]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 71665, 0.87424]], "google_gemma-3-12b-it_contains_pii": [[0, 1871, false], [1871, 4634, null], [4634, 5558, null], [5558, 8461, null], [8461, 11223, null], [11223, 13678, null], [13678, 16084, null], [16084, 18752, null], [18752, 21566, null], [21566, 24373, null], [24373, 26696, null], [26696, 29158, null], [29158, 32312, null], [32312, 35839, null], [35839, 38347, null], [38347, 40172, null], [40172, 42353, null], [42353, 43478, null], [43478, 46313, null], [46313, 48518, null], [48518, 50217, null], [50217, 53031, null], [53031, 55814, null], [55814, 58035, null], [58035, 60897, null], [60897, 63280, null], [63280, 65896, null], [65896, 68263, null], [68263, 70541, null], [70541, 71665, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1871, true], [1871, 4634, null], [4634, 5558, null], [5558, 8461, null], [8461, 11223, null], [11223, 13678, null], [13678, 16084, null], [16084, 18752, null], [18752, 21566, null], [21566, 24373, null], [24373, 26696, null], [26696, 29158, null], [29158, 32312, null], [32312, 35839, null], [35839, 38347, null], [38347, 40172, null], [40172, 42353, null], [42353, 43478, null], [43478, 46313, null], [46313, 48518, null], [48518, 50217, null], [50217, 53031, null], [53031, 55814, null], [55814, 58035, null], [58035, 60897, null], [60897, 63280, null], [63280, 65896, null], [65896, 68263, null], [68263, 70541, null], [70541, 71665, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 71665, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 71665, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 71665, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 71665, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 71665, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 71665, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 71665, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 71665, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 71665, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 71665, null]], "pdf_page_numbers": [[0, 1871, 1], [1871, 4634, 2], [4634, 5558, 3], [5558, 8461, 4], [8461, 11223, 5], [11223, 13678, 6], [13678, 16084, 7], [16084, 18752, 8], [18752, 21566, 9], [21566, 24373, 10], [24373, 26696, 11], [26696, 29158, 12], [29158, 32312, 13], [32312, 35839, 14], [35839, 38347, 15], [38347, 40172, 16], [40172, 42353, 17], [42353, 43478, 18], [43478, 46313, 19], [46313, 48518, 20], [48518, 50217, 21], [50217, 53031, 22], [53031, 55814, 23], [55814, 58035, 24], [58035, 60897, 25], [60897, 63280, 26], [63280, 65896, 27], [65896, 68263, 28], [68263, 70541, 29], [70541, 71665, 30]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 71665, 0.0625]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
58290390d599d07d2e42ac60fbe7eb109d0de93e
Towards a Metric Suite Proposal to Quantify Confirmation Biases of Developers Gul Calikli and Ayse Bener Data Science Laboratory Mechanical and Industrial Engineering Ryerson University Toronto, ON, Canada {gcalikli, ayse.bener}@ryerson.ca Turgay Aytac Prescience Inc. West New York, NJ, USA taytac@scidesktop.org Ovunc Bozcan Turkcell Istanbul, Turkey ovunc.bozcan@turkcellteknojloji.com.tr Abstract—The goal of software metrics is the identification and measurement of the essential parameters that affect software development. Metrics can be used to improve software quality and productivity. Existing metrics in the literature are mostly product or process related. However, thought processes of people have a significant impact on software quality as software is designed, implemented and tested by people. Therefore, in defining new metrics, we need to take into account human cognitive aspects. Our research aims to address this need through the proposal of a new metric scheme to quantify a specific human cognitive aspect, namely “confirmation bias”. In our previous research, in order to quantify confirmation bias, we defined a methodology to measure confirmation biases of people. In this research, we propose a metric suite that would be used by practitioners during daily decision making. Our proposed metric set consists of six metrics with a theoretical basis in cognitive psychology and measurement theory. Empirical sample of these metrics are collected from two software companies that are specialized in two different domains in order to demonstrate their feasibility. We suggest ways in which practitioners may use these metrics to improve software development process. I. INTRODUCTION Software metrics provide a quantitative basis for the development and validation of software development process. More accurate schedule and cost estimates, better quality software products, and higher productivity require effective software management, which can be facilitated by the improved use of software metrics. Product metrics may measure the complexity of the software design, the size of the final program (either source or object code), or the number of pages of documentation produced. [1]. Among most widely studied product metrics are LOC (Lines of Code), Halstead’s metrics [2], McCabe’s cyclomatic complexity [3] and function points [4]. These metrics are criticized due to the lack of a universal agreement about what these metrics measure [1], [5]. Another set of widely used product metrics consist of theoretically grounded metrics of the Object-Oriented (OO) design by Kemerer and Chidamber [6]. Process Metrics are measures of the software development process such as overall development time, type of methodology used or development history (i.e., churn) metrics. Although the three pillars of software development are Product, Process and People (3Ps), people-related metrics are rarely addressed. In the literature, various people-related metrics have been used to build learning-based models to identify defect-prone parts of software. Among such metrics are organizational metrics [8], number of developers [9], [10], developer experience [11], [12] and social interaction between developers [13], [14]. However, these metrics are not directly related with the thought processes of people or other cognitive aspects. On the other hand, thought processes and cognitive aspects of people are one of the fundamental concerns of software development [21], [22]. In our previous research, we wanted to understand the impact of the thought processes of people in determining software defect proneness [15], [16], [17]. We focused on a specific cognitive aspect of people, namely “confirmation bias”, which is defined as the tendency of people to seek evidence to verify hypotheses rather than seeking evidence to refute them. In order to measure confirmation bias, we defined a methodology that is based on Wason’s grounded work in cognitive psychology literature, namely “Wason’s Selection Task” and “Wason’s Rule Discovery Task”. Having discovered a correlation between confirmation bias levels of developers and software defect density, we later used confirmation bias values of developers to learn defect prediction models [18]. Our empirical results demonstrated that the thought processes of people have a significant impact on the defect proneness of software. Due to confirmation bias, developers perform tests to make their program work rather than to break their code. There are similarities between Wason’s rule discovery task and functional (black-box) testing performed by developers. Moreover, logical reasoning skills, which Wason’s selection task aims to assess are essential during unit testing activities, such as white-box testing. During our previous research, we conducted field studies in large and medium-scale software companies both in Canada and Turkey. As a result, we have become aware of the problems encountered by practitioners during software development process. During daily software engineering activities, practitioners need metrics, which are simple and comprehensible enough to guide them while making decisions under uncertainty. Therefore, in this study, we propose a confirmation bias metric set to facilitate practitioners’ decision making process about software development activities. We can summarize the contributions of this work as follows: - A set of metrics that are constructed with a firm basis in theoretical concepts in cognitive psychology, and measurement theory. - Presentation of empirical data from commercial projects to illustrate the characteristics of these metrics on real applications. The rest of the paper is organized as follows: In Section II, we present theoretical background about confirmation bias and measurement theory. Details of our empirical study such as data collection and the employed methodology are explained in Section III. In Section IV we present the empirical study results that aim to illustrate the characteristics of data from software companies. We explain the practical implications of the proposed metrics suite in Section V. Threats to validity are addressed in Section VI. Finally, we mention future work and conclude in Section VII. II. THEORETICAL BACKGROUND A. Confirmation Bias In cognitive psychology, confirmation bias is defined as the tendency of people to seek for evidence that could verify their hypotheses rather than seeking for evidence that could falsify them. The term confirmation bias was first used by Peter Wason in his rule discovery experiment [19] and later in his selection task experiment [20]. 1) Wason’s Rule Discovery Task: The experimental procedure of Wason’s Rule Discovery Task is as follows: Initially, the subject is given a record sheet on which the triple of numbers “2 4 6” is written and (s)he is told that 2 4 6 conforms to a rule, which (s)he is supposed to discover. In order to discover the rule, the subject is asked to write down triples together with the reasons of his/her choice on the record sheet. After each instance, the examiner tells the subject whether the instance conforms to the rule or not. The subject can announce the rule only when (s)he is highly confident. If the subject fails to discover the rule at the first attempt, (s)he can continue giving instances together with reasons for his/her choice. This procedure continues iteratively until either the subject discovers the rule or (s)he wishes to give up. However, if the subject cannot discover the rule in 45 min, the experimenter aborts the procedure. Wason designed this experiment in such a way that once the subject sees the triple “2 4 6”, a set of hypotheses is formed in his/her mind. Most popular ones of such hypotheses are as follows: “even numbers in ascending order”, “numbers ascending with increments of two”, “numbers ascending with constant increments”, [19], [15], [16], [17], [18]. Unless the subject tries to refute such hypotheses after having gained some confidence about the rule, it is unlikely to discover the correct rule, which is “ascending numbers”. 2) Wason’s Rule Discovery Task in Relation to Developer Performance: There are similarities between Wason’s rule discovery task and functional (black-box) testing that are performed by software developers to test the functional units of their codes during unit testing [21]. According to the findings of Wason’s rule discovery task, the subjects have a tendency to select many triples (i.e., test cases) that are consistent with their hypotheses and few tests that are inconsistent with them. For instance, choosing triples such as “5 10 15”, “1 3 5” and “3 6 9” would not be an effective way of testing the validity of the hypothesis “numbers ascending with constant increments”. One can test the validity of such an hypothesis only by giving examples that have the potential to refute that hypothesis (i.e., “3 7 19”, “4 2 16”, “1 100 102”, etc.). Similarly, program testers may select many test cases consistent with the program specifications (positive tests) and a few that are inconsistent with them (negative tests). Moreover, the number of possible test cases is either infinite or too large to be tested within a limited amount of time. Consequently, a strategic approach must be followed that covers both positive and negative test cases while trying to make the code fail during testing in order to find as many defects as possible. 3) Wason’s Selection Task: In the original task, the subject is given four cards, where each card has a letter on one side and a number on the other side. These four cards are placed on a table showing D, K, 3, 7, respectively. Given the rule “If p, then q.”, where p is a letter on one side and q is a number on the other side, the subject is asked which card(s) must be turned over to find out whether the rule is true or false [20]. 4) Wason’s Selection Task in Relation to Developer Performance: Testing the correctness of conditional statements in the source code during white box testing also requires logical reasoning skills. In order to explain the analogy between Wason’s selection task and white box testing, we extend a simple example given by Stacy an MacMillian [22] as follows: Suppose a developer wants to make sure that his/her program avoids de-referencing a null pointer by always checking before de-referencing. During unit testing, the developer would perform a test that could be thought of as checking the validity of the following hypothesis: “If a pointer is de-referenced, then it is checked for nullity.” (If p, then q). Logical reasoning allows us to categorize parts of the code that may need to be tested as follows: - Category #1: Parts of the code where a pointer is checked for nullity. The pointer may or may not be dereferenced in these code parts. - Category #2: Parts of the code where a pointer is not checked for nullity. The pointer may or may not be dereferenced in those parts. - Category #3: Parts of the code where a pointer is dereferenced. The pointer may or may not have been checked for nullity. - Category #4: Parts of the code where a pointer is not dereferenced. The pointer may or may not have been checked for nullity. It is important to determine whether every pointer is checked for nullity in parts of the code, which belong to category #3, since we know every pointer is dereferenced in those parts of the code. It is also important to know whether every pointer is dereferenced in parts of the code that belong to category #2, since we know none of the pointers are checked for nullity in those parts. On the other hand, we don’t need to check whether every pointer is dereferenced in parts of the code that belong to category #1, since we know every pointer is checked for nullity, and we don’t need to check whether every pointer is checked for nullity in parts of the code that belong to category #4, since we know none of the pointers are dereferenced in there. We can arrive the conclusion mentioned above by thinking according to modus ponens: Given that p is true, “if p then q” is true only if q is true. The logical statements “if p then q” and “if not-q then not-p” are equivalent. Therefore, given that not-q is true, “if not-q, then not-p” is true only if not-p is true. Based on these logical facts, one can conclude that parts of the code, which belong to category #2 and category #3 need to be checked in order to find out whether the program avoids dereferencing a null pointer. B. Measurement Theory Metrics developed in empirical software engineering literature have been criticised due to the lack of a theoretical base [1]. As a solution to this issue, Weyuker proposed a formal set of criteria to evaluate software metrics [5]. Kemerer and Chidamber later used Weyuker’s proposed set of measurement principles in order to analytically evaluate their Object-Oriented (OO) design metrics [6]. Weyuker’s formal list of desiderata for software metrics is based on the foundations of measurement theory, which is a branch of applied mathematics that is useful in measurement and data analysis. Measurement theory attempts to describe, categorize, and evaluate quality of the measurements, improve the usefulness, accuracy and meaningfulness of measurements and propose methods for developing new and better measurement instruments [23]. Weyuker’s principles and hence the theoretical base of Kemerer and Chidamber’s OO design metrics are based on representational measurement theory. In representational measurement theory, numbers are assigned to objects only if objects are “quantifiable” and in order to be able to measure an object, there must be a transformation from the empirical relational system to the formal relational system. For instance, if the objects are rigid rods, then lengths of rigid rods in the empirical relation system can be transformed to real numbers in the formal relational system. Hence, transformation of the empirical relation “Rod A is longer than rod B” to the formal relation becomes “8 inch rod 1 > 12 inch rod”. Representational measurement theory is suitable for Kemerer and Chidamber’s OO design metrics. Since classes in an object oriented code can be associated with numbers (e.g. numbers of children of a class, depth of inheritance tree, etc.), Representational theory requires the object to be “quantifiable”. However, psychological variables, such as attitude, ability, intelligence cannot be measured directly. For such variables, classical measurement theory can be employed. The classical measurement theory sustained the development of most quantitative theories in psychology [24], [25]. Classical measurement theory merely requires the attribute of the object to be quantifiable, rather than the object itself. Confirmation bias is also a psychological variable and hence it can be inferred from other variables that are directly measured through a mathematical model. Such variables are called “latent” variables. An example of a widely invoked latent variable is the concept of “intelligence”. We cannot measure intelligence directly, however, we can imagine a quality that we call “general intelligence” to make sense of patterns in scores on tests that are believed to measure specific mental abilities [26]. Similarly, we measure confirmation bias through 6 metrics indirectly from the scores and outcomes of our confirmation bias test. Details of the confirmation test are given in Section III-B. III. EMPIRICAL STUDY A. Data Collection In this study, we used datasets from three different projects. In Table I, the total number of maintained/developed files and defect rates are listed for each dataset as well as the total number of developers in each project group. The defect rate is estimated as the ratio of the number of defective files to the number of total active files. All three datasets contain JAVA and JSP files, while dataset Telecom 2 also contains PL/SQL files besides JAVA and JSP files. Datasets Telecom1 and Telecom2 belong to the largest wireless telecom operator (GSM) company in Turkey (the third largest GSM company in Europe). Project group Telecom1 consists of 10 developers who are responsible for the development of a software product that is used to launch new campaigns. On average, 545 java files exist in a single version, and developers make modifications to 206 files per version (also on average). The total number of active files and defect rates, which are listed in Table I for dataset Telecom1 belong to the four versions that were released between the dates 07/02/2009 and 08/13/2009. Telecom1 project group releases a new version of the software product every 10 days on average. Dataset Telecom2 comes from the billing and charging software package, which has been developed and maintained since the inception of the GSM company in 1994. Telecom2 project group consists of 14 developers. In Table I, information about defect rates and total number of active files for project Telecom2 correspond to four versions of the billing and charging software that were released between the dates 03/06/2011 and 05/08/2011. Software release period of project Telecom2 is every month on average. Dataset ERP belongs to a project group that consists of 6 developers who are employees of the largest ISV (independent software vendor) in Turkey. The software developed by this project group is an enterprise resource planning (ERP) software. The snapshot of the ERP software, which dates from March 2011, was retrieved from the version management system in order to estimate the corresponding defect rate and total number of active files as shown in Table I. B. Methodology 1) Preparation of Confirmation Bias Tests: Confirmation bias test consists of written questions and an interactive question. Interactive question is Wason’s Rule Discovery Task itself [19], while written test is based on Wason’s Selection Task [20]. Written test consists of two parts 7 abstract and 7 thematic questions. Abstract questions require logical reasoning skills to be answered correctly, while real life experience and/or memory cueing [27] can help to answer thematic questions correctly. 2) Administration of Confirmation Bias Tests: Initially, we administered confirmation test to a pilot group consisting of 28 Computer Engineering PhD candidates. Half of the participants in the pilot group had at least two years of experience in commercial software product development. The pilot study was followed by the administration of the test to software engineers in various large scale companies and Small Medium Enterprises (SMEs). So far, we have administered the confirmation bias test to 199 software engineers (129 developers, 26 testers, 32 analysts and 12 project managers) from 4 large scale companies and 3 SMEs. In order to collect confirmation bias metrics in a controlled manner, we administered the confirmation bias test, which consists of the interactive question and the written question set, under a predefined standard procedure. The environment where the confirmation bias test was administered was isolated from noise and had adequate lighting. In Wason’s studies related to his selection task, real packs of cards were used. Most recent studies employ different procedures such as describing the cards and the pictorial representations of their visible sides with pencil and paper or on a computer screen. Employing such procedures have made insignificant differences in the results of the experiments [27]. Moreover, it is possible to administer this part of the confirmation bias test to a group of participants (instead of individually). Therefore, we preferred to use the pencil-and-paper approach rather than the traditional approach to administer the part of the confirmation bias test, which is based on Wason’s Selection Task. During the interactive part of the confirmation bias test, each participant answered the question in a separate room, and there was one examiner to guide and give feedback to each participant. Before the whole procedure started, the participants were asked to consent to have their responses recorded during the session. The goal of the voice recording was to catch every detail about the way a participant thought to discover the correct rule. Before starting the test, detailed information was given about the procedure to discover the correct rule. 3) Defining the metric set: We defined the metric set as a natural extension of our previous study [18]. As a result, we obtained a simple and comprehensible metric set that can guide software practitioners while making decisions during the software development process. In Table II, definition of the confirmation bias metrics are given. Ideal and worst-case values for each metric are given in Table III. Ideal value of a metric is among the indications of low confirmation bias and hence it is desirable that a confirmation bias metric is as close to the ideal value as possible. On the other hand, worst-case value of a metric is among the indications of high confirmation bias. 4) Calculation of Group based Metrics Values: In this study, the empirical results are group-based (i.e., the results are based on confirmation bias metrics values of developer groups). We define “developer group” as one or more developer(s) who create/update the same set of source code files. We used “average” operator to calculate group based confirmation bias metrics values. Assuming that \( A_{ji} \) represents the \( j^{th} \) confirmation bias metric value of \( d^{th} \) developer, \( d \in G_j \) means that \( d^{th} \) developer is among the group of developers who created and/or modified \( j^{th} \) source file, and finally, \( S_j^{avg} \) represents the resulting \( j^{th} \) confirmation bias metric value of \( j^{th} \) source file when operator \( avg \) is applied. We can formulate the definition for the “avg” operator as follows: \[ S_j^{avg} = \frac{\sum_{d \in G_j} |\forall d \in G_j|/\Sigma_{d}(1|\forall d \in G_j)} \] IV. EMPIRICAL STUDY RESULTS In this section, we present our proposed metric suite by giving the definition, theoretical basis and empirical results of each metric. As mentioned previously, the empirical results are group-based (i.e., the results are based on confirmation bias metrics values of developer groups). We identified developer groups for each project by mining log files that are obtained from version management systems. Total number of developer groups for each project are given in Table IV. Distribution of developer groups with respect to group size (i.e., total number of developers in a group) are also given in Table IV. In this section, we compare confirmation bias levels of developer groups of Telecom1, Telecom2 and ERP projects by using our proposed metric suite. Our empirical results show that confirmation bias metrics values of developer groups, which belong to projects Telecom2 and ERP are much closer to their corresponding ideal values compared to metrics values of Telecom1 developer groups. As it can be deduced from Table III, metrics \( AbsPartialInsight \) and \( S_{Th} \) are in the range \( 0, 1 \) (i.e., \( 0 \leq AbsPartialInsight \leq 1 \) and \( 0 \leq S_{Th} \leq 1 \)). We also mapped the values of the rest of the metrics to the range \( [0, 1] \) in Figures, where we present percentage distribution of developer groups with respect to each metrics values (i.e., Figures 1, 2, 3, 4, 5 and 6). For this purpose, we divided value of each metric (i.e., \( \text{Ind}_{\text{elim/enum}} \), \( \text{Ind}_{\text{Compatible}} \), \( \text{Rules/Times}_{\text{avgLIR}} \)) by its maximum value (i.e. \( \text{Ind}_{\text{max}}^{\text{elim/enum}} \), \( \text{Ind}_{\text{max}}^{\text{Compatible}} \), \( \text{Rules/Times}_{\text{max}}^{\text{avgLIR}} \)). In Section II-A, we explained the hypothetical relationship between developers’ testing behavior, and Wason’s Rule Discovery and Selection Tasks. In this section, we also explain what type of information each metric may provide us about developers’ unit testing activities, which may lead to an increase in defect rates. In order to investigate the link between confirmation bias and defect rates through testing, we also interviewed with the project managers and developers of Telecom1, Telecom2 and ERP projects. Telecom1 is currently having serious problems with their customers due to high amount of post-release defects. According to the interviews we conducted with developers and project manager of this project group, developers’ testing activities mainly consist of executing the test cases, which were previously prepared as part of the requirements analysis document. Such type of tests can be classified as “positive tests”, since during these tests developers try to validate whether specific parts of the software conform to the corresponding use-cases in the requirements document. After the unit tests, developers perform smoke tests (i.e., simple integration tests where developers just check whether the system under test returns normally and does not blow up when it is invoked). During the interviews, the developers indicated that they employed negative tests only when a new functionality is introduced to the software. Since Telecom1 project group launches a new release every 10 days, new functionalities are rarely introduced to the software. Therefore, tests which focus on “What might go wrong?” (i.e., negative tests) are rarely conducted. Telecom2 and ERP projects have not experienced a software quality-related crisis, that is as serious as the crisis that is currently encountered by Telecom1 project. As it can be seen from the snapshots in Table I, pre-release defect rate of Telecom2 and ERP projects are lower than defect rate of Telecom1 project. Telecom2 and ERP projects are mission critical, since their software products contain modules such as billing, charging and revenue collection. Therefore, it is crucial for developers and project managers of Telecom2 and ERP that the testing strategies they employ are efficient and effective. During the interviews, Telecom2 and ERP project developers indicated that negative tests are important to explore “What might go wrong?”. Negative tests are part of developers’ testing routine in addition to the tests to validate use-cases in the requirements analysis documents. In some cases some negative test scenarios might be overlooked, since such test cases may seem too extreme to be encountered while the software is in use in real life settings. For instance, ERP developers prepared negative test cases where 100-line long bills were generated by the software module. However, problems were later encountered in the field (i.e., in the form of post-release defects), when a client of the ERP company attempted to generate 10000-line long bills. ERP project manager indicated that in order to minimize such incidents, developers take into account such experiences in the past while generating negative test scenarios for the next release of the software. Based on the outcomes of positive and negative tests, addition of new features or refactoring might be required. However, such modifications might not be feasible at the time, since modifications may lead to failures in other parts of the software. ### A. Metric 1: Eliminative/Enumerative Index (\( \text{Ind}_{\text{elim/enum}} \)) 1) Definition: \( \text{Ind}_{\text{elim/enum}} \) metric is extracted from the interactive part of the confirmation bias test. This metric is used to estimate the proportion of the total number of instances that are incompatible with reasons the participant writes down during the interactive test to those that are compatible. 2) Theoretical Basis: The eliminative/enumerative index (\( \text{Ind}_{\text{elim/enum}} \)) was introduced by Wason to evaluate the results of his rule discovery task [19], which forms the basis of the interactive part of confirmation bias test. In his rule discovery task, Wason concluded that participants who announced the correct rule on the first try had higher \( \text{Ind}_{\text{elim/enum}} \) values compared to the rest of the participants. If the value of \( \text{Ind}_{\text{elim/enum}} \) is lower than 1, this implies that participants are more inclined to use triples of numbers (i.e., test cases) that are compatible with their hypotheses. As it was previously indicated by Teasley et al., there is a similarity between software testing and Wason’s rule discovery task [21]. Developers with \( \text{Ind}_{\text{elim/enum}} \) values lower than 1 are more likely to be inclined to select positive test cases to verify their code. This, in turn, leads to an increase in software defect density. On the other hand, effective unit testing can be achieved only by employing negative test scenarios in addition to positive tests. 3) Empirical Data: Percentage distribution of developer groups with respect to \( \text{Ind}_{\text{Elim/Enum}} \) metric values and summary statistics are shown in Figure 1 and Table V for all three projects Telecom1, Telecom2 and ERP. 4) Interpretation of Data: As shown in Figure 1, 41.86% of the developer groups in project Telecom1 have \( \text{Ind}_{\text{elim/enum}} \) value that is in the range \([0, 0.1]\) (i.e., \( \text{Ind}_{\text{Elim/Enum}} \geq 0 \) and \( \text{Ind}_{\text{Elim/Enum}} \leq 0.1 \)). Moreover, the values of the eliminative/ enumerative index is less than 0.5 for 79.07% of the Telecom1 developer groups. Distributions of the \( \text{Ind}_{\text{elim/enum}} \) values among developer groups for the projects Telecom2 and ERP exhibit a tendency towards a more eliminative behavior. The difference among the distributions for all three projects is statistically significant (\( \chi^2(2, N = 77) = 17.4, p = 1E - 6 \)). The value of the \( \text{Ind}_{\text{elim/enum}} \) metric for 71.43% and 61.54% of the developer groups belonging to projects Telecom2 and ERP, respectively is in the range \([0.5, 1]\) (i.e., \( \text{Ind}_{\text{Elim/Enum}} > 0.5 \) and \( \text{Ind}_{\text{Elim/Enum}} \leq 1 \)). ### B. Metric 2: Total Number of Positive and Compatible Instances (\( \text{Ind}_{\text{Compatible}} \)) 1) Definition: \( \text{Ind}_{\text{Compatible}} \) metric value is also extracted from the interactive part of the confirmation bias test. This <table> <thead> <tr> <th>Project (Dataset)</th> <th>Metric</th> <th>Mean_{0.1}</th> <th>Mean</th> <th>Median</th> <th>Max</th> </tr> </thead> <tbody> <tr> <td>Telecom1</td> <td>( \text{Ind}_{\text{elim/enum}} )</td> <td>0.23</td> <td>0.39</td> <td>0.25</td> <td>1.68</td> </tr> <tr> <td>Telecom2</td> <td>( \text{Ind}_{\text{elim/enum}} )</td> <td>0.55</td> <td>0.71</td> <td>0.72</td> <td>3.09</td> </tr> <tr> <td>ERP</td> <td>( \text{Ind}_{\text{elim/enum}} )</td> <td>0.47</td> <td>0.93</td> <td>0.94</td> <td>2.00</td> </tr> </tbody> </table> metric gives the total number of compatible instances given by a participant after (s)he makes an incorrect rule announcement. 2) Theoretical Basis: Giving rules that conform to one or more of the previously announced incorrect rules is an indication of the participant’s lack of tendency to refute the hypotheses in his/her mind even though (s)he has been informed about the incorrectness of these hypotheses (i.e., previously announced rules). In his rule discovery task experiment, Wason also observed that subjects, who failed to find the correct rule on the first announcement, gave examples of triples that are compatible with the rules, which they previously announced [19]. 3) Empirical Data: Percentage distribution of developer groups with respect to InstCompatible metric values and summary statistics are shown in Figure 2 and Table VI for all three projects Telecom1, Telecom2 and ERP. 4) Interpretation of Data: As it can be seen from the percentage distribution of developer groups for the InstCompatible metric in Figure 2, compatible instances are rarely announced by developers that belong to the projects Telecom2 and ERP. There is a statistically significant difference among he three distributions \( \chi^2(2, N = 77) = 18.1, p = 1E - 6 \). The InstCompatible metric values for the 71.43% and 92.31% of developer groups belonging to the projects Telecom2 and ERP are in the range \([0, 0.1]\). On the other hand, only 2.33% of the developer groups that belong to the project Telecom1 have InstCompatible metric values that are in the range \([0, 0.1]\). C. Metric 3: Total Number of Rules Announced per Unit Time (Rules/Time) 1) Definition: The metric Rules/Time measures the Total number of rules announced per unit time during the interactive part of the confirmation bias test. Rules/Time is estimated by dividing the total number of rules announced by the participant (i.e., \( N_a \)) to the total time (in minutes) it takes to complete/terminate the interactive part of the confirmation bias test. 2) Theoretical Basis: In his rule discovery task, Wason used a metric \( N_a \) measure the total number of rules announced by a participant throughout the whole experiment. As one of the outcomes of his rule discovery task, Wason presented a frequency distribution of participants with respect to the total number of rule announcements made [19]. In our research, we introduce the metric Rules/Time by also taking “time” into consideration. A developer having a high Rules/Time value (i.e., a developer who announces high number of rules in a short period of time) as the outcome of the interactive question has the tendency to deliver his/her code to the testing phase without making adequate unit testing. For such a developer, the compilation of his/her code is sufficient. In other words, high Rules/Time is an indication of the developers rush to solve the interactive question correctly, mostly without checking the possibility of the alternative hypotheses in his/her mind by giving instances. 3) Empirical Data: Percentage distribution of developer groups with respect to Rules/Time metric values and summary statistics are shown in Figure 3 and Table VII for all three projects Telecom1, Telecom2 and ERP. 4) Interpretation of Data: There is a statistically significant difference among the distributions of developer groups with respect to the Rules/Time metric values for the three projects Telecom1, Telecom2 and ERP \( (\chi^2(2, N = 77) = 26.7, p = 1E - 6) \). The Rules/Time metric values for the 86.05% of the developer groups belonging to the project Telecom1 are in the range \([0.5, 1]\). On the other hand, the metric values for the 76.19% and 53.85% of the developer groups, which belong to the project groups Telecom2 and ERP, respectively are less than 0.5. 2) Theoretical Basis: In their information processing model, Johnson-Laird and Wason [28] classified the participants' performance on Wason’s selection task as no insight, partial insight and complete insight based on the kinds of systematic errors made by the participants. In their studies, Mataraso-Roth [29] and Evans and Lynch [30] discovered that participants performing at the level of no insight focus on cards mentioned in the rule whose validity is tested. The selection of cards by a participant with no insight might be due to the participants tendency to verify the rule, or (s)he might just match the symbols or words on the cards with those mentioned in the rule. On the other hand, participants performing at the level of partial insight or complete insight consider what symbols or words occur on the back of each card, such participants perform a systematic combinatorial analysis of the cards. The difference between these two performance levels is that the participants having partial insight select all cards that could either verify or falsify the rule, whereas the participants with complete insight select only the cards that have the potential to falsify the rule. Depending on whether the selection task in the written question set is abstract, or thematic, performance of a participant may vary [27]. Participants usually perform poorly on abstract questions [27], [28], since logical reasoning skills are required to solve abstract questions correctly, while in thematic questions memory cueing and real life experience can be helpful while answerung those type of questions [27]. As a result of our analyses, partial insight regarding abstract questions turned out to be the most discriminative measure. Therefore, our metric set only included the metric \( \text{Abs}_{\text{PartialInsight}} \). 3) Empirical Data: Percentage distribution of developer groups with respect to \( \text{Abs}_{\text{PartialInsight}} \) metric values and summary statistics are shown in Figure 4 and Table VIII for all three projects Telecom1, Telecom2 and ERP. 4) Interpretation of Data: As it is shown in Figure 4, the difference in the percentage distribution of the developer groups with respect to the \( \text{Abs}_{\text{PartialInsight}} \) metric values for all three projects (i.e., Telecom1, Telecom2 and ERP) is statistically significant (\( \chi^2(2, N = 77) = 29.3, p = 1E-6 \)). The results obtained are inline with the results that we obtained in our previous study. Developer groups belonging to the projects Telecom2 and ERP performed better than the developer groups belonging to the project Telecom1 in terms of the metric \( \text{Abs}_{\text{PartialInsight}} \). The values for the metric \( \text{Abs}_{\text{PartialInsight}} \) are in the range \([0, 0.1]\) for the 52.38% of the developer groups belonging to the project Telecom2. Moreover, the values of this metric are in the range \([0, 0.5]\) for 80.94% and 61.55% of the developer groups, which belong to the projects Telecom2 and ERP, respectively. On the other hand, the metric values are in the range \([0.5, 1]\) for the developer groups, which belong to the project team Telecom1. E. Metric 5: Score in Thematic Questions (\( S_{\text{Th}} \)) 1) Definition: \( S_{\text{Th}} \) measures the portion of the correctly answered thematic questions in the written part of the confirmation bias test. 2) Theoretical Basis: A participant who has a high \( S_{\text{Th}} \) metric value makes use of the thematic facilitation effects, such as daily life experience or memory queuing in addition to his/her logical reasoning skills. During unit testing, it is likely that In addition to his/her logical reasoning skills, a developer’s expertise about software development will facilitate his/her unit testing activities. 3) Empirical Data: Percentage distribution of developer groups with respect to \( S_{\text{Th}} \) metric values and summary statistics are shown in Figure 5 and Table IX for all three projects Telecom1, Telecom2 and ERP. 4) Interpretation of Data: As it is shown in Figure 5, developer groups that belong to projects Telecom2 and ERP performed better in the thematic part of the written test compared to Telecom1 developer groups. \( S_{\text{Th}} \) metric values for the 42.68% of the Telecom2 developer groups are in the range \([0.6, 0.7]\), whereas the metric values for the 69.23% of the developer groups of the project ERP are in the range \([0.9, 1.0]\). On the other hand, the peak values of the metric \( S_{\text{Th}} \) for the project Telecom1 are at the ranges \([0.4, 0.5]\) and \([0.6, 0.7]\), each corresponding to 23.26% of all developer groups belonging to that project. Moreover, the \([0.5, 1]\) value range of the \( S_{\text{Th}} \) metric corresponds to the 81.40%, 66.67% and 92.30% of the developer groups, which belong to the projects Telecom1, Telecom2 and ERP, respectively. However, the differences among the distributions for the developer groups of Telecom1, Telecom2 and ERP projects did not turn out to be statistically significant at the 0.05 significance level ($\chi^2(2, N = 77) = 5.21, p = 0.074$). **F. Metric 6: Length of Immediate Rule Announcement (avg$L_{IR}$)** 1) **Definition:** $\text{avg$L_{IR}$}$ is the average length of the immediate rule announcements made by a participant during the interactive part of the confirmation bias test. Immediate rule announcements are made consecutively one after another without giving instance(s) in between any two consecutively announced rules. If a participant fails to discover the correct rule after announcing consecutive rules, according to the testing protocol (s)he may start over the whole procedure, which may also end up with a series of consecutively announced rules. This procedure may go on iteratively until the participant announces the correct rule or the interactive session is terminated. Therefore, administration of the interactive test may result in one or more series of consecutively announced rules. $\text{avg$L_{IR}$}$ estimates the average length of consecutively announced rules in all these series. 2) **Theoretical Basis:** Immediate rule announcements are an indication of a participants inadequate hypotheses testing strategies. As a result of such announcements, participants cannot come up with a single rule at the end by eliminating alternative hypotheses in their minds. A develop who makes immediate rule announcements during the interactive part of the test, is likely to exhibit poor unit testing performance. For instance, during functional unit testing equivalence partitioning technique may be referred by the developer. Equivalence partitioning is a non-exhaustive functional testing technique that is applied to each functional unit mostly together with boundary testing. In equivalence partitioning, a set of dimensions of input data are identified for each functional unit, and a set of equivalence classes are identified for each dimension. A developer who makes immediate rule announcements when solving the interactive question is very likely to fail to identify all dimensions of input data to be tested in the functional unit testing. Moreover, (s)he will probably fail to properly determine equivalence classes for each dimension. 3) **Empirical Data:** Percentage distribution of developer groups with respect to $S_{Th}$ metric values and summary statistics are shown in Figure 6 and Table X for all three projects Telecom1, Telecom2 and ERP. 4) **Interpretation of Data:** Majority of the Telecom2 and ERP developer groups made seldom consecutive rule announcements during the interactive part of the test. The values of the metric $\text{avg$L_{IR}$}$ are in the range $[0, 0.1]$ for 58% and 85.71% of Telecom2 and ERP developer groups, respectively. On the other hand, $\text{avg$L_{IR}$}$ metric values are in the range $[0, 0.1]$ only for 23.35% of Telecom1 developer groups. There is a statistically significant difference among the percentage distribution of developer groups with respect to $\text{avg$L_{IR}$}$ metric values for Telecom1, Telecom2 and ERP developer groups ($\chi^2(2, N = 77) = 13.7, p = 0.001$). **G. Discussions** Values of $\text{Ind Elim/Enum}$ and $S_{Th}$ metrics for Telecom1 developer groups are in general lower than those of Telecom2 and ERP developer groups. As mentioned previously, low $\text{Ind Elim/Enum}$ and $S_{Th}$ metrics values are among the indications of high confirmation bias. Moreover, high values for the $\text{IndCompatible}$, $\text{Rules/Time}$, $\text{AbsPartialInsight}$ and $\text{avg$L_{IR}$}$ metrics were observed for Telecom1 developer groups. High values of the metrics $\text{IndCompatible}$, $\text{Rules/Time}$, $\text{AbsPartialInsight}$ and $\text{avg$L_{IR}$}$ are among the indications of high confirmation bias. When we shared our findings with developers and the manager of Telecom1 project, they stated that one rationale behind high amount of post-release defects in their software product is their confirmatory behaviour during testing activities. **V. PRACTICAL IMPLICATIONS** In our previous studies, we defined a methodology to quantify/measure confirmation bias. In this study, we formed a metric set that can be used by software practitioners to improve their software management process and hence quality of the software product. Based on our findings, we make the following recommendations to software practitioners: A. Foreseeing a Major Project Crisis: The metrics in the proposed metric suite can be used to foresee a crisis regarding quality of the software product so that required precautions can be taken on time. For instance, Telecom1 project group is currently having crisis with its customers due to high amount of post-release defects. During the interviews, Telecom1 project group developers and the project manager stated that the problems are due to inadequate testing strategies and the origins of the problem go back to 2-3 years. We administered confirmation bias tests to Telecom1 developers in January 2010. During the period 2010-2011, we administered confirmation bias tests to more project groups. During the analysis of the test outcomes, we observed that confirmation bias levels of Telecom1 developers were significantly higher compared to developers of other project groups [15], [16], [17], [18]. We shared our analysis results with developers and the project manager. Developers and manager of project group Telecom 1 indicated that if necessary precautions had been taken earlier based on our findings, they would not be currently dealing with a software crisis. B. Implementation and Rework Project managers should take into account confirmation bias metrics values besides other factors in order to decide which developer(s) should fix bugs in the most critical parts of the software. Moreover, project managers can use confirmation bias metrics values to prevent contribution of developers having high confirmation biases (i.e., confirmation bias metrics values that are close to worst-case values that are given in Table III) to same set of files that are supposed to be created for the upcoming releases. Information about defect rates introduced by some developer groups during previous releases gives clues about the future performance of such developer groups. However, new members may have been included to the project team and/or some combinations of existing developers may have contributed to same set of files during previous releases (i.e., such developer groups may not have been encountered during previous releases). In such cases, confirmation bias metrics values can guide project managers to decide whether a group of developers should contribute to the same set of files or not. C. Forming a Balanced Project Organization It would not be wise to expect any organization to be created solely with members of low confirmation bias levels (i.e., members with confirmation bias metrics values that are close to the corresponding ideal metric values). It also applies to project teams as dynamic subgroups of the organization under consideration. The project teams (i.e., subgroups) should be balanced with respect to confirmation bias level. Using these metrics as one of the inputs for recruitment is also another option. VI. Threats to Validity In order to avoid mono-method bias that is one of the threats to construct validity, we used more than a single version of a confirmation bias measure. In this current study, we defined metric set to be used by practitioners. To form our confirmation bias metric set, we conducted an extensive survey of the cognitive psychology literature [19], [20], [27], [28], [29]. Another threat to construct validity is the interaction of different treatments. Before the administration of confirmation bias tests to participant groups, we ensured that none of the participants were simultaneously involved in several other experiments designed to have similar effects. Evaluation apprehension is a social threat to construct validity. Many people are anxious about being evaluated. Participants may perform poorly as a result of feeling psychologically pressured. In order to avoid such problems, before the tests we informed the participants that the questions they are about to solve do not aim to measure IQ or any related capability. Participants were also told that the results would not be used in their performance evaluations and their identity would be kept anonymous. Moreover, participants were told that there was no time constraint for completing the questions. Another social threat to construct validity is the expectancies of the researcher. Since, there are many ways a researcher may bias the results of a study. Hence, the outcomes of both written and interactive parts of the test were independently evaluated by two researchers, one of whom was not actively involved in the study. The said researcher was given a tutorial about how to evaluate the confirmation bias metrics from the outcomes of the written question set and the interactive question. However, in order not to induce a bias, she was not told about what the desired answers to the questions were. The inter-rater reliability was found to be high for the evaluation of each confirmation bias metric. The average value for Cohen’s kappa was 0.89. In order to avoid internal threats to validity, we set the test dates for all project groups for a time when the workload of the developers was not intense. No event took place in between the confirmation bias tests that could have influenced the performance of the subjects in any of the groups. For internal validity, we also interviewed with the developers and project managers in order to interpret our empirical results and used the information we obtained through interviews in order to cross-validate the obtained empirical results. To avoid external threats to validity, we collected data from two different companies specialized in two different software development domains. We also selected two different projects within one of these companies. For statistical validity, we used Chi Square test while interpreting the results of our empirical study. VII. Conclusions and Future Work In this study, we proposed a confirmation bias metric set to guide practitioners while making decisions about software development activities. Although, “confirmation bias” is only a single human aspect, the results we have obtained so far are quite promising [27]. Therefore, we strongly recommend that people’s thought processes and other cognitive aspects should be further investigated within the context of software engineering. Existing software metrics deal with the measurement of the software product and process by which it is developed. We believe that people metrics that focus on human thought processes, problem solving skills and other cognitive aspects need to be defined. As future work, we intend to extend our dataset to include 200 more software engineers from SMEs and large scale companies in Canada and Turkey. We also would like to refine our tests to decrease the time and effort required to solve the tests so that they can also be used by practitioners besides serving research-related purposes. In Section II-A, we mentioned the theoretical link between confirmation bias and defect rates through testing activities. As a result of our previous research, we found a correlation between developers’ confirmation biases and defect rates. In this study, besides empirical analyses, we also conducted interviews with developers and project managers in order to find out about actual unit testing performed, the employed testing strategies and how much testing is done by developers. As future work, we aim to conduct observational studies and think aloud protocols in order to further investigate developers’ testing behavior. In the long run, our previous and current research may lead to the design of a training and monitoring program which aims to lower confirmation biases of developers. In cognitive psychology literature, there are de-biasing strategies that are based on recent results in meta-cognition research. Meta-cognitive skills can be taught, however they are not necessarily transferred from one context to another [31]. Therefore, cognitive psychologists and computer scientists must collaborate to design context-specific materials for the training of software professionals. Such a training program can be combined with project performance monitoring in order to be conducted to target groups. In addition to monitoring project performance, improvement in developers, confirmation bias levels can be monitored by using the metrics in our proposed metric scheme. ACKNOWLEDGMENT The authors would like to thank Turkcell A. S. and Ayhan Inal from Logo Business Solutions for their support in sharing data. REFERENCES
{"Source-Url": "http://oro.open.ac.uk/45345/1/ESEM2013.pdf", "len_cl100k_base": 11094, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 37647, "total-output-tokens": 13390, "length": "2e13", "weborganizer": {"__label__adult": 0.0004472732543945313, "__label__art_design": 0.0003402233123779297, "__label__crime_law": 0.0003039836883544922, "__label__education_jobs": 0.0019369125366210935, "__label__entertainment": 6.586313247680664e-05, "__label__fashion_beauty": 0.00017273426055908203, "__label__finance_business": 0.00046181678771972656, "__label__food_dining": 0.00031685829162597656, "__label__games": 0.0006604194641113281, "__label__hardware": 0.0005660057067871094, "__label__health": 0.00047850608825683594, "__label__history": 0.00019443035125732425, "__label__home_hobbies": 8.940696716308594e-05, "__label__industrial": 0.00028586387634277344, "__label__literature": 0.00040531158447265625, "__label__politics": 0.00027632713317871094, "__label__religion": 0.0003662109375, "__label__science_tech": 0.0058135986328125, "__label__social_life": 0.0001291036605834961, "__label__software": 0.00392913818359375, "__label__software_dev": 0.98193359375, "__label__sports_fitness": 0.000308990478515625, "__label__transportation": 0.0004374980926513672, "__label__travel": 0.00017762184143066406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 57732, 0.02302]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 57732, 0.56295]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 57732, 0.91919]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 5408, false], [5408, 11805, null], [11805, 17973, null], [17973, 23425, null], [23425, 30896, null], [30896, 34712, null], [34712, 39697, null], [39697, 44180, null], [44180, 50594, null], [50594, 57732, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 5408, true], [5408, 11805, null], [11805, 17973, null], [17973, 23425, null], [23425, 30896, null], [30896, 34712, null], [34712, 39697, null], [39697, 44180, null], [44180, 50594, null], [50594, 57732, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 57732, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 57732, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 57732, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 57732, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 57732, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 57732, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 57732, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 57732, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 57732, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 57732, null]], "pdf_page_numbers": [[0, 0, 1], [0, 5408, 2], [5408, 11805, 3], [11805, 17973, 4], [17973, 23425, 5], [23425, 30896, 6], [30896, 34712, 7], [34712, 39697, 8], [39697, 44180, 9], [44180, 50594, 10], [50594, 57732, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 57732, 0.03049]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
abaff3affff49430c4fd7eda5903d2aa1d6e4c27
CS 348 Lecture 6 Recursion in SQL, Datalog and SQL Programming Semih Salihoğlu Jan 25th, 2022 Outline For Today 1. SQL Recursive Query Support - Recursion Motivation & FixedPoint Subroutine - WITH and WITH RECURSIVE Clauses - Monotonicity - Linear vs Non-Linear Recursion - Mutual Recursion - Important Note About Convergence of Recursive Queries 2. Datalog: A More Elegant Query Languages For Recursion 3. SQL Programming Strengths and Limitations of SQL So Far Strengths: - Excellent fit for tasks using fundamental set operations: - projection, joins, filtering, grouping etc. and combinations - Very high-level: 1. Declarative: abstracts users away from low-level computations 2. Physical data independence: abstracts away low-level storage Limitations: - Is not Turing-complete - More specifically: Cannot express recursive computations - Historically: Recursion was an afterthought when standardizing SQL Motivating Example 1: Transitive Closure Ex: Given academic <(co-)supervisor, student> relationships: Find all academic ancestors/descendants of an academic <table> <thead> <tr> <th>Advisor</th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td></td> <td>supervisor</td> <td>student</td> </tr> <tr> <td>C1</td> <td>D1</td> <td></td> </tr> <tr> <td>C1</td> <td>D2</td> <td></td> </tr> <tr> <td>C2</td> <td>D1</td> <td></td> </tr> <tr> <td>C2</td> <td>D2</td> <td></td> </tr> <tr> <td>B</td> <td>C1</td> <td></td> </tr> <tr> <td>A</td> <td>B</td> <td></td> </tr> </tbody> </table> Ancestors <table> <thead> <tr> <th></th> <th>anc</th> <th>desc</th> </tr> </thead> <tbody> <tr> <td></td> <td>...</td> <td>...</td> </tr> <tr> <td></td> <td>...</td> <td></td> </tr> <tr> <td></td> <td>...</td> <td></td> </tr> <tr> <td></td> <td>...</td> <td></td> </tr> <tr> <td></td> <td>...</td> <td></td> </tr> </tbody> </table> Diagram: A → B → C1 → D1 → C2 → D2 Ancestors: <table> <thead> <tr> <th></th> <th>anc</th> <th>desc</th> </tr> </thead> <tbody> <tr> <td></td> <td>...</td> <td></td> </tr> <tr> <td></td> <td>...</td> <td></td> </tr> <tr> <td></td> <td>...</td> <td></td> </tr> <tr> <td></td> <td>...</td> <td></td> </tr> <tr> <td></td> <td>...</td> <td></td> </tr> </tbody> </table> Graph: A, B, C1, C2, D1, D2 Motivating Example 1: Transitive Closure - Can find ancestors at any fixed degree, e.g., 1st, 2nd or 4th degree - If max depth d is known: union all possible queries upto degree d: \[ \text{(SELECT * FROM Advisor) UNION (SELECT Adv1.sup, Adv2.stu FROM Adv1,Adv2 WHERE Adv1.stu=Adv2.sup) UNION ... (SQL Query for d-degree ancestors)} \] - But cannot express arbitrary depths Motivating Example 1: Transitive Closure - Historical Fact: killer app of graph DBMSs before relational systems was the “parts explosion query” equivalent transitive closure - Ask me offline if you want to hear more about this history! Motivating Example 2: Shortest Paths - Many other queries builds on top of transitive closure. - Ex: Given flights <from, to, price> relationships: - Find cheapest paths from A to F ### Flights <table> <thead> <tr> <th>from</th> <th>to</th> <th>cost</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>B</td> <td>5</td> </tr> <tr> <td>A</td> <td>C</td> <td>5</td> </tr> <tr> <td>B</td> <td>D</td> <td>10</td> </tr> <tr> <td>C</td> <td>D</td> <td>2</td> </tr> <tr> <td>C</td> <td>E</td> <td>10</td> </tr> <tr> <td>D</td> <td>F</td> <td>5</td> </tr> <tr> <td>F</td> <td>E</td> <td>2</td> </tr> </tbody> </table> Motivating Example 2: Shortest Paths <table> <thead> <tr> <th>Flights</th> </tr> </thead> <tbody> <tr> <td>from</td> </tr> <tr> <td>A</td> </tr> <tr> <td>A</td> </tr> <tr> <td>B</td> </tr> <tr> <td>C</td> </tr> <tr> <td>C</td> </tr> <tr> <td>D</td> </tr> <tr> <td>F</td> </tr> </tbody> </table> - Can find all (shortest) paths with any fixed number, e.g., k, edges - If max depth \( d \) is known (*and (directed) graph is acyclic*) 1. Union all paths with up to \( d \) edges. Call this relation AllPaths: 2. \[\text{SELECT from, to, min(cost) FROM AllPaths}\] - But cannot express arbitrary depths 3-edge Paths Query: \[\text{SELECT F1.from, F3.to, F1.cost+F2.cost+F3.cost as cost}\] \[\text{FROM Flights F1, Flights F2, Flights F3}\] \[\text{WHERE F1.to=F2.from AND F2.to=F3.from}\] Transitive closure (TC) and all paths (or shortest paths which depend on all paths) are inherently recursive properties of graphs Example: TC of v: all nodes that v can directly or indirectly reach Computing them require a recursive computation subroutine: High-level Recursive Subroutine for TC: ``` FixedPoint(fnc F w/ T as input): T_{prev} = ∅ T_{new} = F(T_{prev}) // 1st degree ancestors while (T_{prev} != T_{new}): T_{prev} = T_{new} T_{new} = F(T_{prev}) // compute up to next-degree ancestors ``` Equivalently: Compute T_0 = ∅; T_1 = F(T_0); T_2 = F(T_1); ... until T_i = T_{i+1} Important Questions: 1. When does fp converge? 2. When is it unique? SQL WITH A convenient way to define sub-queries and temporary views WITH R1 AS Q1 R2 AS Q2 ... Rn AS Qn Ri is the result of Qi Ri visible to Ri+1, ..., Rn Can explicitly specify schema as R1(foo, bar) AS Q1 o.w inherits from Q Q // a query that can use existing tables *and* R1, ..., Rn Ex: WITH Deg2Anc AS (SELECT Adv1.sup AS anc, Adv2.stu as desc FROM Advisor Adv1, Advisor Adv2 WHERE Adv1.stu = Adv2.sup) Deg3Anc AS (....) SELECT desc FROM (SELECT * FROM Deg2Anc UNION ... WITH can be suffixed with RECURSIVE keyword WITH RECURSIVE \[ \begin{align*} R_1 & \text{ AS } Q_1 \\ R_2 & \text{ AS } Q_2 \\ \ldots \\ R_n & \text{ AS } Q_n \end{align*} \] Q // a query that can use existing tables *and* R1, ..., Rn Semantics of “RECURSIVE T AS Q”: run FixedPoint subroutine \[ \begin{align*} T_0 &= \emptyset \\ T_1 &= Q \text{ (but use } T_0 \text{ for } T) \\ T_2 &= Q \text{ (but use } T_1 \text{ for } T) \end{align*} \] until } T_i = T_{i+1} Note: In SQL standard RECURSIVE is bound to specific Ri. We will and some systems bound it to WITH, so all Ri. WITH RECURSIVE Ancestors(anc, desc) AS ( SELECT Ancestor.anc, Adv.stu FROM Ancestor, Advisor WHERE Ancestor.desc = Advisor.sup) Problem? Ancestor starts as \(\emptyset\) Common fix: UNION with a 2nd query that inits Ancestor to Advisor Common WITH RECURSIVE query template: WITH RECURSIVE R AS ( Q UNION Q ) WITH RECURSIVE Ancestors(anc, desc) AS ( SELECT sup as anc, stu as desc FROM Advisor UNION SELECT Ancestor.anc, Adv.stu FROM Ancestor, Advisor WHERE Ancestor.desc = Advisor.sup) Ancestor_0 = [A, B] Q_B = Ancestor_0 \times Advisor Q_R = Ancestor_0 \cup Q_B Is Ancestor_1 = Ancestor_0 \? No: Repeat TC: ATTEMPT 2: Union w/ a “Base” Case All 1-degree ancestors Ancestor_2 = Q_R = Anc_1 \bowtie Advisor Is Anc_2 – Ans_1 = \emptyset? No: Repeat TC: ATTEMPT 2: Union w/ a “Base” Case <table> <thead> <tr> <th>Anc₂</th> <th></th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>anc</td> <td>desc</td> <td>anc</td> <td>desc</td> <td></td> </tr> <tr> <td>C1</td> <td>D1</td> <td>A</td> <td>C1</td> <td></td> </tr> <tr> <td>C1</td> <td>D2</td> <td>B</td> <td>D1</td> <td></td> </tr> <tr> <td>C2</td> <td>D1</td> <td></td> <td></td> <td></td> </tr> <tr> <td>C2</td> <td>D2</td> <td></td> <td></td> <td></td> </tr> <tr> <td>B</td> <td>C1</td> <td></td> <td></td> <td></td> </tr> <tr> <td>A</td> <td>B</td> <td></td> <td></td> <td></td> </tr> </tbody> </table> All 1- and 2-degree ancestors Advisor <table> <thead> <tr> <th>sup</th> <th>stu</th> </tr> </thead> <tbody> <tr> <td>C1</td> <td>D1</td> </tr> <tr> <td>C1</td> <td>D2</td> </tr> <tr> <td>C2</td> <td>D1</td> </tr> <tr> <td>C2</td> <td>D2</td> </tr> <tr> <td>B</td> <td>C1</td> </tr> <tr> <td>A</td> <td>B</td> </tr> </tbody> </table> Qₐₐₛₚ = Anc₂ ⋈ Advisor Ancestor₃ = <table> <thead> <tr> <th>QB</th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>anc</td> <td>desc</td> <td></td> </tr> <tr> <td>C1</td> <td>D1</td> <td></td> </tr> <tr> <td>C1</td> <td>D2</td> <td></td> </tr> <tr> <td>C2</td> <td>D1</td> <td></td> </tr> <tr> <td>C2</td> <td>D2</td> <td></td> </tr> <tr> <td>B</td> <td>C1</td> <td></td> </tr> <tr> <td>A</td> <td>B</td> <td></td> </tr> </tbody> </table> <table> <thead> <tr> <th>QR</th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>anc</td> <td>desc</td> <td></td> </tr> <tr> <td>A</td> <td>C1</td> <td></td> </tr> <tr> <td>B</td> <td>D1</td> <td></td> </tr> <tr> <td>A</td> <td>D1</td> <td></td> </tr> <tr> <td>A</td> <td>D2</td> <td></td> </tr> </tbody> </table> <table> <thead> <tr> <th>Anc₃</th> <th></th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>anc</td> <td>desc</td> <td>anc</td> <td>desc</td> <td></td> </tr> <tr> <td>C1</td> <td>D1</td> <td>A</td> <td>C1</td> <td></td> </tr> <tr> <td>C1</td> <td>D2</td> <td>B</td> <td>D1</td> <td></td> </tr> <tr> <td>C2</td> <td>D1</td> <td></td> <td></td> <td></td> </tr> <tr> <td>C2</td> <td>D2</td> <td></td> <td></td> <td></td> </tr> <tr> <td>B</td> <td>C1</td> <td></td> <td></td> <td></td> </tr> <tr> <td>A</td> <td>B</td> <td></td> <td></td> <td></td> </tr> </tbody> </table> Is Anc₃ – Ans₂ = ∅? No: Repeat TC: ATTEMPT 2: Union w/ a “Base” Case All 1-, 2-, and 3-degree ancestors \[ \text{Q}_R = \text{Anc}_3 \bowtie \text{Advisor} \] Ancestor_4 = \[ \text{Is Anc}_4 - \text{Ans}_3 = \emptyset? \] Yes: Stop Final Answer called the fixed point of Q. Recall common WITH RECURSIVE query template: ```sql WITH RECURSIVE R AS (Q_B UNION Q_R) ``` Can use other queries/templates (e.g., multiple base cases) - But some restrictions apply (stay tuned) Note that fixed-point computation was very well-behaved in TC: - Computation converged: - In finite steps (and computed a finite relation) - No oscillations Question: Are there conditions that guarantee convergence to a unique fixed point of Q? Monotonicity - If we focus on core relational algebra foundation of SQL: - Select/project/cross product/join/union/set difference/intersection - Ignore group by and aggregations and arithmetic functions etc. - Theorem: If a recursive Q is “monotone w.r.t to every relation it contains”, then Q has a unique and finite fixed point (i.e., the fixed point subroutine is guaranteed to converge) - Definition: Q is monotone w.r.t R iff adding more tuples to R can not remove tuples from output of Q (but new tuples can appear) - i.e., if each t that used to be in the output of Q is guaranteed to remain in output if add more tuples to R (keeping all else same) Monotonicity - Recall each core RA operator except set difference is monotone w.r.t their arguments - E.g.: $R \bowtie_p S$ is monotone w.r.t $R$ and $S$ - But: $R - S$ is non-monotone w.r.t $S$ - Therefore: Any Q that uses core relational algebraic operations and does not use set difference is monotone => Q will converge to a unique fixed point (if recursive) - Note: Q can still be monotone even if it contains set difference. But not guaranteed to be. Why Does Monotonicity Guarantee A Unique Fixed Point For A Recursive Query? Proof Sketch: Recall fixed point subroutine: \[ T_0 = \emptyset; \ T_1 = Q \ (\text{but use } T_0 \text{ for } T); \ T_2 = Q \ (\text{but use } T_1 \text{ for } T) \] \[ \ldots \] Note we are assuming we are focusing on core RA: - Each value in a column of \( T_i \) is from a value from base relation - But a base relation in \( Q \) is finite Any relation, no matter what its schema is, has a finite maximum size. B/c \( Q \) is monotone (specifically w.r.t to \( T \)): \[ T_1 \subset T_2 \subset T_3 \subset \ldots \] (must stop b/c finiteness) i.e. \( T_1 \subset T_2 \subset \ldots T_k = T_{k+1} \) (and fp stops) <table> <thead> <tr> <th>Anc_4</th> <th>Advisor</th> </tr> </thead> <tbody> <tr> <td>( \text{anc} )</td> <td>( \text{desc} )</td> </tr> <tr> <td>C1</td> <td>D1</td> </tr> <tr> <td>C1</td> <td>D2</td> </tr> <tr> <td>C2</td> <td>D1</td> </tr> <tr> <td>C2</td> <td>D2</td> </tr> <tr> <td>B</td> <td>C1</td> </tr> <tr> <td>A</td> <td>B</td> </tr> </tbody> </table> Example Non-Monotone Recursive Query 1 WITH RECURSIVE \( T(x) \) AS ( SELECT x FROM R UNION SELECT sum(x) as x FROM T ) \( R \) <table> <thead> <tr> <th>( x )</th> </tr> </thead> <tbody> <tr> <td>1</td> </tr> <tr> <td>2</td> </tr> </tbody> </table> \( T \) \( T_0 \) <table> <thead> <tr> <th>( x )</th> </tr> </thead> <tbody> <tr> <td>1</td> </tr> <tr> <td>2</td> </tr> </tbody> </table> \( T_1 \) <table> <thead> <tr> <th>( x )</th> </tr> </thead> <tbody> <tr> <td>1</td> </tr> <tr> <td>2</td> </tr> </tbody> </table> \( T_2 \) <table> <thead> <tr> <th>( x )</th> </tr> </thead> <tbody> <tr> <td>1</td> </tr> <tr> <td>2</td> </tr> </tbody> </table> \( T_3 \) <table> <thead> <tr> <th>( x )</th> </tr> </thead> <tbody> <tr> <td>1</td> </tr> <tr> <td>2</td> </tr> </tbody> </table> \( T_4 \) <table> <thead> <tr> <th>( x )</th> </tr> </thead> <tbody> <tr> <td>1</td> </tr> <tr> <td>2</td> </tr> </tbody> </table> \( \cdots \) would never converge - Q is non-monotone b/c as we added 3, 3 got deleted, as we added 6, 6 got deleted etc. - That’s why aggr. not allowed in recursive queries in SQL standard. A 2\( \text{nd} \) example after we cover “mutual recursion” (stay tuned). Recall $Q_R$ in transitive closure: SELECT Ancestor.anc, Adv.stu FROM Ancestor, Advisor WHERE Ancestor.desc = Advisor.sup Has 1 reference to itself Ancestor: Called *linear recursion* Can have > 1 reference to Ancestor, called *non-linear recursion* WITH RECURSIVE Ancestors(anc, desc) AS ( SELECT sup as anc, stu as desc FROM Advisor UNION SELECT Anc1.anc, Anct.desc FROM Ancestor Anc1, Ancestor Anc2 WHERE Ac1.desc = Anc2.anc) Non-linear Recursive Computation of Ancestors <table> <thead> <tr> <th>Anc_1</th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>anc</td> <td>desc</td> <td></td> </tr> <tr> <td>1</td> <td>2</td> <td></td> </tr> <tr> <td>2</td> <td>3</td> <td></td> </tr> <tr> <td>3</td> <td>4</td> <td></td> </tr> <tr> <td>4</td> <td>5</td> <td></td> </tr> <tr> <td>5</td> <td>6</td> <td></td> </tr> <tr> <td>6</td> <td>7</td> <td></td> </tr> <tr> <td>7</td> <td>8</td> <td></td> </tr> </tbody> </table> All 1-degree ancestors <table> <thead> <tr> <th>Advisor</th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>sup</td> <td>stu</td> <td></td> </tr> <tr> <td>1</td> <td>2</td> <td></td> </tr> <tr> <td>2</td> <td>3</td> <td></td> </tr> <tr> <td>3</td> <td>4</td> <td></td> </tr> <tr> <td>4</td> <td>5</td> <td></td> </tr> <tr> <td>5</td> <td>6</td> <td></td> </tr> <tr> <td>6</td> <td>7</td> <td></td> </tr> <tr> <td>7</td> <td>8</td> <td></td> </tr> </tbody> </table> <table> <thead> <tr> <th>Q_B</th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>anc</td> <td>desc</td> <td></td> </tr> <tr> <td>1</td> <td>2</td> <td></td> </tr> <tr> <td>2</td> <td>3</td> <td></td> </tr> <tr> <td>3</td> <td>4</td> <td></td> </tr> <tr> <td>4</td> <td>5</td> <td></td> </tr> <tr> <td>5</td> <td>6</td> <td></td> </tr> <tr> <td>6</td> <td>7</td> <td></td> </tr> <tr> <td>7</td> <td>8</td> <td></td> </tr> </tbody> </table> <table> <thead> <tr> <th>Q_R</th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>anc</td> <td>desc</td> <td></td> </tr> <tr> <td>1</td> <td>3</td> <td></td> </tr> <tr> <td>2</td> <td>4</td> <td></td> </tr> <tr> <td>3</td> <td>5</td> <td></td> </tr> <tr> <td>4</td> <td>6</td> <td></td> </tr> <tr> <td>5</td> <td>7</td> <td></td> </tr> <tr> <td>6</td> <td>8</td> <td></td> </tr> </tbody> </table> ∪ <table> <thead> <tr> <th>Anc_2</th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>anc</td> <td>desc</td> <td>anc</td> </tr> <tr> <td>1</td> <td>2</td> <td>1</td> </tr> <tr> <td>2</td> <td>3</td> <td>2</td> </tr> <tr> <td>3</td> <td>4</td> <td>3</td> </tr> <tr> <td>4</td> <td>5</td> <td>4</td> </tr> <tr> <td>5</td> <td>6</td> <td>5</td> </tr> <tr> <td>6</td> <td>7</td> <td>6</td> </tr> <tr> <td>7</td> <td>8</td> <td></td> </tr> </tbody> </table> ### Non-linear Recursive Computation of Ancestors #### $\text{Anc}_2$ <table> <thead> <tr> <th>anc</th> <th>desc</th> <th>anc</th> <th>desc</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2</td> <td>1</td> <td>3</td> </tr> <tr> <td>2</td> <td>3</td> <td>2</td> <td>4</td> </tr> <tr> <td>3</td> <td>4</td> <td>3</td> <td>5</td> </tr> <tr> <td>4</td> <td>5</td> <td>4</td> <td>6</td> </tr> <tr> <td>5</td> <td>6</td> <td>5</td> <td>7</td> </tr> <tr> <td>6</td> <td>7</td> <td>6</td> <td>8</td> </tr> <tr> <td>7</td> <td>8</td> <td></td> <td></td> </tr> </tbody> </table> All 1 and 2-degree ancestors #### $\text{Q}_B$ <table> <thead> <tr> <th>anc</th> <th>desc</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2</td> </tr> <tr> <td>2</td> <td>3</td> </tr> <tr> <td>3</td> <td>4</td> </tr> <tr> <td>4</td> <td>5</td> </tr> <tr> <td>5</td> <td>6</td> </tr> <tr> <td>6</td> <td>7</td> </tr> <tr> <td>7</td> <td>8</td> </tr> </tbody> </table> #### $\text{Q}_R$ <table> <thead> <tr> <th>anc</th> <th>desc</th> <th>anc</th> <th>desc</th> <th>anc</th> <th>desc</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>3</td> <td>2</td> <td>5</td> <td>4</td> <td>8</td> </tr> <tr> <td>2</td> <td>4</td> <td>3</td> <td>6</td> <td></td> <td></td> </tr> <tr> <td>3</td> <td>5</td> <td>4</td> <td>7</td> <td></td> <td></td> </tr> <tr> <td>4</td> <td>6</td> <td>5</td> <td>8</td> <td></td> <td></td> </tr> <tr> <td>5</td> <td>7</td> <td>1</td> <td>5</td> <td></td> <td></td> </tr> <tr> <td>6</td> <td>8</td> <td>2</td> <td>6</td> <td></td> <td></td> </tr> <tr> <td>1</td> <td>4</td> <td>3</td> <td>7</td> <td></td> <td></td> </tr> </tbody> </table> $\bigcup$ #### $\text{Anc}_3$ <table> <thead> <tr> <th>a</th> <th>d</th> <th>a</th> <th>d</th> <th>a</th> <th>d</th> <th>a</th> <th>d</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2</td> <td>1</td> <td>3</td> <td>2</td> <td>5</td> <td>4</td> <td>8</td> </tr> <tr> <td>2</td> <td>3</td> <td>2</td> <td>4</td> <td>3</td> <td>6</td> <td></td> <td></td> </tr> <tr> <td>3</td> <td>4</td> <td>3</td> <td>5</td> <td>4</td> <td>7</td> <td></td> <td></td> </tr> <tr> <td>4</td> <td>5</td> <td>4</td> <td>6</td> <td>5</td> <td>8</td> <td></td> <td></td> </tr> <tr> <td>5</td> <td>6</td> <td>5</td> <td>7</td> <td>1</td> <td>5</td> <td></td> <td></td> </tr> <tr> <td>6</td> <td>7</td> <td>6</td> <td>8</td> <td>2</td> <td>6</td> <td></td> <td></td> </tr> <tr> <td>7</td> <td>8</td> <td>1</td> <td>4</td> <td>3</td> <td>7</td> <td></td> <td></td> </tr> </tbody> </table> = Non-linear Recursive Computation of Ancestors All 1, 2, 3, and 4-degree ancestors <table> <thead> <tr> <th>Anc₃</th> <th>Advisor</th> </tr> </thead> <tbody> <tr> <td>a d</td> <td>sup</td> </tr> <tr> <td>a d</td> <td>stu</td> </tr> <tr> <td>a d</td> <td>1</td> </tr> <tr> <td>a d</td> <td>2</td> </tr> <tr> <td>a d</td> <td>3</td> </tr> <tr> <td>a d</td> <td>4</td> </tr> <tr> <td>a d</td> <td>5</td> </tr> <tr> <td>a d</td> <td>6</td> </tr> <tr> <td>a d</td> <td>7</td> </tr> <tr> <td>a d</td> <td>8</td> </tr> </tbody> </table> <table> <thead> <tr> <th>Q_B</th> <th>Q_R</th> <th>Anc₄</th> </tr> </thead> <tbody> <tr> <td>anc</td> <td>desc</td> <td>a d</td> </tr> <tr> <td>1</td> <td>2</td> <td>1</td> </tr> <tr> <td>2</td> <td>3</td> <td>2</td> </tr> <tr> <td>3</td> <td>4</td> <td>3</td> </tr> <tr> <td>4</td> <td>5</td> <td>4</td> </tr> <tr> <td>5</td> <td>6</td> <td>5</td> </tr> <tr> <td>6</td> <td>7</td> <td>6</td> </tr> <tr> <td>7</td> <td>8</td> <td>7</td> </tr> </tbody> </table> <table> <thead> <tr> <th></th> <th>a d</th> <th>a d</th> <th>a d</th> <th>a d</th> <th>a d</th> <th>a d</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <td>2</td> <td>2</td> <td>2</td> <td>2</td> <td>2</td> <td>2</td> <td>2</td> </tr> <tr> <td>3</td> <td>3</td> <td>3</td> <td>3</td> <td>3</td> <td>3</td> <td>3</td> </tr> <tr> <td>4</td> <td>4</td> <td>4</td> <td>4</td> <td>4</td> <td>4</td> <td>4</td> </tr> <tr> <td>5</td> <td>5</td> <td>5</td> <td>5</td> <td>5</td> <td>5</td> <td>5</td> </tr> <tr> <td>6</td> <td>6</td> <td>6</td> <td>6</td> <td>6</td> <td>6</td> <td>6</td> </tr> <tr> <td>7</td> <td>7</td> <td>7</td> <td>7</td> <td>7</td> <td>7</td> <td>7</td> </tr> </tbody> </table> \[ \bigcup \] Non-linear Recursive Computation of Ancestors \[ \text{Anc}_4 \] \[ \begin{array}{cccccccc} \text{a} & \text{d} & \text{a} & \text{d} & \text{a} & \text{d} & \text{a} & \text{d} \\ 1 & 2 & 1 & 3 & 2 & 5 & 4 & 8 \\ 2 & 3 & 2 & 4 & 3 & 6 & 1 & 6 \\ 3 & 4 & 3 & 5 & 4 & 7 & 2 & 7 \\ 4 & 5 & 4 & 6 & 5 & 8 & 3 & 8 \\ 5 & 6 & 5 & 7 & 1 & 5 & 1 & 7 \\ 6 & 7 & 6 & 8 & 2 & 6 & 2 & 8 \\ 7 & 8 & 1 & 4 & 3 & 7 & 1 & 8 \\ \end{array} \] All 1, … 8-degree ancestors \[ \text{Q}_B \] \[ \begin{array}{cc} \text{anc} & \text{desc} \\ 1 & 2 \\ 2 & 3 \\ 3 & 4 \\ 4 & 5 \\ 5 & 6 \\ 6 & 7 \\ 7 & 8 \\ \end{array} \] \[ \text{Q}_R \] \[ \begin{array}{cccccccc} \text{a} & \text{d} & \text{a} & \text{d} & \text{a} & \text{d} & \text{a} & \text{d} \\ 1 & 3 & 2 & 5 & 4 & 8 \\ 2 & 4 & 3 & 6 & 1 & 6 \\ 3 & 5 & 4 & 7 & 2 & 7 \\ 4 & 6 & 5 & 8 & 3 & 8 \\ 5 & 7 & 1 & 5 & 1 & 7 \\ 6 & 8 & 2 & 6 & 2 & 8 \\ 1 & 4 & 3 & 7 & 1 & 8 \\ \end{array} \] \[ \text{Anc}_5 \] \[ \begin{array}{cccccccc} \text{a} & \text{d} & \text{a} & \text{d} & \text{a} & \text{d} & \text{a} & \text{d} \\ 1 & 2 & 1 & 3 & 2 & 5 & 4 & 8 \\ 2 & 3 & 2 & 4 & 3 & 6 & 1 & 6 \\ 3 & 4 & 3 & 5 & 4 & 7 & 2 & 7 \\ 4 & 5 & 4 & 6 & 5 & 8 & 3 & 8 \\ 5 & 6 & 5 & 7 & 1 & 5 & 1 & 7 \\ 6 & 7 & 6 & 8 & 2 & 6 & 2 & 8 \\ 7 & 8 & 1 & 4 & 3 & 7 & 1 & 8 \\ \end{array} \] Is \( \text{Anc}_5 - \text{Ans}_4 = \emptyset \)? Yes: Stop Fixed Point Linear recursion would take 8 steps Linear vs Non-linear Recursion - For tc-like computations: - Linear recursion: - Takes *linear* # iterations in the depth of the relationships - But each iteration might perform less work b/c joins are between smaller tables - Non-linear recursion: - Takes logarithmic # iterations in the same depth - But each iteration performs more work - SQL standard requires/allows linear recursion for performance reasons Mutual Recursion - Each Qi in our examples so far referred to itself. - We can have the following “mutually recursive” set of queries \[ \text{WITH RECURSIVE} \] \[ \text{RECURSIVE R1 AS Q1} \quad \text{e.g. references R2} \] \[ \text{RECURSIVE R2 AS Q2} \quad \text{e.g. references R3} \] \[ \text{RECURSIVE R3 AS Q3} \quad \text{e.g. references R1} \] - No query alone is recursive but Q1, Q2, Q3 together is recursive - So they need to be executed “in tandem” until fixed point. Mutual Recursion Example Table *Natural* (*n*) contains 1 Even/Odd numbers < 100 WITH RECURSIVE Even(n) AS (SELECT n FROM Natural WHERE n = ANY(SELECT n+1 FROM Odd) AND n < 100), Odd(n) AS ( (SELECT n FROM Natural WHERE n = 1) UNION (SELECT n FROM Natural WHERE n = ANY(SELECT n+1 FROM Even) AND n < 100) Even\(_0\) = \(\emptyset\),\nOdd\(_0\) = \(\emptyset\) Even\(_1\) = \(\emptyset\),\nOdd\(_1\) = \(\{1\}\) Even\(_2\) = \(\{2\}\),\nOdd\(_2\) = \(\{1\}\) Even\(_3\) = \(\{2\}\),\nOdd\(_3\) = \(\{1, 3\}\) Even\(_4\) = \(\{2, 4\}\),\nOdd\(_4\) = \(\{1, 3\}\) Even\(_5\) = \(\{2, 4\}\),\nOdd\(_5\) = \(\{1, 3, 5\}\) ... Example Non-Monotone Recursive Query 2: Set Difference WITH RECURSIVE PGroup(uid) AS (SELECT uid FROM User AND uid NOT IN (SELECT uid FROM SGroup)), RECURSIVE SGroup(uid) AS (SELECT uid FROM User AND uid NOT IN (SELECT uid FROM PGroup)) <table> <thead> <tr> <th>uid</th> <th>name</th> <th>age</th> </tr> </thead> <tbody> <tr> <td>142</td> <td>Bart</td> <td>10</td> </tr> <tr> <td>121</td> <td>Allison</td> <td>8</td> </tr> </tbody> </table> MINUS can replace with AND uid NOT IN. In general negated sub-queries or MINUS in recursive parts are not allowed. Q is non-monotone b/c recall set diff. is nonmonotone w.r.t 2nd arg. Important Note On Monotonicity/Convergence - In practice: DBMSs will not/cannot check for monotonicity and may allow much more than SQL standard: arithmetic, aggregations. - Nor will they detect oscillations - You can write non-converging code. Systems will often run a max # iterations (e.g., 100) and error - SQL compiler will not error for these errors. This is on the user! - Be careful with recursive queries: Know your query & database! Consider this All Paths query Q: ```sql WITH RECURSIVE AllPaths(s, d, cost) AS (SELECT s, d, cost FROM Edges) UNION (SELECT AllPaths.s, Edges.d, AllPaths.cost+Edges.cost FROM AllPaths, Edges WHERE AllPaths.d = Edges.s) ``` - If Edges \{ (1, 2, 10) \} => All Paths: \{ (1, 2, 10) \} - Keep Q the same but add one more tuple (2, 1, 5) to Edges - Now there are infinitely many (1, 2) and (2, 1) paths: \( (1, 2, 10), (1, 2, 25), (1, 2, 40) \) etc.. Systems will allow this query! Summary of SQL Recursion - Recursion did not exist from 1986-1999 in SQL Standard - General Syntax: WITH RECURSIVE \[R_1 \text{ AS } Q_1\] \[R_2 \text{ AS } Q_2\] \[...\] \[R_n \text{ AS } Q_n\] - Basic functionality: linear recursion - Extended functionality: non-linear and mutual recursion - Unsafe recursive queries: non-monotone (may not converge) queries or query is monotone but output relation’s size is infinite (e.g., due to use of arithmetic) - Personal opinion: Recursive computations are not elegant in SQL. A QL based on logical rules of the form: \( \text{Head} := \text{Body} \) A DB consists of a set of “base relations” (called “extensional” db) - \( \text{Likes(person, foodItem)} \) - \( \text{Sells(restaurant, foodItem, cost)} \) - \( \text{Frequents(person, restaurant)} \) Ex Rule: \( \text{Happy(p)} := \text{Likes(p, f), Frequents(p, r), Sells(r, f, c)} \) - Head - Body: conjunction/AND of “subgoals” For simplicity: assume head, subgoals can be relation names (called predicates) with arguments that can be variables or constants. Datalog allows other predicates: e.g., \( c < 20 \) Semantics of Datalog Rules - Happy(p) := Likes(p, f), Frequents(p, r), Sells(r, f, c) - Natural join on common variables: - Any p s.t. ”∃ a food f & rest r | p likes f & p frequents r & r sells f” is happy - In RA: $\Pi_{\text{person}} (\text{Likes} \bowtie \text{Frequents} \bowtie \text{Sells})$ - Equality filters on constants: - Happy(p) := Likes(p, f), Frequents(p, r), Sells(r, f, 20) - Any p s.t. ”∃ a food f & rest r | p likes f & p frequents r & r sells f & x costs 20 CAD” is happy - Note: also declarative More “Datalog Program” Examples - There can be multiple rules with the same head predicate Happy(p) := Likes(p, f), Frequents(p, r), Sells(r, f, c) Happy(p) := Likes(p, “Chocolate Cake”) Happy(p) := Frequents(p, r), Frequents(“Karim”, r) - Meaning: Any p s.t: 1) “∃ a food f & rest r | p likes f & p frequents r & r sells f” OR 2) “p likes Chocolate Cake” OR 3) “∃ a restaurant r | both Karim and p frequent r” is happy! - Advantage: Arbitrary recursive, non-recursive, mutually recursive rules can be just written down as logical “derivation” rules More Elegant Recursive Programs Example 1: Transitive Closure: Ancestor(a, d) := Advisor(a, d) Ancestor(a, d) := Ancestor(a, b), Advisor(b, d) Example 2: Shortest Paths: AllPaths(a, d, cost) := Edge(a, d, cost) AllPaths(a, d, totalCost) := AllPaths(a, k, cost1), Edge(k, d, cost2), \[ \text{totalCost} = \text{cost1} + \text{cost2} \] ShortestPaths(a, d, min(cost)) := AllPaths(a, k, cost) - Can be done in SQL WITH RECURSIVE but don’t need to think about any recursive execution. - Syntax forces one to focus on logical derivation rules for relations. Given a Datalog program that satisfy some properties (specifically some monotonicity and finiteness rules as before): \[ R_1 := \text{body 1 (possibly recursive)} \] \[ R_2 := \text{body 2 (possibly recursive)} \] \[ \ldots \] \[ R_2 := \text{body 7 (possibly recursive)} \] \[ \ldots \] \[ R_k := \text{body 1000 (possibly recursive)} \] Apply rules in arbitrary order to generate new tuples and one always converges to same unique fixed-point => i.e., the order of execution does not matter If you want: run \( R_1 := \text{body 1} \) 500 times if it keeps producing new tuples; then run \( R_2 := \text{body 2} \), then \( \text{Rj} \), then \( R_1 \) again etc. Several DBMSs, e.g., recent LogicBlox or LinkedIn’s core graph DBMS, adopts Datalog as a query language instead of SQL. Better fit for apps requiring recursion and logical inference rules (e.g., in knowledge management and traditional AI applications): \[ \text{Sibling}(x, y) := \text{BioParent}(z, x), \text{BioParent}(z, y), x \neq y \] Many cool applications have been developed on Datalog: (e.g., declarative distributed network programming) - See Peter Alvaro’s work from UC Santa Cruz - Has been the foundation for many seminal theoretical results Challenge of using SQL on a real app: - Not intended for general-purpose computation Solutions - Augment SQL with constructs from general-purpose programming languages - E.g.: SQL/PSM - Use SQL together with general-purpose programming languages: many possibilities - Through an API, e.g., Python psycopg2 - Embedded SQL, e.g., in C - SQL generating approaches: Web Programming Frameworks (e.g., Django) 1) Augmenting SQL: SQL/PSM - An ISO standard to extend SQL to an advanced prog. lang. - Control flow, exception handling, etc. - Several systems adopt SQL/PSM partially (e.g. MySQL, PostgreSQL) - PSM = Persistent Stored Modules CREATE PROCEDURE proc_name(param_decls) local_decls proc_body; CREATE FUNCTION func_name(param_decls) RETURNS return_type local_decls func_body; CALL proc_name(params); Inside procedure body: SET variable = CALL func_name(params); CREATE FUNCTION SetMaxPop(IN newMaxPop FLOAT) RETURNS INT -- Enforce newMaxPop; return # rows modified. BEGIN DECLARE rowsUpdated INT DEFAULT 0; DECLARE thisPop FLOAT; -- A cursor to range over all users: DECLARE userCursor CURSOR FOR SELECT pop FROM User FOR UPDATE; -- Set a flag upon “not found” exception: DECLARE noMoreRows INT DEFAULT 0; DECLARE CONTINUE HANDLER FOR NOT FOUND SET noMoreRows = 1; ... (see next slide) ... END RETURN rowsUpdated; -- Fetch the first result row: OPEN userCursor; FETCH FROM userCursor INTO thisPop; -- Loop over all result rows: WHILE noMoreRows <> 1 DO IF thisPop > newMaxPop THEN -- Enforce newMaxPop: UPDATE User SET pop = newMaxPop WHERE CURRENT OF userCursor; END IF; -- Update count: SET rowsUpdated = rowsUpdated + 1; END IF; -- Fetch the next result row: FETCH FROM userCursor INTO thisPop; END WHILE; CLOSE userCursor; Other SQL/PSM Features - Assignment using scalar query results - SELECT INTO - Other loop constructs - FOR, REPEAT UNTIL, LOOP - Flow control - GOTO - Exceptions - SIGNAL, RESIGNAL - ... - For more PostgreSQL-specific information, look for “PL/pgSQL” in PostgreSQL documentation 2) Working with SQL through an API - E.g.: Python psycopg2, JDBC, ODBC (C/C++/VB) - Based on the SQL/CLI (Call-Level Interface) standard - The application program sends SQL commands to the DBMS at runtime. Gets back a “cursor” that can iterate over results. - Results are converted to objects in the application program. Often you use a cursor to loop through result tuples. import psycopg2 conn = psycopg2.connect(dbname='beers') cur = conn.cursor() # list all drinkers: cur.execute('SELECT * FROM Drinker') for drinker, address in cur: print(drinker + ' lives at ' + address) # print menu for bars whose name contains "a": cur.execute('SELECT * FROM Serves WHERE bar LIKE %s', ('%a%',)) for bar, beer, price in cur: print('{} serves {} at {:.2f}'.format(bar, beer, price)) cur.close() conn.close() # “commit” each change immediately—need to set this option just once at the start of the session conn.set_session(autocommit=True) bar = input('Enter the bar to update: ').strip() beer = input('Enter the beer to update: ').strip() price = float(input('Enter the new price: ')) try: cur.execute(''' UPDATE Serves SET price = %s WHERE bar = %s AND beer = %s''', (price, bar, beer)) if cur.rowcount != 1: print('{} row(s) updated: correct bar/beer?\n'.format(cur.rowcount)) except Exception as e: print(e) Perform passing, semantic analysis, optimization, compilation, and finally execution while true: # Input bar, beer, price... cur.execute(''' UPDATE Serves SET price = %s WHERE bar = %s AND beer = %s''', (price, bar, beer)) # Check result... Perform passing, semantic analysis, optimization, compilation, and finally execution Execute many times Can we reduce this overhead? Prepared Statements: Example cur.execute(''" # Prepare once (in SQL) PREPARE update_price AS # Name the prepared plan, UPDATE Serves SET price = $1 # and note the $1, $2, ... notation for WHERE bar = $2 AND beer = $3"") # parameter placeholders. while true: # Input bar, beer, price... cur.execute('' EXECUTE update_price(%s, %s, %s), (price, bar, beer)).... # Check result... Watch Out For SQL Injection Attacks! The school probably had something like: ```python cur.execute("SELECT * FROM Students \ WHERE (name = " + name + ")") ``` where `name` is a string input by user Called an SQL injection attack. Most APIs have ways to sanitize inputs. Augmenting SQL vs. Programming Through an API Pros of augmenting SQL: - More processing features for DBMS - More application logic can be pushed closer to data Cons of augmenting SQL: - SQL is already too big - Complicate optimization and make it impossible to guarantee safety 3) “Embedding” SQL in a host language - Can be thought of as the opposite of SQL/PSM - Extends a host language, e.g., C or Java, with SQL-based features - Can compile host language together with SQL statements and catch SQL errors during *application compilation time* 4) Web Programming Frameworks - A web development “framework” e.g., Django or Ruby on Rails - Very frequent approach to web apps that need a DB - For most parts, no explicitly writing SQL is needed: - Example: Django Web App Programming: - Define “Models”: python objects and only do oo programming - Models will be backed up with Relations in an RDBMS - E.g.: a Person class/object with first and lastName: ```python from django.db import models class Person(models.Model): f_name = models.CharField(max_len=30) l_name = models.CharField(max_len=30) ``` Would lead the “framework” (not the user) to generate the following SQL code somewhere in the web application files: ```sql CREATE TABLE myapp_person ( "id" serial NOT NULL PRIMARY KEY, "f_name" varchar(30) NOT NULL, "l_name" varchar(30) NOT NULL ) ``` Thank You
{"Source-Url": "https://student.cs.uwaterloo.ca/~cs348/slides/06-sql-partIV-slides.pdf", "len_cl100k_base": 12487, "olmocr-version": "0.1.53", "pdf-total-pages": 55, "total-fallback-pages": 0, "total-input-tokens": 90826, "total-output-tokens": 12749, "length": "2e13", "weborganizer": {"__label__adult": 0.0002810955047607422, "__label__art_design": 0.00024259090423583984, "__label__crime_law": 0.00022029876708984375, "__label__education_jobs": 0.002986907958984375, "__label__entertainment": 6.198883056640625e-05, "__label__fashion_beauty": 0.00010281801223754884, "__label__finance_business": 0.00020766258239746096, "__label__food_dining": 0.0003497600555419922, "__label__games": 0.0004189014434814453, "__label__hardware": 0.0005030632019042969, "__label__health": 0.0003750324249267578, "__label__history": 0.00020956993103027344, "__label__home_hobbies": 0.00010073184967041016, "__label__industrial": 0.0003757476806640625, "__label__literature": 0.00022995471954345703, "__label__politics": 0.00015974044799804688, "__label__religion": 0.0003898143768310547, "__label__science_tech": 0.00977325439453125, "__label__social_life": 9.98377799987793e-05, "__label__software": 0.00998687744140625, "__label__software_dev": 0.97216796875, "__label__sports_fitness": 0.0001970529556274414, "__label__transportation": 0.0003781318664550781, "__label__travel": 0.0001729726791381836}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 29517, 0.03814]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 29517, 0.01818]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 29517, 0.76345]], "google_gemma-3-12b-it_contains_pii": [[0, 97, false], [97, 447, null], [447, 945, null], [945, 1742, null], [1742, 2119, null], [2119, 2356, null], [2356, 2753, null], [2753, 3529, null], [3529, 4204, null], [4204, 4689, null], [4689, 5274, null], [5274, 5620, null], [5620, 5952, null], [5952, 6099, null], [6099, 7081, null], [7081, 7330, null], [7330, 7780, null], [7780, 8446, null], [8446, 8910, null], [8910, 9887, null], [9887, 10552, null], [10552, 10805, null], [10805, 11008, null], [11008, 12444, null], [12444, 13846, null], [13846, 14941, null], [14941, 16365, null], [16365, 16800, null], [16800, 17288, null], [17288, 18000, null], [18000, 18528, null], [18528, 18972, null], [18972, 19476, null], [19476, 20019, null], [20019, 20615, null], [20615, 21152, null], [21152, 21730, null], [21730, 22292, null], [22292, 22961, null], [22961, 23520, null], [23520, 23931, null], [23931, 24412, null], [24412, 24874, null], [24874, 25308, null], [25308, 25654, null], [25654, 26035, null], [26035, 26471, null], [26471, 27094, null], [27094, 27398, null], [27398, 27837, null], [27837, 28111, null], [28111, 28395, null], [28395, 28665, null], [28665, 29508, null], [29508, 29517, null]], "google_gemma-3-12b-it_is_public_document": [[0, 97, true], [97, 447, null], [447, 945, null], [945, 1742, null], [1742, 2119, null], [2119, 2356, null], [2356, 2753, null], [2753, 3529, null], [3529, 4204, null], [4204, 4689, null], [4689, 5274, null], [5274, 5620, null], [5620, 5952, null], [5952, 6099, null], [6099, 7081, null], [7081, 7330, null], [7330, 7780, null], [7780, 8446, null], [8446, 8910, null], [8910, 9887, null], [9887, 10552, null], [10552, 10805, null], [10805, 11008, null], [11008, 12444, null], [12444, 13846, null], [13846, 14941, null], [14941, 16365, null], [16365, 16800, null], [16800, 17288, null], [17288, 18000, null], [18000, 18528, null], [18528, 18972, null], [18972, 19476, null], [19476, 20019, null], [20019, 20615, null], [20615, 21152, null], [21152, 21730, null], [21730, 22292, null], [22292, 22961, null], [22961, 23520, null], [23520, 23931, null], [23931, 24412, null], [24412, 24874, null], [24874, 25308, null], [25308, 25654, null], [25654, 26035, null], [26035, 26471, null], [26471, 27094, null], [27094, 27398, null], [27398, 27837, null], [27837, 28111, null], [28111, 28395, null], [28395, 28665, null], [28665, 29508, null], [29508, 29517, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 29517, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 29517, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 29517, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 29517, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 29517, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 29517, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 29517, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 29517, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 29517, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 29517, null]], "pdf_page_numbers": [[0, 97, 1], [97, 447, 2], [447, 945, 3], [945, 1742, 4], [1742, 2119, 5], [2119, 2356, 6], [2356, 2753, 7], [2753, 3529, 8], [3529, 4204, 9], [4204, 4689, 10], [4689, 5274, 11], [5274, 5620, 12], [5620, 5952, 13], [5952, 6099, 14], [6099, 7081, 15], [7081, 7330, 16], [7330, 7780, 17], [7780, 8446, 18], [8446, 8910, 19], [8910, 9887, 20], [9887, 10552, 21], [10552, 10805, 22], [10805, 11008, 23], [11008, 12444, 24], [12444, 13846, 25], [13846, 14941, 26], [14941, 16365, 27], [16365, 16800, 28], [16800, 17288, 29], [17288, 18000, 30], [18000, 18528, 31], [18528, 18972, 32], [18972, 19476, 33], [19476, 20019, 34], [20019, 20615, 35], [20615, 21152, 36], [21152, 21730, 37], [21730, 22292, 38], [22292, 22961, 39], [22961, 23520, 40], [23520, 23931, 41], [23931, 24412, 42], [24412, 24874, 43], [24874, 25308, 44], [25308, 25654, 45], [25654, 26035, 46], [26035, 26471, 47], [26471, 27094, 48], [27094, 27398, 49], [27398, 27837, 50], [27837, 28111, 51], [28111, 28395, 52], [28395, 28665, 53], [28665, 29508, 54], [29508, 29517, 55]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 29517, 0.28047]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
64fadd1c724e39c9f1b83071951c044b2834f83a
Deep Just-in-Time Defect Prediction: How Far Are We? Zhengran Zeng Southern University of Science and Technology China 12032889@mail.sustech.edu.cn Yuqun Zhang∗ Southern University of Science and Technology China zhangyq@sustech.edu.cn Haotian Zhang Kwai Inc. China zhanghaotian@kuaishou.com Lingming Zhang University of Illinois Urbana-Champaign United States lingming@illinois.edu ABSTRACT Defect prediction aims to automatically identify potential defective code with minimal human intervention and has been widely studied in the literature. Just-in-Time (JIT) defect prediction focuses on program changes rather than whole programs, and has been widely adopted in continuous testing. CC2Vec, state-of-the-art JIT defect prediction tool, first constructs a hierarchical attention network (HAN) to learn distributed vector representations of both code additions and deletions, and then concatenates them with two other embedding vectors representing commit messages and overall code changes extracted by the existing DeepJIT approach to train a model for predicting whether a given commit is defective. Although CC2Vec has been shown to be the state of the art for JIT defect prediction, it was only evaluated on a limited dataset and not compared with all representative baselines. Therefore, to further investigate the efficacy and limitations of CC2Vec, this paper performs an extensive study of CC2Vec on a large-scale dataset with over 310,370 changes (8.3 X larger than the original CC2Vec dataset). More specifically, we also empirically compare CC2Vec against DeepJIT and representative traditional JIT defect prediction techniques. The experimental results show that CC2Vec cannot consistently outperform DeepJIT, and neither of them can consistently outperform traditional JIT defect prediction. We also investigate the impact of individual traditional defect prediction features and find that the added-line-number feature outperforms other traditional features. Inspired by this finding, we construct a simplistic JIT defect prediction approach which simply adopts the added-line-number feature with the logistic regression classifier. Surprisingly, such a simplistic approach can outperform CC2Vec and DeepJIT in defect prediction, and can be 81k X/120k X faster in training/testing. Furthermore, the paper also provides various practical guidelines for advancing JIT defect prediction in the near future. CCS CONCEPTS • Software and its engineering → Software defect analysis. ∗Yuqun Zhang is the corresponding author. Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. Copyrights for components of this work owned by others than ACM must be honored. Abstracting with credit is permitted. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. Request permissions from permissions@acm.org. © 2021 Association for Computing Machinery. ACM ISBN 978-1-4503-8459-9/21/07... 1 INTRODUCTION Software development nowadays has been increasingly involved with rapidly changing requirements, diverse and evolving infrastructures, and fierce peer pressure among developers, all of which together can raise intense time and resource constraints on software quality assurance tasks. Therefore, it is essential to identify program defects as early as possible such that developers/testers can focus on specific program scopes to reduce the overall testing and debugging time and efforts. To this end, Just-in-Time (JIT) defect prediction approaches have been proposed [32] to provide early predictions about likely program defects during software evolution. In particular, compared with traditional defect prediction approaches which mainly operate at the file or module level [10, 27, 45, 46], JIT defect prediction approaches work at the fine-grained code-change level to provide precise hints about potential defects. Among the existing general-purpose JIT defect prediction approaches, CC2Vec, proposed at ICSE’20 [19], has been demonstrated to be the state of the art. CC2Vec basically learns the vector representations for code additions and deletions, and then integrates that with the previous DeepJIT approach [18] to construct a deep neural network for JIT defect prediction. More specifically, CC2Vec first applies a hierarchical attention network (HAN) [51] to deliver the distributed vector representations of both code additions and deletions. Meanwhile, the previous DeepJIT approach is leveraged to obtain two embedding vectors representing commit messages and overall code changes via convolutional neural networks (CNNs) [25]. Next, the resulting vectors of CC2Vec and DeepJIT are concatenated and input to a fully-connected network for final defect prediction. Taking two open-source projects with a total of 37k commits (with 3.6k defects), CC2Vec can outperform DeepJIT by over 7% in terms of the AUC score. Meanwhile, despite its advanced design, the effectiveness of CC2Vec is still unclear because (1) CC2Vec was only evaluated upon a limited dataset with marginal improvements (i.e., around 7% in terms of the AUC [26] score) against the previous state-of-the-art approach DeepJIT; (2) CC2Vec is built on deep neural networks and thus relies on training data quality; and (3) there is no comprehensive comparison between CC2Vec (or DeepJIT) and other representative traditional approaches. Therefore, in this paper, to fully understand the efficacy and limitations of the general-purpose deep-learning-based JIT defect prediction approaches, we construct a large-scale dataset by extending the original one to include the latest program versions and introducing additional popular open-source projects. As a result, we collect 310k commits from six well-known open-source projects. To the best of our knowledge, this is so far the largest evaluation in the literature on general-purpose deep-learning-based JIT defect prediction. The experimental results show that overall the performance of DeepJIT and CC2Vec can be replicated on their original dataset. However, surprisingly, the GitHub version of DeepJIT, which abstracts all the detailed code changes into simple labels (i.e., “added_code/removed_code”), performs better than the DeepJIT version described in the original DeepJIT paper, which leverages the detailed code-change information. This indicates that feeding detailed information into machine learning models does not always help with JIT defect prediction. Our experimental results on the extended dataset further show that CC2Vec fails to outperform DeepJIT under most studied projects. Also, we find that neither DeepJIT nor CC2Vec can consistently outperform traditional JIT defect prediction on all the studied projects under either within-project or cross-project prediction scenarios. Therefore, we further investigate how different popular traditional defect prediction features can impact the performance of JIT defect prediction. Importantly, the experimental results show that the added-line-number feature (which simply computes the number of added lines of code in each commit) can provide the higher prediction accuracy than all other studied features. At last, inspired by the findings of our study, we construct a simplistic and fast approach, LApredict, which simply adopts the added-line-number feature with the traditional logistic regression classifier for JIT defect prediction. We also compare LApredict with all the studied approaches on top of the extended dataset under both within-project and cross-project scenarios. Surprisingly, the results show that LApredict can outperform CC2Vec and all other existing approaches for most cases in JIT defect prediction, and can be 81k X/120k X faster than CC2Vec in training/testing. Furthermore, the superiority of LApredict is even enlarged in cross-project validation. Accordingly, our study also reveal various practical guidelines for how to further advance JIT defect prediction in the near future. In summary, this paper makes the following contributions. - **Dataset.** An extensive dataset with 310k commits, collected from all program versions of six popular projects over the last 10 years. Such a dataset provides not only a much larger amount of real-world software defects but also their distributions over a larger time span, which can potentially benefit and impact all future JIT defect prediction research. - **Study.** An extensive study of state-of-the-art general-purpose JIT defect prediction approaches (CC2Vec and DeepJIT) on the proposed extended dataset, with detailed quantitative and qualitative analysis on their strengths and limitations. - **Technique.** A simplistic and fast approach, LApredict, which simply adopts the added-line-number feature with the traditional logistic regression classifier instead of building complex deep neural networks for JIT defect prediction. --- **Implications.** An empirical evaluation of LApredict, state-of-the-art CC2Vec and DeepJIT, and two other representative JIT defect prediction approaches, indicating that simplistic/traditional approaches/features can easily outperform the advanced deep-learning-based approaches and be 81kX/120kX faster in training/testing. The paper also reveals various practical guidelines for future JIT defect prediction. The replication package for this paper, including all our data, source code, and documentation, is publicly available online at: https://github.com/ZZR0/ISSTA21-JIT-DP --- ### 2 BACKGROUND #### 2.1 Deep JIT Defect Prediction: Example In this section, we present a defective commit (commit b032a5) and its fixing commit (commit 6db280) of project Gerrit [2] in Figure 1 to demonstrate the challenges of JIT defect prediction. Specifically in commit b032a5, the developer replaced a database request operation with a parameter passed from JGit, e.g., “db.getAllRefs()” (Line 107) is replaced with variable “refs”. It was until two years later when the developers discovered that commit b032a5 introduced an issue that “refs” and “db.getAllRefs()” are not always equivalent, i.e., “db.getAllRefs()” returns the whole “Refs” object of “db” while “refs” can only return partial “Refs” object. --- #### Figure 1: An illustrative example Figure 2: The overall framework of CC2Vec + DeepJIT Therefore, commit 6db280 was further made to replace "refs" back with "db.getAllRepos()". From the example, we can observe that the defect refers to an only one-line discrepancy of the source code between the two commits, which can be rather challenging to predict automatically. Many existing approaches perform JIT defect prediction based on classic features (e.g., the number of modified files and the file size) and traditional machine learning techniques (e.g., logistic regression [12]). However, traditional techniques can hardly learn useful information for all possible cases, e.g., simply extracting the traditional syntactic features for comparative analysis can hardly work for this example with a single-line change. Intuitively, to identify such defects, it is helpful to understand their specific program semantics, e.g., investigating program control/data flows. However, such analysis can be rather challenging for complex programs and involve intensive manual efforts. Therefore, recently, researchers have leveraged deep learning models to learn more useful semantic information for precise JIT defect prediction [18, 19]. For example, the deep learning models can potentially learn from other historical defects that the change in commit b032a5 can be dangerous. 2.2 State-of-the-Art CC2Vec Figure 2 presents the overall neural network structure for CC2Vec [19]. Specifically, as the state-of-the-art general-purpose JIT defect prediction approach, CC2Vec constructs a hierarchical attention network (HAN) [51] to embed added and deleted code of each changed file associated with one given commit respectively. Specifically, the adopted HAN first builds vector representations for lines, and further uses them to build vector representations of hunks. At last, such hunk vector representations are aggregated to construct the embedding vectors corresponding to the added or removed code. CC2Vec further adopts multiple comparison functions to capture the difference between the derived embedding vectors of the added and removed code for exploring their relationship, where each comparison function can produce a vector. Next, all the resulting vectors are concatenated into one embedding vector to represent the file-level added/removed code changes. Eventually, all the embedding vectors associated with all the changed files under one commit are aggregated as the distributed vector representations of the code additions and deletions. In addition, CC2Vec also adopts a previous JIT defect prediction approach, DeepJIT [18], to strengthen the prediction efficacy. DeepJIT constructs two convolutional neural networks (CNNs) [25] to extract the features of (1) commit messages and (2) overall code changes of a given commit. Note that, the DeepJIT code-change feature extraction is totally different from CC2Vec and can be complementary: DeepJIT simply aggregates added/removed code as one single input, and thus ignores the distributed information between code additions and deletions considered by CC2Vec (which treats added/removed code as two different inputs for HAN). Eventually, all the vectors derived by CC2Vec and DeepJIT are input to a fully-connected layer for computing the likelihood that the given commit incurs a defect. Although CC2Vec attempts to leverage the semantic information out of code changes for facilitating the JIT defect prediction efficacy, the adopted input information is still limited, i.e., only the textual code changes and their associated commit messages are considered. On the other hand, there is no detailed exploration for validating the actual contributions of different adopted components. Moreover, the study of CC2Vec only considers two open-source projects QT [3] and OpenStack [4] with a total of 37k commits. Such a dataset may be too limited to demonstrate the generalizability and scalability of CC2Vec. Lastly, the program versions of the adopted projects are a bit outdated, i.e., QT contains data from June 2011 to March 2014 while OpenStack contains data from November 2011 to February 2014, making the evaluation incapable of demonstrating whether the findings vary over time since no recent data are included. 3 STUDY ON DEEP JIT DEFECT PREDICTION As discussed in Section 2.2, state-of-the-art CC2Vec was only evaluated upon a limited dataset against DeepJIT. Therefore, it is essential to extend the efficacy evaluation of CC2Vec (and DeepJIT) to a more diverse and larger dataset with more representative baseline approaches to thoroughly understand deep JIT defect prediction. 3.1 Dataset Collection In general, we attempt to collect influential open-source projects for conducting our study. In particular, since one of our study tasks is to replicate the evaluations of CC2Vec, we first retain all the projects used in the evaluations of the original CC2Vec paper, i.e., QT and OpenStack. Next, we choose to extend the existing dataset by including the projects which are not only influential but also diverse from the existing ones. To this end, we also adopt Eclipse JDT and Platform [1], which have been widely adopted by prior defect prediction work [20, 21, 49] and are programmed mainly in Java (while QT and OpenStack are mainly in C++). Moreover, we also include project Gerrit [2], a professional code review tool which has been adopted by many commercial and open-source projects for their code review process [53]. Lastly, we select project Go [3] for our study since it is a representative and popular modern programming language. In this way, we have a diverse set of real-world projects in different programming languages. Furthermore, for each studied project, we collect all its code commits between 2011-01-01 and 2020-12-01 (which subsumes the time range covered by the CC2Vec dataset) to explore how JIT defect prediction results vary across time. Specifically, following prior work [18, 19, 31], we apply the widely-used SZZ algorithm [22, 41] to identify the defective commits. First, we identify defect-fixing commits by analyzing their commit messages. Next, we locate the modified lines of the defect-fixing commits using the Diff command. Furthermore, we use the Blame command to detect the commits inducing the modified lines as defective commits. Meanwhile, following prior work [31], all other commits unmarked by the SZZ algorithm will be treated as the correct instances for training-testing. At last, we filter such commits based on the procedure by Kim et al. [22] and McIntosh et al. [31] to remove whitespace commits, comment commits, merged commits, and other suspicious commits. Note that we also eliminate the authentication latency issue [6] by following prior work [6, 31, 42], e.g., we remove recent data according to Column “Median Defect Fix Delay (days)” in Table 1, which represents the median time interval for the defect from appearance to be fixed. The reason is that many defects from recent data have not been fully detected/fixed yet, and may affect our study. Finally, we obtain a dataset with six projects and 310,370 total real-world commits including 81,300 defects, enabling an extensive evaluation and study of CC2Vec. Table 1 presents the detailed dataset statistics. To the best of our knowledge, this is the largest dataset for general-purpose deep-learning-based JIT defect prediction. 3.2 Research Questions We investigate the following research questions for studying CC2Vec: - **RQ1**: Why do DeepJIT and CC2Vec work? For this RQ, we explore what makes the deep learning models effective in JIT defect prediction. In particular, we reproduce the experiments in the DeepJIT [18] and CC2Vec [19] papers and conduct a more detailed analysis of their adopted input components than the original papers, including exploring each input component’s contribution to the overall models. - **RQ2**: How do DeepJIT and CC2Vec perform on the extended dataset? For this RQ, we conduct an extensive study for the performance comparison between CC2Vec, DeepJIT, and other representative traditional JIT defect prediction approaches upon the extended dataset. We also investigate not only the AUC score adopted in the original study, but also other widely used metrics for prediction effectiveness. - **RQ3**: How do traditional defect prediction features perform for JIT defect prediction? For this RQ, we adopt the features widely used in traditional JIT defect prediction and investigate their respective performance impact. - **RQ4**: Can a simplistic approach without deep learning outperform DeepJIT/CC2Vec for JIT defect prediction? For this RQ, we attempt to design/implement a simplistic but effective JIT defect prediction approach without deep learning. ### Table 1: Dataset statistics <table> <thead> <tr> <th>Project</th> <th># Changes</th> <th>% Defect</th> <th>Median Defect Fix Delay (days)</th> <th>Language</th> </tr> </thead> <tbody> <tr> <td>QT</td> <td>95758</td> <td>15.16</td> <td>526.29</td> <td>C++</td> </tr> <tr> <td>OpenStack</td> <td>66065</td> <td>31.68</td> <td>280.06</td> <td>C++</td> </tr> <tr> <td>JDT</td> <td>13348</td> <td>41.20</td> <td>251.28</td> <td>Java</td> </tr> <tr> <td>Platform</td> <td>39365</td> <td>37.74</td> <td>75.01</td> <td>Java</td> </tr> <tr> <td>Gerrit</td> <td>34610</td> <td>8.64</td> <td>294.58</td> <td>Java</td> </tr> <tr> <td>Go</td> <td>61224</td> <td>36.75</td> <td>243.21</td> <td>Golang</td> </tr> </tbody> </table> Commit Id: “0041b2267144f215fee996c4c99773e8550d8527b” Message: “remove qalgorithms usage from qt designer…” - **Code Change**: Array 0: "added__code__removed__code" 1: "added__code__removed__code" 2: "added__code__removed__code" 3: "added__code__removed__code" 4: "added__code__removed__code" 5: "added__code__removed__code" 6: "added__code__removed__code" Figure 3: DeepJIT example with abstracted code changes 3.3 Results and Analysis 3.3.1 RQ1: Why Do DeepJIT and CC2Vec Work? For this RQ, we replicate the experiments on DeepJIT and CC2Vec under exactly the same setting and dataset of their original papers [18, 19]. We also explore how the three different inputs of CC2Vec (the DeepJIT code-change vector, the DeepJIT commit-message vector, and the CC2Vec code-change vector) impact JIT defect prediction. Note that after carefully inspecting the source code provided by the DeepJIT and CC2Vec GitHub pages, we find that instead of using the vector representations of detailed code changes as declared in the original DeepJIT paper, DeepJIT and the DeepJIT component in CC2Vec actually abstract each changed file within one commit into a simple "added_code/removed_code" label (with a maximum of 10 labels for each commit), as shown in Figure 3. Therefore, we also collect the vector representations of the detailed code changes according to the original DeepJIT paper and implement them for both DeepJIT and the DeepJIT component in CC2Vec. Eventually, we end up with a complete replication study on DeepJIT and CC2Vec by involving not only reusing the provided source code on GitHub but also reimplementing their original versions described in the original papers (i.e., we modify the "added_code/removed_code" labels back to the detailed source code they represent for DeepJIT). Table 2 shows our reproduced experimental results in terms of AUC scores. Note that considering the model randomness, we run all our experiments for 16 runs as recommended by prior work [36], and present the mean, min, max, and standard deviation values across all 16 runs. In the table, DeepJIT GitHub refers to the DeepJIT version using the "added_code/removed_code" labels (i.e., consistent with the original DeepJIT implementation on GitHub) and DeepJIT Paper refers to the DeepJIT version vectorizing the detailed given code changes (i.e., consistent with the original DeepJIT paper description). Also, we denote DeepJIT GitHub + CC2Vec as CC2Vec GitHub, denote DeepJIT Paper + CC2Vec as CC2Vec Paper. We can observe that in general, the original experimental results can be replicated. For example, the Mean AUC score is 0.7705 for DeepJIT GitHub and 0.7841 for DeepJIT GitHub + CC2Vec in our reproduced results, while they were 0.7595 and 0.8155, respectively, in the original papers. Interestingly, the standard deviations of 16 identical runs are less than 0.0030 and the differences between the minimum and maximum AUC values are no greater than 0.0094 for all the replicated techniques. We have similar findings for all our subsequent experiments. Therefore, due to such rather stable results, we only show the experimental results for one run for all our subsequent experiments. Note that considering the randomness in the 5-fold cross validation process used by the original papers and the discrepancies on the execution environments, such performance discrepancies can be tolerated and neglected. DeepJIT code-change vector effectiveness. We can further observe that the performance of DeepJIT\textsubscript{GitHub} is slightly better than DeepJIT\textsubscript{Paper}. For instance, 0.7959 vs. 0.7724 on QT and 0.7452 vs. 0.7152 on OpenStack. We also have similar observations for DeepJIT\textsubscript{GitHub} + CC2Vec and DeepJIT\textsubscript{Paper} + CC2Vec (0.8118 vs. 0.7788 on QT and 0.7564 vs. 0.7378 on OpenStack). Such observations indicate that the "added_code/removed_code" labels, which are literally simply the number of changed files, can outperform the detailed code-change vectors described in the original DeepJIT paper for JIT defect prediction. This finding is rather surprising to us, as it implies that while the power of the code-change semantics can be leveraged by deep learning techniques, a simple traditional feature (e.g., the number of changed files) can be more helpful in JIT defect prediction! Note that based on such experimental results, for all the following studies, we would apply DeepJIT\textsubscript{GitHub} and its associated combinations with CC2Vec, as DeepJIT\textsubscript{GitHub} not only performs better but also was the version used to produce the experimental results in the original CC2Vec and DeepJIT papers. DeepJIT commit-message vector effectiveness. Next, we attempt to infer how the commit messages can advance the performance of DeepJIT and CC2Vec. In particular, we use the Grad-CAM (Class Activation Mapping) algorithm \cite{GradCAM} which is widely used for visual analysis of neural network model inputs. In particular, since the last layer of the cumulative convolution layer in a CNN model contains the richest spatial and semantic information, the Grad-CAM algorithm can weight and sum the last layer feature maps of the CNN model to deliver the contribution of each word to the model’s output. Accordingly, we can derive which words in the commit messages significantly impact the model’s prediction results. For instance, Figure 4a demonstrates a true positive example where DeepJIT derives that it is 80.39% a defect. Then, we calculate each word’s contribution to the predicted results using the Grad-CAM algorithm and mark them under colors, where darker colors indicate more significant contributions of the associated words. We can observe that “task-number” and “qbug-27968” make the largest contributions to the prediction result. In QT, “task-number” is always followed by a task ID which indicates this commit may be a bug fix or a feature commit. Actually, many previous studies \cite{Selectivity, Selectivity2} have found that fixing a bug or adding a new feature is likely to result in a bug. Therefore, we can infer that DeepJIT identifies “task-number” and “qbug-27968” to be useful and highlight their impact for defect prediction. We can also strengthen such finding via the other two examples from Figure 4b and Figure 4c, where “task-number” in Figure 4b and “fixes” in Figure 4c cause the examples to be classified as defective. We further derive the impact rank of the words (which appear more than once in QT and OpenStack) on the defect prediction results according to their average Grad-CAM scores. Table 3 presents the results of the words we consider to be relevant to the intents of their associated programs. We can observe that although some of them, e.g., “task-number” in QT and “failures” in OpenStack, rank relatively high, the others’ rankings are rather less distinctive. Such results indicate that while DeepJIT can identify the importance of the words associated with the program intents under certain circumstances, its overall effectiveness can be nevertheless compromised by many other words, making the contributions of the commit-message feature somewhat limited. CC2Vec code-change vector effectiveness. Furthermore, we attempt to investigate the effect posed by the code-change vectors extracted by CC2Vec. Specifically, CC2Vec is designed to leverage its HAN model structure to extract code-change semantics information to further boost DeepJIT. However, we can observe that DeepJIT + CC2Vec only leads to limited performance improvement over DeepJIT, i.e., 1.99% and 1.50% on QT and OpenStack, respectively. From such results, we can infer that the code-change semantics information extracted by CC2Vec may have limited effectiveness for JIT defect prediction, and will further verify it in our extended experimental settings (Section 3.3.2). Ablation study. At last, we attempt to investigate the impact of each individual feature input adopted by CC2Vec. To this end, we choose to adopt/remove only one DeepJIT/CC2Vec input feature at a time to train the deep JIT model for evaluating their respective effectiveness, as presented in Table 4. In the table, CC2Vec\textsubscript{Code}, DeepJIT\textsubscript{Code}, and DeepJIT\textsubscript{Msg} represent the CC2Vec code-change input, the DeepJIT code-change input, and the DeepJIT commit-message input, respectively. The last three rows present the results ### Table 2: Replication study results for DeepJIT and CC2Vec <table> <thead> <tr> <th>Feature Type</th> <th>QT</th> <th>OpenStack</th> </tr> </thead> <tbody> <tr> <td></td> <td>Mean</td> <td>Min</td> </tr> <tr> <td>DeepJIT\textsubscript{GitHub}</td> <td>.7959</td> <td>.7940</td> </tr> <tr> <td>DeepJIT\textsubscript{Paper}</td> <td>.7724</td> <td>.7683</td> </tr> <tr> <td>CC2Vec\textsubscript{GitHub}</td> <td>.8118</td> <td>.8106</td> </tr> <tr> <td>CC2Vec\textsubscript{Paper}</td> <td>.7788</td> <td>.7780</td> </tr> </tbody> </table> ### Table 3: Word rank by contribution <table> <thead> <tr> <th>Rank</th> <th>QT</th> <th>Word</th> <th>OpenStack</th> <th>Word</th> </tr> </thead> <tbody> <tr> <td>18</td> <td>task-number</td> <td>39</td> <td>failures</td> <td>693</td> </tr> <tr> <td>443</td> <td>fix</td> <td>96</td> <td>resolves</td> <td>474</td> </tr> <tr> <td>532</td> <td>bug</td> <td>474</td> <td>fail</td> <td></td> </tr> <tr> <td>643</td> <td>failures</td> <td>693</td> <td>bugs</td> <td></td> </tr> </tbody> </table> Finding 1: The performance of DeepJIT and CC2Vec can overall be replicated on the originally adopted benchmark projects (QT and OpenStack). Interestingly, the two DeepJIT versions perform differently: the GitHub version which abstracts detailed code changes (DeepJIT\textsubscript{GitHub}) outperforms the original-paper version which leverages the detailed code-change semantics (DeepJIT\textsubscript{Paper}) on both two studied projects. Finding 2: DeepJIT and CC2Vec can extract the intent of code changes from commit messages to assist defect prediction under certain circumstances. when removing each of the three feature inputs, e.g., ł-CC2Vecł AUC of CC2Vec can observe that using individual inputs can reduce the prediction accuracy in terms of the AUC scores. For example, the average AUC of CC2Vec, DeepJIT, and DeepJIT, respectively. On the other hand, for the remaining three studied projects, DeepJIT can even outperform CC2Vec by 0.56% to 1.29%. Since CC2Vec only differs from DeepJIT by including additional code-change vector representations, such performance deviation can indicate that the code-change vector representation extracted by CC2Vec does not generalize its advantages over the original DeepJIT features to diverse datasets, indicating CC2Vec’s limited effectiveness for real-world JIT defect prediction compared with DeepJIT. **Finding 3:** The DeepJIT commit-message/code-change vector representations contribute more for deep JIT defect prediction than the CC2Vec code-change vector representations. ### 3.3.2 RQ2: How Do DeepJIT and CC2Vec Perform on the Extended Dataset? In particular, we investigate how they perform under both the within-project and cross-project JIT defect prediction scenarios on top of the extended dataset. We also choose to conduct the experiments on the late versions of the adopted benchmark projects (partially for experimental comparison with the previous studies on early versions). Note that to eliminate the authentication latency issues [6], we remove certain recent data according to the defect fix delay time. As a result, we select the latest three-year commits, e.g., commits from 2015-01-01 to 2018-01-01 for QT and from 2016-01-01 to 2019-01-01 for OpenStack. Moreover, our training data and testing data are extracted chronologically and follow the same training/testing data partitioning of the original DeepJIT and CC2Vec work, i.e., the earlier 80% data are used for training and the later 20% data are used for testing. Furthermore, we choose to extend the performance comparison between CC2Vec, DeepJIT, and other representative approaches. To this end, we first retain DBN-JIT [50] which uses Deep Belief Network [17] to extract high-level information from the traditional defect prediction features and is adopted as the evaluation baseline in the original DeepJIT paper. Moreover, we also adopt a classic approach proposed by Kamei et al. [21] (denoted as LR-JIT), which integrates manually extracted features with the logistic regression model and has been widely adopted as the evaluation baseline for many traditional JIT defect prediction approaches [8, 29, 50]. **Within-project prediction.** The “WP” columns in Table 5 present the overall within-project results for CC2Vec, DeepJIT, and the other selected approaches on the extended dataset. We can observe that CC2Vec fails to retain performance advantages over DeepJIT on most of the projects. Specifically, for QT, OpenStack and Go, the prediction accuracy advantages of CC2Vec over DeepJIT in terms of the AUC scores are rather limited, i.e., 0.13%, 1.33% and 0.37% respectively. On the other hand, for the remaining three studied projects, DeepJIT can even outperform CC2Vec by 0.56% to 1.29%. Since CC2Vec only differs from DeepJIT by including additional code-change vector representations, such performance deviation can indicate that the code-change vector representation extracted by CC2Vec does not generalize its advantages over the original DeepJIT features to diverse datasets, indicating CC2Vec’s limited effectiveness for real-world JIT defect prediction compared with DeepJIT. Next, we can also observe that while DeepJIT and CC2Vec can deliver rather marginal average performance advantage over the two traditional approaches LR-JIT and DBN-JIT on top of all the adopted benchmarks, i.e., 0.7065 (DeepJIT) and 0.7055 (CC2Vec) vs. 0.6726 (LR-JIT) and 0.6847 (DBN-JIT), they cannot always outperform traditional approaches under all of the adopted projects. To be specific, on OpenStack, the AUC results of the two traditional approaches LR-JIT and DBN-JIT are 0.7248 and 0.7330, compared with 0.7132 of DeepJIT and 0.7227 of CC2Vec. On Eclipse JDT, LR-JIT can also slightly outperform DeepJIT and CC2Vec. We further attempt to explore the prediction accuracy of all the studied approaches in terms of diverse metrics, e.g., false discovery rate, recall, and accuracy, as such metrics have been widely adopted in previous work [21, 49, 50]. In particular, Accuracy (ACC) is the ratio of the number of correct predictions over the total number of predictions; Recall denotes the ratio of the number of correctly predicted defective instances over the total number of defective ![Finding 4: In general, CC2Vec cannot clearly outperform DeepJIT in the extended dataset, indicating that the vector representation of code changes extracted by CC2Vec do not contribute much in advancing JIT defect prediction.](image-url) ![Table 4: The impact of different feature subsets for CC2Vec](table-url) Deep Just-in-Time Defect Prediction: How Far Are We? ISSTA ’21, July 11–17, 2021, Virtual, Denmark Table 5: Within- and cross-project JIT defect prediction on our extended dataset <table> <thead> <tr> <th>AUC Score</th> <th>QT</th> <th>OpenStack</th> <th>JDT</th> <th>Platform</th> <th>Gerrit</th> <th>Go</th> <th>Mean</th> <th>% Drop</th> </tr> </thead> <tbody> <tr> <td></td> <td>WP</td> <td>CP</td> <td>WP</td> <td>CP</td> <td>WP</td> <td>CP</td> <td>WP</td> <td>CP</td> </tr> <tr> <td>DeepJIT</td> <td>0.6927</td> <td>0.6734</td> <td>0.7132</td> <td>0.7126</td> <td>0.6701</td> <td>0.6886</td> <td>0.7712</td> <td>0.6957</td> </tr> <tr> <td>CC2Vec</td> <td>0.6936</td> <td>0.6843</td> <td>0.7227</td> <td>0.7198</td> <td>0.6653</td> <td>0.6822</td> <td>0.7613</td> <td>0.6574</td> </tr> <tr> <td>LR-JIT</td> <td>0.6551</td> <td>0.5887</td> <td>0.7248</td> <td>0.6645</td> <td>0.6736</td> <td>0.6572</td> <td>0.6403</td> <td>0.6946</td> </tr> <tr> <td>DBN-JIT</td> <td>0.6752</td> <td>0.5844</td> <td>0.7330</td> <td>0.6707</td> <td>0.6426</td> <td>0.6595</td> <td>0.7016</td> <td>0.7113</td> </tr> </tbody> </table> Finding 5: DeepJIT and CC2Vec cannot always outperform traditional approaches on all the studied projects, and the finding holds for multiple widely-used metrics. Furthermore, we perform a within-project experiment in the early versions of the studied projects from 2011-01-01 to 2014-01-01 (roughly the same as the project versions in DeepJIT and CC2Vec), as shown in Table 6. We can find that compared with the AUC scores on the late versions of the studied projects (shown in Table 5), the AUC scores on the early versions can be quite inconsistent. For instance, for DeepJIT, the AUC scores on the two settings can be close on QT and OpenStack, i.e., 0.7144 vs. 0.6927 on QT and 0.7140 vs. 0.7152 on OpenStack, while they can be quite different on other projects, e.g., 0.7491 vs. 0.6701 on JDT. The same is true for all studied approaches. Accordingly, we can derive that all studied approaches cannot ensure consistent performance even under the identical benchmarks with different versions. The above performance inconsistency implies that for certain projects, their defect patterns can potentially vary between different program versions, causing potential challenges for designing training setups to optimize defect prediction. To better explore such concern, we further attempt to investigate the performance impact by adopting different training sets. In particular, we construct the training set with its size ranging from 10k to 50k historical commits for each studied project, and fixate most recent 2k samples for testing, i.e., 20% of the minimum training set size. Note that our training sets are constructed in the reverse chronological order so that larger training sets include more outdated historical data compared with smaller training sets; also, some projects will end with smaller training sets if they do not have sufficient historical data within last 10 years. Figure 6 presents the AUC trends in terms of the training data size for DeepJIT and LR-JIT. Note that we select these two approaches as representatives since the performance of CC2Vec and DBN-JIT are similar with DeepJIT and LR-JIT, respectively. We can observe that in general, both approaches enable fluent prediction accuracy under the increasing training data size. For instance, the average AUC of OpenStack is degraded from 0.7294 to 0.7018, while in contrast, the average AUC of QT increases from 0.6854 to 0.6906. Moreover, even each approach itself can encounter different trends under the increasing training data size. For instance, on Platform, the AUC of DeepJIT first slightly increases from 0.7744 to 0.7769 and then drops to 0.7610. In contrast, the AUC of LR-JIT first decreases from 0.6463 to 0.6307, and then increases to 0.6374 eventually. Such results directly indicate that simply expanding training set by including more historical data cannot always advance the prediction accuracy for both deep-learning-based and traditional approaches. We can also infer that the outdated historical data may not conform to the defect patterns of more recent data, and thus have limited effectiveness, which is consistent with prior findings on traditional JIT defect prediction [31]. Therefore, it can be rather challenging to adopt the optimal training set for JIT defect prediction. Finding 6: Simply adding more historical data cannot improve the prediction accuracy for both advanced deep JIT defect prediction approaches and traditional approaches. Cross-project prediction. While the original DeepJIT and CC2Vec papers do not include any cross-project evaluation, in this paper, we further study the performance of DeepJIT, CC2Vec, and the other studied approaches for cross-project validation, which attempts to address the issues caused by insufficient data from the projects under prediction. Specifically, similar as existing work [7, 20], our cross-project validation collects historical data from all the other adopted projects rather than the project under prediction for training a classifier, i.e., we use the training data from all the other studied projects for training a classifier and use the same testing data as the within-project evaluation shown in Table 5 for testing. The “CP” columns in Table 5 present the AUC scores for the studied approaches in cross-project prediction. We can observe that the deep JIT defect prediction approaches also cannot consistently outperform the traditional approaches on all the projects in this scenario. To be specific, on Platform, the AUC scores of the two traditional approaches (LR-JIT and DBN-JIT) are 0.6946 and 0.7113, compared with 0.6957 of DeepJIT and 0.6574 of CC2Vec. Also, compared with the within-project evaluation results (presented in the “WP” columns in Table 5), we can observe that for all the studied approaches, their within-project prediction accuracy can outperform their cross-project prediction accuracy for almost all the studied projects. For instance, the average AUC score of DeepJIT drops slightly form 0.7065 to 0.6808 in cross-project validation, while the average AUC scores of LR-JIT and DBN-JIT drop from 0.6726 and 0.6847 to 0.6490 and 0.6532, respectively. Such results conform to the finding on traditional JIT detect prediction that within-project prediction can usually outperform cross-project prediction [20]. Therefore, cross-project prediction is usually taken as the secondary choice when within-project prediction is not possible. Another interesting finding is that deep JIT approaches can incur roughly the same AUC loss as the traditional approaches when moving from within-project to cross-project prediction, i.e., -3.63% and -4.03% for two recent deep learning approaches vs. -3.52% and -4.60% for two traditional approaches. This indicates that deep JIT defect prediction approaches are not more robust than the traditional approaches in cross-project prediction. Finding 7: JIT defect prediction approaches usually perform better for within-project prediction than for cross-project prediction. In addition, deep JIT defect prediction approaches are not more robust than the traditional approaches in cross-project prediction. Table 7: Studied 14 basic change features <table> <thead> <tr> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>NS</td> <td>The number of modified subsystems [32]</td> </tr> <tr> <td>ND</td> <td>The number of modified directories [32]</td> </tr> <tr> <td>NF</td> <td>The number of modified files [33]</td> </tr> <tr> <td>Entropy</td> <td>Distribution of modified code across each file [9, 15]</td> </tr> <tr> <td>LA</td> <td>Lines of code added [33, 34]</td> </tr> <tr> <td>LD</td> <td>Lines of code deleted [33, 34]</td> </tr> <tr> <td>LT</td> <td>Lines of code in a file before the change [24]</td> </tr> <tr> <td>FIX</td> <td>Whether or not the change is a defect fix [14, 37]</td> </tr> <tr> <td>NDEV</td> <td>The number of developers that changed the modified files [30]</td> </tr> <tr> <td>AGE</td> <td>The average time interval between the last and current change [13]</td> </tr> <tr> <td>NUC</td> <td>The number of unique changes to the modified files [5, 13]</td> </tr> <tr> <td>EXP</td> <td>Developer experience [32]</td> </tr> <tr> <td>REXP</td> <td>Recent developer experience [32]</td> </tr> <tr> <td>SEXP</td> <td>Developer experience on a subsystem [32]</td> </tr> </tbody> </table> 3.3.3 RQ3: How Do Traditional Defect Prediction Features Perform for Just-in-Time Defect Prediction? The findings from RQ1 and RQ2 altogether reveal the following facts. First, for deep JIT defect prediction approaches, the DeepJIT code-change representations (i.e., the “added_code/removed_code” labels, which is essentially close to a traditional defect prediction feature, i.e., changed file number) have been shown to be more important than other feature inputs, i.e., DeepJIT commit-message representations and CC2Vec code-change representations (Table 4). Second, CC2Vec with more input features than DeepJIT can sometimes even degrade the prediction accuracy. Third, the recent deep JIT defect prediction approaches cannot consistently outperform traditional JIT defect prediction approaches under different settings/scenarios. Such facts expose that different features from traditional approaches have not been fully studied for JIT defect prediction. Accordingly, we attempt to answer this RQ by further investigating the performance of various representative traditional features for JIT defect prediction. Our investigation is launched based on a simple and classic JIT defect prediction approach proposed by Kamei et al. [20] (i.e., LR-JIT in RQ2). More specifically, they train a logistic regression classifier on a set of 14 manually summarized features that can demonstrate the size, diffusion, history, and author experience of the associated presents the AUC scores in terms of the adopted trajectory. We further present the AUC scores of all the additional features for within-project prediction, where the x-axis labels indicate the AUC scores. Note that “all” indicates that all the traditional features are adopted for model training, while all other x-axis labels indicate that only the corresponding feature is adopted for model training. Interestingly, we find that it is possible to build a well-performed classifier for JIT defect prediction using only one single feature. In particular, the average AUC score of the model increases from 0.7212 when all the features are adopted to 0.7236 when only the added-line-number (“la”) feature is used. Moreover, using the “la” feature, the AUC scores of QT, OpenStack, and Gerrit can reach 0.7343, 0.7465, and 0.7145, while they are only 0.6872, 0.7247, and 0.6842 when all the features are used. We further present the effectiveness of each single traditional feature for cross-project prediction in Figure 7b. In general, we find that compared with the within-project prediction results, many features are presented with significant performance variance, e.g., the “nu” feature achieves an average AUC 0.6214 in within-project prediction, but only 0.4783 in cross-project prediction. We infer that such performance variance is caused by the divergent distributions of the studied features among different studied projects. On the other hand, the fact that the cross-project prediction accuracy of the “la” feature is quite close to its within-project prediction accuracy indicates that such a simple feature is potentially variance-resilient in its distribution among different projects. Finding 8: The within-project and cross-project JIT defect prediction using only the “la” feature can achieve high prediction accuracy and negligible performance variance. 3.3.4 RQ4: Can a Simpler Approach Outperform DeepJIT and CC2Vec? Inspired by Finding 8, we propose a simplistic “la”-feature-based JIT defect prediction approach, namely LApredict. While it is definitely possible to integrate the “la” (added-line-number) feature with other information for more powerful JIT defect prediction, in this paper, we want to keep our design simplistic and only leverage the “la” feature with the classic logistic regression model for JIT defect prediction. We have empirically compared LApredict with all the other studied approaches, i.e., DeepJIT, CC2Vec, DBN-JIT, and LR-JIT, for both within- and cross-project validation (under the same setting as Table 5). The “WP” columns in Table 8 show the AUC scores of all the compared approaches for within-project prediction. Surprisingly, we observe that LApredict can outperform all the other approaches on average and on most of the studied projects! Specifically, the average AUC of LApredict is 0.7246 while the best of the other approaches is only 0.7065. Moreover, on QT, OpenStack, and Gerrit, LApredict achieves an AUC of 0.7438, 0.7491 and 0.7495, while the best results for DeepJIT and CC2Vec on those three projects are only 0.6993, 0.7227 and 0.7025. The “CP” columns in Table 8 further presents the AUC scores of all the studied approaches for cross-project prediction. We can observe that LApredict not only can retain its performance superiority over DeepJIT and CC2Vec, but also further expand its advantage compared with within-project prediction! The potential reason is that while using the cross-project data can potentially bring extra noises to the deep-learning-based approaches and thus degrade the prediction accuracy compared with within-project prediction, the simplistic added-line-number (“la”) feature can stay steady across projects since the training data of both WP and CP reflect the same rule, i.e., the larger the “la”, the higher the probability of being defective. In fact, using the logistic regression model, LApredict will always predict commit with a larger “la” value as more defect-prone. Also, the AUC score is calculated only based on the relative ranking of the predicted results. Thus, even different training data are used in WP/CP, the same testing data will always yield the same AUC. We further present the time costs of all the studied approaches in terms of both training and testing time under within-project prediction in Table 9. Note that the cross-project prediction results are similar, and thus are omitted here. We can observe that LApredict has negligible training and testing time due to its simplistic design (i.e., single feature with traditional classifier). On the contrary, the recent deep-learning-based approaches (i.e., DeepJIT and CC2Vec) can be much more costly due to their complicated neural network design, e.g., at least 81k X/120k X slower than LApredict in training/testing time. Table 8: Within- and cross-project prediction effectiveness for LApredict <table> <thead> <tr> <th></th> <th>AUC Score</th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td>Q1</td> <td>OpenStack</td> <td>JDT</td> <td>Platform</td> <td>Gerrit</td> <td>Go</td> <td>Mean</td> <td></td> </tr> <tr> <td></td> <td></td> <td>WP</td> <td>CP</td> <td>WP</td> <td>CP</td> <td>WP</td> <td>CP</td> <td>WP</td> <td>CP</td> </tr> <tr> <td>DeepJIT</td> <td>.6927</td> <td>6754</td> <td>7132</td> <td>.7126</td> <td>.6701</td> <td>6886</td> <td>.7712</td> <td>.6597</td> <td>7025</td> </tr> <tr> <td>CC2Vec</td> <td>.6936</td> <td>6848</td> <td>7227</td> <td>.7198</td> <td>.6553</td> <td>6822</td> <td>.7613</td> <td>.6574</td> <td>6986</td> </tr> <tr> <td>LR-JIT</td> <td>.6651</td> <td>5887</td> <td>7248</td> <td>.6645</td> <td>.6756</td> <td>6572</td> <td>.6403</td> <td>.6946</td> <td>6570</td> </tr> <tr> <td>DBN-JIT</td> <td>.6752</td> <td>5844</td> <td>7350</td> <td>.6707</td> <td>.6426</td> <td>6595</td> <td>.7016</td> <td>.7113</td> <td>6855</td> </tr> <tr> <td>LApredict</td> <td>.7438</td> <td>7438</td> <td>7491</td> <td>.7491</td> <td>.6757</td> <td>6757</td> <td>.7461</td> <td>.7461</td> <td>7495</td> </tr> </tbody> </table> Finding 9: Our simplistic LApredict can substantially outperform the advanced deep-learning-based approaches in JIT defect prediction under both within-project and cross-project scenarios in terms of both effectiveness and efficiency. 4 IMPLICATIONS AND DISCUSSIONS Our study reveals the following important practical guidelines for future JIT defect prediction. Deep learning does not always help. Our study reveals that although the deep JIT defect prediction approaches can be advanced under certain scenarios, they are rather data dependent and have limited effectiveness under diverse datasets/scenarios (Findings 5, 7, and 9). Also, the interpretability issue of deep learning models makes it even harder to ensure the optimal performance of deep JIT defect prediction. Furthermore, deep learning techniques can be orders of magnitude slower than traditional classifiers. We highly recommend the researchers/developers to conduct thorough evaluations for future deep JIT defect prediction approaches. Simple features can work. Our study shows that DeepJIT_GitHub, which abstracts code changes in each file into a simple label (i.e., "added_code/removed_code"), performs even better than the original DeepJIT_Paper described in the paper, which analyzes the detailed code changes (Finding 1). Also, the single added-line-number feature (with the logistic regression model) can already outperform all existing JIT defect prediction approaches, including the deep-learning-based approaches with rather complicated features (Finding 9). All such observations indicate that simple features should not be just ignored. In fact, they should be considered and even combined with advanced learning models and features for even more advanced JIT defect prediction. Commit messages are helpful. Our results show that certain keywords in the commit messages are rather helpful for deep JIT defect prediction, since they can convey the intents of specific code changes (Finding 2). This suggests that developers/teams interested in JIT defect prediction should maintain strict rules for drafting informative commit messages. Furthermore, this also motivates researchers to develop more advanced approaches to better align commit messages with code changes to avoid the negative impact of noisy commit messages. Training data selection is important. Our study shows that simply adding more training data cannot enhance the prediction accuracy for traditional or deep JIT defect prediction approaches (Finding 6). On the other hand, it is rather challenging to manually capture the most informative training set which optimizes the prediction accuracy under different benchmarks/scenarios. Therefore, we suggest researchers/developers to consider fully automated training data selection approaches targeting specific projects under prediction or even specific commits under prediction. Cross-project validation should be considered. Our experimental results show that the existing traditional/deep JIT defect prediction approaches witnessed a decreased performance when switching to cross-project validation (Finding 7). Interesting, our simplistic LApredict, which only uses the added-line-number feature with the classic logistic regression model, incurs no performance drop in cross-project validation (Finding 9). Such observation motivates future researchers to investigate more robust JIT defect prediction approaches under both within- and cross-project scenarios. 5 THREATS TO VALIDITY Threats to Internal Validity. The threats to internal validity mainly lie in the potential bugs in our implementation. To reduce such threats, we directly obtain the original source code from the GitHub repositories of the studied techniques. Also, we use the same hyperparameters as the original papers. The authors also carefully reviewed the experimental scripts to ensure their correctness. Meanwhile, the validity of the SZZ algorithm used for our dataset construction is also a critical threat that has been widely argued. Several studies have pointed out the limitations of SZZ [16, 38], while there are also studies demonstrating the effectiveness/accuracy of SZZ [11, 22, 48]. Despite the ongoing debate about SZZ, our focus is on the performance comparison of different prediction models, which is not directly affected by the SZZ algorithm. Therefore, we simply applied the same SZZ algorithm with DeepJIT/CC2Vec for a fair comparison. Threats to External Validity. The threats to external validity mainly lie in the benchmark projects used in this study. To reduce such threats, we not only use all the benchmark projects studied in the original CC2Vec and DeepJIT papers, but also construct a much larger-scale JIT defect prediction dataset (with 310k commits). Threats to Construct Validity. The threat to construct validity mainly lies in the adopted metrics in our evaluations. To reduce such threat, following the prior CC2Vec and DeepJIT work, we adopt the widely-used Area Under the Curve (AUC) score to evaluate the performance of the studied approaches. In particular, the AUC score does not need to manually set a threshold and thus can be quite objective [43]. To further reduce the threats, we also adopt other widely used metrics, e.g., Recall, ACC, and FDR. 6 RELATED WORK JIT defect prediction has been extensively studied in the last two decades. Mockus et al. [32] built a classifier based on information extracted from historic changes to predict the risk of new code changes. Kamei et al. [21] built a Logistic Regression Model on a set of 14 manually summarized features. Meanwhile, they also took into account the effort required to find defects in their evaluation. Based on Kamei’s work [21], Yang et al. [50] used Deep Belief Network (DBN) to extract higher-level information from the initial features and achieved better performance compared with Kamei’s approach. Also, by adopting Kamei’s features, Yang et al. [49] combined decision tree and ensemble learning to build a two-layer ensemble learning model for JIT defect prediction. Later, to enhance such approach [49], by allowing using arbitrary classifiers in the ensemble and optimizing the weights of the classifiers, Young et al. [52] proposed a new deep ensemble approach and achieved significantly better results. Meanwhile, Liu et al. [29] found that the code churn metric is effective in effort-aware JIT defect prediction, while Chen et al. [8] transformed the effort-aware JIT defect prediction task into a multi-objective optimization problem and selected a set of effective features via evolutionary algorithms. More recently, Cabral et al. [6] provided a new sampling approach to handle verification latency and class imbalance evolution of online JIT defect prediction. Also, Yan et al. [47] proposed a two-phase framework by combining JIT defect identification and localization. Note that most of such approaches are developed based on the two classic traditional JIT defect prediction approaches (Kamei et al. [21] and Yang et al. [50]) adopted for our study. On the other hand, the current state-of-the-art approaches, CC2Vec [19] and DeepJIT [18], attempt to enhance the prediction accuracy by applying modern advanced deep learning models to automatically extract features from commit messages and code changes. There also have been various studies on JIT defect prediction. McIntosh et al. [31] conducted a study of the impact of systems evolution on JIT defect prediction models via a longitudinal case study of 37,524 changes from the QT and OpenStack systems. They found that the performance of the JIT defect prediction model decreases as the interval between training periods and testing periods increases. Tabassum et al. [42] investigated cross-project JIT defect prediction in realistic online learning scenarios. They showed that in online learning scenarios, the model trained with both within- and cross-project data achieved better performance over the model trained with within-project data only. Recently, through literature review and a survey of practitioners, Wan et al. [44] discussed the shortcomings of existing defect prediction tools and highlighted future research directions. Different from all prior studies, our work presents the first extensive study of the state-of-the-art deep JIT defect prediction approaches. SZZ is also a critical part to be discussed [38]. Kim et al. [22] proposed an improved SZZ and claimed that such SZZ can achieve high accuracy under manual validation. Note that our dataset construction process followed such enhanced SZZ algorithms to ensure high accuracy (Section 3.1). Recently, Herbold et al. [16] conducted an empirical study on 38 Apache projects and found that many of the bug fixing commits identified by SZZ were incorrect or imprecise. Meanwhile, Fan et al. [11] investigated the impact of different SZZ variants on JIT defect prediction, and showed that different SZZ algorithms have limited impact on the prediction accuracy of the studied JIT defect prediction models. More recently, Yan et al. [48] performed a case study on 14 industrial projects and found that SZZ-tagged data can be validated to successfully derive a JIT defect prediction model which can help developers reduce their workload in real-world code review process. Despite the ongoing debate about SZZ, our focus is on the performance comparison of different prediction models, which is not directly affected by the SZZ algorithm. Therefore, we simply applied the same SZZ algorithm with DeepJIT/CC2Vec for a fair comparison. 7 CONCLUSIONS In this study, we have investigated the effectiveness and limitations of state-of-the-art deep JIT defect prediction approaches, i.e., DeepJIT and CC2Vec. Specifically, we have constructed an extended dataset containing over 310k commits and used it to evaluate the performance of DeepJIT, CC2Vec, and two representative traditional JIT defect prediction approaches. We found that CC2Vec cannot consistently outperform DeepJIT and neither of them can be ensured to outperform the traditional JIT defect prediction approaches. We also noticed that all the studied traditional and deep JIT defect prediction approaches witnessed a performance drop in cross-project validation. Moreover, simply increasing the training data size does not improve the prediction accuracy of the studied approaches. Surprisingly, we have also demonstrated that a simplistic JIT defect prediction approach, Lapredict, which simply uses the added-line-number feature with a traditional classifier, can already outperform CC2Vec and DeepJIT in terms of both effectiveness and efficiency on most studied projects. Lastly, our study also revealed various practical guidelines for future JIT defect prediction. ACKNOWLEDGEMENTS This work was partially supported by the National Natural Science Foundation of China (Grant No. 61902169) and Shenzhen Peacock Plan (Grant No. KQTD2016112514355031). This work was also partially supported by National Science Foundation under Grant Nos. CCF-1763906 and CCF-1942430, and Kwai Inc. REFERENCES
{"Source-Url": "https://lingming.cs.illinois.edu/publications/issta2021a.pdf", "len_cl100k_base": 14081, "olmocr-version": "0.1.50", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 43301, "total-output-tokens": 14999, "length": "2e13", "weborganizer": {"__label__adult": 0.0004258155822753906, "__label__art_design": 0.0004017353057861328, "__label__crime_law": 0.0003104209899902344, "__label__education_jobs": 0.000995635986328125, "__label__entertainment": 6.496906280517578e-05, "__label__fashion_beauty": 0.0002111196517944336, "__label__finance_business": 0.00024127960205078125, "__label__food_dining": 0.00026035308837890625, "__label__games": 0.0006623268127441406, "__label__hardware": 0.000918865203857422, "__label__health": 0.0004377365112304687, "__label__history": 0.0001951456069946289, "__label__home_hobbies": 9.5367431640625e-05, "__label__industrial": 0.0003380775451660156, "__label__literature": 0.0002267360687255859, "__label__politics": 0.00019681453704833984, "__label__religion": 0.00042319297790527344, "__label__science_tech": 0.01318359375, "__label__social_life": 0.00010895729064941406, "__label__software": 0.005191802978515625, "__label__software_dev": 0.97412109375, "__label__sports_fitness": 0.00032639503479003906, "__label__transportation": 0.00044655799865722656, "__label__travel": 0.0001854896545410156}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 62502, 0.05899]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 62502, 0.12826]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 62502, 0.91312]], "google_gemma-3-12b-it_contains_pii": [[0, 5663, false], [5663, 10495, null], [10495, 16441, null], [16441, 23373, null], [23373, 30031, null], [30031, 34997, null], [34997, 38801, null], [38801, 45119, null], [45119, 49933, null], [49933, 55604, null], [55604, 62502, null], [62502, 62502, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5663, true], [5663, 10495, null], [10495, 16441, null], [16441, 23373, null], [23373, 30031, null], [30031, 34997, null], [34997, 38801, null], [38801, 45119, null], [45119, 49933, null], [49933, 55604, null], [55604, 62502, null], [62502, 62502, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 62502, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 62502, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 62502, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 62502, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 62502, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 62502, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 62502, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 62502, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 62502, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 62502, null]], "pdf_page_numbers": [[0, 5663, 1], [5663, 10495, 2], [10495, 16441, 3], [16441, 23373, 4], [23373, 30031, 5], [30031, 34997, 6], [34997, 38801, 7], [38801, 45119, 8], [45119, 49933, 9], [49933, 55604, 10], [55604, 62502, 11], [62502, 62502, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 62502, 0.2598]]}
olmocr_science_pdfs
2024-12-03
2024-12-03
638cf87aba399a38a0ec7a550f560bd92f9ff777
Global Optimization I - Central to all the global optimizations are that they make use of global data-flow analysis. We are going to start out by discussing the algorithms for performing global optimizations, assuming that the information computed during data-flow analysis is available. Later on we will describe how this information is actually computed. - Global data-flow analysis answers questions like: “will a value v computed at a point p in a procedure be available at some other point q?” - In other words, global data-flow analysis tracks values and computations as they cross basic block boundaries. Global Optimization II - In general we can’t know how control will flow in a flow-graph, so our data-flow analysis has to be conservative: it has to assume that any possible control flow may be an actual control flow. This means that 1. any optimization that we perform will not change the semantics of the program, and 2. sometimes we won’t be able to perform an optimization that would be perfectly legal, just because our data-flow information is imprecise (too conservative). Loop Invariants I - Let $C$ be a computation in a loop body. $C$ is **invariant** if it computes the same value during all iterations. $C$ can sometimes be moved out of the loop. $K := 1; \ I := 2;$ **REPEAT** $A := K + 1; \ I := I + A;$ **UNTIL** $I <= 10;$ $K := K + A;$ **Step 1: Build Flowgraph** $d_1: K := 1; \ d_2: I := 2;$ $d_3: A := K + 1;$ $d_4: I := I + A;$ $d_5: \text{if } I > 10 \text{ goto } B2$ $d_6: K := K + A;$ Slide 17–4 Loop Invariants II - To detect (in the previous slide) that $A := K + 1$ is invariant, we must first detect that $K$ is not changed within the loop. - We really want to know is where the value that $K$ has in the loop could have been computed. If $K$’s value could only have been computed outside the loop (as is, in fact, the case) then we can conclude that $K$ is not changed within the loop, and hence $A := K + 1$ is invariant. - Information on where the value of a particular variable (at a particular point in the program) could have been computed is often stored in **use-definition-chains**, or **ud-chains**. Slide 17–5 Loop Invariants III - If, at a point $p$ in the program, we use a variable $i$, and the point $q$ is on $i$’s ud-chain at point $p$, then the value of $i$ at $p$ could have been computed at $q$. - Note that we have no way of knowing exactly where $i$’s value has been computed (this depends on the actual control-flow at run-time and is in general non-computable [equiv the halting problem]), so our ud-chains will be overly pessimistic: there may be points on $i$’s ud-chain that are never reached at run-time (and hence $i$ could never receive a value there), but we can’t be sure of this and therefore we must include those points as well. Slide 17–6 Reaching Definitions I - To detect loop invariant computations we must first compute **reaching definitions**, or **use-definition-chains**. - $p$: ud[i], the ud-chain for a variable $i$ at a point $p$, lists the points in the program where $i$’s value could have been computed. **Example:** $d_1: \ i := m - 1;$ $d_2: \ j := n;$ **REPEAT** $d_3: \ i := i + 1; \ \text{ud}[i] = \langle d_1, d_3, d_6 \rangle$ $d_4: \ j := j - 1; \ \text{ud}[j] = \langle d_2, d_4 \rangle$ **IF** ... **THEN** $d_5: \ a := \cdots$; **ELSE** $d_6: \ i := \cdots$; **END**; **UNTIL** ... Reaching Definitions II - Ud-chains are built from the solution to a data-flow problem known as **reaching definitions**. For example, in the previous slide 1. the definition of i at point \( d_1 \) reaches point \( d_3 \), because the value of \( i \) on the right hand side of \( i := i + 1 \) could have been computed at \( d_1 \). 2. the definition of i at point \( d_3 \) reaches \( d_3 \) itself, since if the first branch of the IF-statement is taken \( d_5 \) won’t be executed, and i’s value computed at \( d_3 \) will still be valid the next time \( d_3 \) is reached. 3. if the second branch of the IF-statement is taken, however, i’s value computed at \( d_5 \) will reach \( d_3 \). Hence, the definitions of i at \( d_1, d_3, d_6 \) all reach \( d_3 \), and are on i’s ud-chain at \( d_3 \). Data-Flow Problems I - In order to build ud-chains, we have to solve the data-flow problem **reaching definitions**. - Data-flow problems are problems on **sets**. These sets can be sets of points in the control flow graph, sets of expressions, sets of variables, etc, depending on the nature of the problem. - In the reaching definitions problem we work on sets of **definitions**, or places in the control flow graph where a particular variable could have received its value. - In general, data-flow problems come in two parts: a local part which solves the problem within each basic block, and a global part which combines the local solutions into a global solution. Data-Flow Problems II - The local part of the data-flow problem consists of (for each basic block \( B \)), computing two sets, often called \( \text{gen}[B] \) and \( \text{kill}[B] \). - For the reaching definitions problem \( \text{gen}[B] \) is the set of definitions that occur within \( B \) and that reach the end of \( B \). I.e., if there is more than one assignment to \( a \) in \( B \), then only the last one reaches the end of \( B \). - Similarly, \( \text{kill}[B] \) is the set of definitions (anywhere in the routine) that are killed by definitions in \( B \). I.e., if some definition \( d \) reached the beginning of \( B \) and \( d \) is in \( \text{kill}[B] \), we could be sure that that definition would not reach the end of \( B \). Loop Invariants IV - For each basic block we compute \( \text{gen} \) and \( \text{kill} \). - \( \text{gen}[B] \) is the set of definitions (assignments to variables) that occur within \( B \). \( \text{kill}[B] \) is the set of definitions outside \( B \), killed by definitions within \( B \). --- **Step 2: Compute \( \text{gen} \) & \( \text{kill} \):** \[ \begin{align*} \text{B1: } & \quad d_1 : K := 1; \\ & \quad d_2 : I := 2; \\ \text{B2: } & \quad \text{gen}[B1] = \{ d_1, d_2 \} \\ & \quad \text{kill}[B1] = \{ d_4, d_6 \} \\ \text{B3: } & \quad \text{gen}[B2] = \{ d_3, d_4 \} \\ & \quad \text{kill}[B2] = \{ d_2 \} \\ \text{B3: } & \quad \text{gen}[B3] = \{ d_6 \} \\ & \quad \text{kill}[B3] = \{ d_1 \} \end{align*} \] Data-Flow Problems III - The global part of a data-flow problem computes sets called $\text{in}[B]$ and $\text{out}[B]$. - For the reaching definitions problem, $\text{in}[B]$ is the set of definitions that reach the beginning of $B$, i.e., the set of points in the control flow graph that computes values that may still be valid when we (at run time) reach the beginning of $B$. - Similarly, $\text{out}[B]$ is the set of definitions that may reach the end of $B$, i.e., the set of points in the flow graph that computes values that may still be valid when control reaches the end of $B$. - Consider the example in the previous slide: 1. Since no definitions are going into $B_1$, $\text{out}[B_1]$ is simply the set of defs generated within $B_1$, i.e., $\text{gen}[B_1]$. --- Loop Invariants V (a) - Next we must compute $\text{in}$ and $\text{out}$. - $\text{in}[B]$ is the set of definitions that reach the beginning of $B$. - $\text{out}[B]$ the set that reach $B$'s end. --- Slide 17–12 Slide 17–13 --- Slide 17–14 Slide 17–15 **Loop Invariants VI** - Reaching definitions information is often stored as ud-chains. - \( d_k \in \text{ud}[v] \) at point \( p \), if \( v \)'s value at \( p \) could have been computed in \( d_k \). - If \( v \) is used at point \( p \) in block \( B \), then \( \text{du}[v]_p \) is the list of definitions of \( v \) in \( \text{in}(B) \). (Well, almost.) **Step 3: Compute du-chains:** \[ \begin{align*} \text{B1:} & \quad d_1 : K := 1; \\ & \quad d_2 : I := 2; \quad \text{in}([B1]) = \{\} \\ \text{B2:} & \quad d_3 : A := K + 1; \\ & \quad d_4 : I := I + A; \\ & \quad d_5 : \text{if } I > 10 \text{ goto } B2 \quad \text{in}([B2]) = \{d_1, \ldots, d_4\} \\ \text{B3:} & \quad d_6 : K := K + A; \quad \text{in}([B3]) = \{d_1, d_3, d_4\} \\ \end{align*} \] **Loop Invariants VII** - With du-chains available, we can now mark invariant computations in loops. - \( d_k \) is invariant if either all arguments are constants, or have their reaching definitions outside the loop. **Step 4: Compute Invariant Expr:** \[ \begin{align*} \text{B1:} & \quad d_1 : K := 1; \\ & \quad d_2 : I := 2; \\ \text{invariant!} & \quad \text{B2:} \\ & \quad d_3 : A := K + 1; \\ & \quad d_4 : I := I + A; \\ & \quad d_5 : \text{if } I > 10 \text{ goto } B2 \quad \text{ud}[K] = (d_1) \\ & \quad \text{B3:} \\ & \quad d_6 : K := K + A; \quad \text{ud}[A] = (d_3) \\ \end{align*} \] **Loop Invariants VIII** - Finally we can move invariant computations out of loops, subject to certain conditions (see the Dragon book, p. 641). **Step 5: Perform Code-Motion:** \[ \begin{align*} \text{B1:} & \quad d_1 : K := 1; \\ & \quad d_2 : I := 2; \\ & \quad d_3 : A := K + 1; \quad \text{B2:} \\ & \quad d_4 : I := I + A; \\ & \quad d_5 : \text{if } I > 10 \text{ goto } B2 \quad \text{B3:} \\ & \quad d_6 : K := K + A; \\ \end{align*} \] **Loop Invariants IX** **Algorithm** 1. Build a flowgraph for the procedure. 2. Compute ud-chains: (a) Compute reaching definitions: i. For each block \( B \), compute \( \text{gen}(B) \) and \( \text{kill}(B) \). ii. For each block \( B \), compute \( \text{in}(B) \) and \( \text{out}(B) \). (b) Use \( \text{in}(B) \) to build ud-chains. 3. Use ud-chains to detect invariant computations. 4. When possible, perform code motion, by moving invariant computations out of loops. **Reaching Def. Example I** - To understand global optimization, it’s important to have a thorough understanding of data-flow analysis. Therefore we’re going to take another look at the computations of ud-chains, through reaching definitions. \[ \begin{align*} d_1 & : \text{i} := m - 1; \\ d_2 & : \text{j} := n; \\ d_3 & : \text{m} := \cdots; \\ \text{REPEAT} & \\ d_4 & : \text{i} := \text{i} + 1; \\ d_5 & : \text{j} := \text{j} - 1; \\ \text{IF} & \text{ ... THEN} \\ d_6 & : \text{a} := \cdots; \\ \text{ELSE} & \\ d_7 & : \text{i} := \cdots; \\ \text{END}; \\ \text{UNTIL} & \cdots \end{align*} \] **Slide 17–20** **Reaching Def. Example II** \[ \begin{align*} d_1 & : \text{i} := m - 1 \\ d_2 & : \text{j} := n \\ d_3 & : \text{m} := \cdots \} \] **Slide 17–21** **Reaching Def. Example III (a)** **Block B1** - \text{out[B1]}=\{d_1, d_2, d_3\}, since \(d_1, d_2, d_3\) reach the end of the block (once \text{i} has been defined, there are no further assignments to it in the block). **Block B2** - \text{in[B2]}=\{d_1, \cdots, d_7\}, since we can reach the entrance to B2 either through B2 (when definitions \(d_1, d_2, d_3\) are active), through B3 (when definitions \(d_4, d_5, d_6\) are active), or through B4 (when \(d_3, d_5, d_6, d_7\) are active). The union of these sets is \{d_1, \cdots, d_7\}. - \text{out[B2]}=\{d_3, \cdots, d_6\}, since B2 definitely kills \{d_1, d_2, d_7\}in B1. **Slide 17–22** **Reaching Def. Example III (b)** **Block B3** - \text{in[B3]}=\text{out[B2]}=\{d_3, \cdots, d_6\}, since if some value is available at the end of B2, then certainly it is available at the beginning of B3. - \text{out[B3]}=\{d_4, \cdots, d_6\} since all the incoming definitions (\{d_3, \cdots, d_6\}) plus those definitions generated within B3 (\(d_4\)) are available at B3’s exit, except those that were killed by B3’s \(d_4\). **Slide 17–23** **Data-Flow Equations I** \[ \text{out}[B] = \text{gen}[B] \cup (\text{in}[B] - \text{kill}[B]) \] \[ \text{in}[B] = \bigcup_{\text{predecessors} \ P \ of \ B} \text{out}[P] \] --- **Local Equations:** - \( d \in \text{gen}[B] \Rightarrow d \) reaches the end of \( B \). - \( d \in \text{kill}[B] \Rightarrow d \) does not reach the end of \( B \). --- **Global Equations:** - \( d \in \text{in}[B] \Rightarrow d \) reaches the beginning of \( B \). - \( d \in \text{out}[B] \Rightarrow d \) reaches the end of \( B \). --- **Global Data-Flow (Equations):** \[ \text{out}[B] = \text{gen}[B] \cup (\text{in}[B] - \text{kill}[B]) \] --- **Global Data-Flow (English):** \( \text{out}[B] \) (the definitions which are available at the end of \( B \)) contains the definitions generated within \( B \) (\( \text{gen}[B] \)), and the definitions that are available at the beginning of \( B \) (\( \text{in}[B] \)), except those that where superseded by definitions in \( B \) (\( \text{kill}[B] \)). --- **Example:** \( g[B_1]=[d_2] \) \( k[B_1]=[d_5,d_6] \) \( g[B_3]=[d_6] \) \( k[B_3]=[d_2,d_5] \) \( g[B_2]=[d_5] \) \( k[B_2]=[d_2,d_6] \) --- **Global Data-Flow (Equations):** \[ \text{in}[B] = \bigcup_{\text{predecessors} \ P \ of \ B} \text{out}[P] \] --- **Global Data-Flow (English):** \( \text{in}[B] \) (the definitions which are available at the beginning of \( B \)) contains all definitions available at the end of any basic block from which control can flow into \( B \). --- **Example:** \( g[B_1]=[d_2] \) \( k[B_1]=[d_5,d_6] \) \( g[B_2]=[d_5] \) \( k[B_2]=[d_2,d_6] \) --- \( \text{in}[B_2] = \{d_2\} \) \( \text{in}[B_3] = \{d_2\} \) \( \text{out}[B_2] = \text{gen}[B_2] \cup (\text{in}[B_2] - \text{kill}[B_2]) = \{d_5\} \cup (\{d_2\} - \{d_2,d_6\}) = \{d_5\} \) \( \text{out}[B_3] = \text{gen}[B_3] \cup (\text{in}[B_3] - \text{kill}[B_3]) = \{d_6\} \cup (\{d_2\} - \{d_2,d_5\}) = \{d_6\} \) \( \text{in}[B_4] = \text{out}[B_2] \cup \text{out}[B_3] = \{d_5,d_6\} \) --- **Global Data-Flow (Equations):** --- **Global Data-Flow (English):** --- **Example:** --- --- --- Computing UD-Chains - Assume that variable a is used at point p in block B. Assume that there is not def of a between the beginning of B and p. - Then the ud-chain of a at p is the definitions of a in in[B]. **Example** ``` B1 d1: i := m - 1 d2: j := n d3: a := ... B2 d4: i := i + 1 d5: j := j - 1 ud[i] = {d1, d4, d7} B3 d6: a := ... i = {d3 ... d0} ``` Global CSE I - Reaching definitions are only one of many possible global data flow problems. Next we will see how we can perform global common sub-expression elimination, based on information computed by a global data-flow analysis problem called Available Expressions. - In the next slide we see that 1. when control reaches B6, the expression Y+Z will have been computed, regardless of which IF-statement branch has been taken, 2. Y+Z is used within B6 and is therefore a common subexpression. Can we detect this so that we need not recompute Y+Z in B6 but rather can reuse the value computed in B4 & B5 in B6. Global CSE II ``` X := G; WHILE X < 10 DO IF X > 1 THEN X := Y + Z; T := 5 - V; ELSE V := Y + Z; END; END; ``` ``` B1 d1: X := G B2 d2: if X >= 10 goto B5 B3 d3: if X > 1 goto B4 B4 d4: X := Y + Z d5: T := 5 - V d6: V := Y + Z B5 d7: R := Y + Z d8: S := 7 - V ``` Available Expressions I (a) - An expression E is available at some point p if (regardless of the actual execution path from the initial node to p) E's value will have been computed when p is reached. ``` localAvailableExprs ``` gen[B] is the set of expressions generated within B (and not killed by B itself). ``` ap: X := Y + Z A := A \cup \{Y + Z\} - expr in A q: Y := ... A := A \cup \{Y + Z\} r: Y := ... ``` --- Slide 17–28 Slide 17–29 Slide 17–30 Slide 17–31 Available Expressions I (b) Local Available Expres: kill[B] is the set of expressions killed within B, i.e. all expressions Y + Z such that Y or Z is assigned to in B. \[ U = \{ q, r \} \] \[ \begin{align*} q & : \ldots = X + \ldots \\ r & : \ldots = \ldots X \\ p & : X := \ldots \\ \end{align*} \] kill[B] = exprs in U killed by B, i.e. \{q, r\} U is the universal set of expressions in the procedure. --- Available Expressions II \[ \begin{align*} B_1: d_1 & : X := 0 \\ B_2: d_2 & : \text{if } X >= 10 \text{ goto } B_6 \\ B_3: d_3 & : \text{if } X > 1 \text{ goto } B_4 \\ B_4: d_4 & : X := Y + Z \\ B_5 & \\ B_6: d_6 & : V := Y + Z \\ B_7: d_7 & : R := Y + Z \\ \end{align*} \] --- Available Expressions III Global Data-Flow (Equations): \[ \text{out}[B] = \text{gen}[B] \cup (\text{in}[B] - \text{kill}[B]) \] Global Data-Flow (English): out[B] (the set of expressions available at the end of B) contains the expressions generated within B (gen[B]), and the expressions that are available at the beginning of B (in[B]), except those that were killed by definitions in B (kill[B]). Example: \[ \text{in} = \{ X + Y, S + T \} \] \[ \begin{align*} d_1 & : \ldots = R + P \\ d_9 & : S := \ldots \\ \end{align*} \] \[ \text{gen} = \{ R + P \} \] \[ \text{kill} = \{ S + T \} \] \[ \text{out} = \{ X + Y, R + P \} \] --- Available Expressions IV Global Data-Flow (Equations): \[ \text{in}[B_1] = \{ \} \] \[ \text{in}[B] = \bigcap_{\text{pred}P \text{ of } B} \text{out}[P] \] Global Data-Flow (English): in[B_1] is always empty. in[B] expressions available at the entrance to B, i.e. any expression available at the exit of all of B’s predecessors. Example: \[ \begin{align*} s & : \ldots := V + T \\ q & : \ldots := X + Y \\ r & : \ldots := X + Y \\ \end{align*} \] \[ \text{X+Y is available here, but not } V + T. \] --- Slide 17–32 Slide 17–33 Slide 17–34 Slide 17–35 Available Expressions V Global CSE III – Algorithm Consider each statement \( s : x := y + z \) in block B such that \( (y + z) \in \text{in}[B] \). 1. Find all statements \( d : R := y + z \) in B's ancestor blocks, such that \( y + z \) could reach \( s \). 2. Replace \( d : R := y + z \) with \( d : T_1 := y + z ; R := T_1 \). 3. Replace \( s : x := y + z \) with \( s : x := T_1 \). Global CSE IV Search for \( Y + Z \) Readings and References Summary I - Global Data-Flow Analysis tracks the flow of values and computations across basic block boundaries. - Typically, before we can perform a particular global optimization, we have to collect (one or more kinds of) global data-flow information. - The data-flow information is normally collected for each basic block of the flow-graph. We can then easily compute the relevant information for points within each basic block, on a need-to-know basis. Summary II - Data-flow problems are represented as data-flow equations. Each equation manipulates sets of computations: - \texttt{gen} is the set of computations generated locally within a basic block. - \texttt{kill} is the set of computations generated outside the block, which could possibly be invalidated by computations within the block. - \texttt{in} is the set of computations available at the beginning of a block. - \texttt{out} is the set of computations available at the end of a block. - \texttt{gen} and \texttt{kill} are generated locally for each basic block \texttt{B}, without ever looking at computations outside the block. Summary III - \texttt{in[\texttt{B}]} and \texttt{out[\texttt{B}]} store the actual global data-flow information for the block \texttt{B}. They are computed from \texttt{gen[\texttt{B}]} and \texttt{kill[\texttt{B}]} and from \texttt{in} and \texttt{out} of neighboring blocks. - A typical data-flow equation for some problem \texttt{P} might look like this: \[ \text{outp[\texttt{B}]} = \text{genp[\texttt{B}]} \cup (\text{inp[\texttt{B}]} - \text{killp[\texttt{B}]}) \] It says that the computations available at the the end of the block (\texttt{out[\texttt{B}]} are those available at the entrance of the block, plus those generated within the block, except those computations generated outside the block that were invalidated by computations inside the block. Summary IV - Keep in mind that a global optimizer will solve many different data-flow problems, all involving sets called \texttt{gen}, \texttt{kill}, in and \texttt{out}, but that each problem has its own sets and equations. So, for a particular block \texttt{B}, we may have \texttt{inReachDef[\texttt{B}]}, \texttt{outReachDef[\texttt{B}]}, \texttt{genReachDef[\texttt{B}]}, \texttt{killReachDef[\texttt{B}]}, and \texttt{inAvailExpr[\texttt{B}]}, \texttt{outAvailExpr[\texttt{B}]}, \texttt{genAvailExpr[\texttt{B}]}, \texttt{killAvailExpr[\texttt{B}]}, etc. - Similarly, each data-flow problem sets up its own set of unique data-flow equations, although these equations may look remarkably similar from one problem to the next. Summary V - We have seen two data-flow problems: - Reaching Definition Analysis is used to build ud-chains, which in turn are used to detect loop-invariant computations (computations that produce the same value regardless of how many times the loop is executed). - Available Expression Analysis is used to optimize global common subexpressions. For each point \( p \) in the program we build the set of expressions that must have been computed, and whose value must still be current. Slide 17–44 Summary VI - There are many other data-flow problems: - Live-Variable Analysis is used during code-generation to avoid having to save a value stored in a register, if that value has no future use in the program. A live variable, on the other hand holds a value which may be used later on. - Definition-Use Analysis builds definition-use chains, lists which for each definition of a variable \( v \) holds the possible uses of \( v \)‘s value. du-chains are needed in order to perform copy propagation. Slide 17–46 Homework I - Build the flow-graph and ud-chains for the procedure body below. Then detect invariant computations, and — if possible — move them out of the loop. \[ \begin{align*} \text{K} & := 1; \text{ I} := 2; \\ \text{REPEAT} & \\ \text{IF I} & = 4 \text{ THEN} \\ \text{A} & := \text{K} + 1; \\ \text{ELSE} & \\ \text{A} & := \text{K} + 2; \\ \text{I} & := \text{I} + \text{A}; \\ \text{ENDIF}; \\ \text{UNTIL I} & <= 10; \\ \text{K} & := \text{K} + \text{A}; \end{align*} \] Exam Problem I (a) [07.430 ’95] - An expression \( E \) is very busy if – regardless of which path we take through the flow graph – \( E \)'s value will be used before it is killed. Example: (1) BEGIN (2) IF expr THEN (3) \( V := A + 3; \) (4) \( R := K + 3; \) (5) ELSE (6) \( Z := A + 3; \) (7) \( K := 5; \) (8) \( L := K + 3; \) (9) END; (10) END Slide 17–48 Exam Problem I (b) [07.430 ’95] - \( A+3 \) is very busy at (2), since – regardless of which branch of the IF-statement we take – \( A+3 \) will be used before it is killed. However, \( K+3 \) is not very busy, since (in the ELSE-branch) it is being killed by the assignment to \( K \) (at (7)) before it is being used. - Very busy expression information is useful for register allocation (very busy expressions will always be computed, and should probably be allocated to a register) and when performing code hoisting, i.e. moving code to a common ancestor in the flow graph. Code hoisting applied to the example above would produce the following: Exam Problem I (b) [07.430 ’95] (1) BEGIN (1.5) \( T$0 := A + 3; \) (2) IF expr THEN (3) \( V := T$0; \) (4) \( R := K + 3; \) (5) ELSE (6) \( Z := T$0; \) (7) \( K := 5; \) (8) \( L := K + 3; \) (9) END; (10) END Data-Flow Equations: - The data-flow equations for computing very busy expressions are: \[ \text{in}[B] = \text{used}[B] \cup (\text{out}[B] - \text{killed}[B]) \] \[ \text{out}[B] = \bigcap \text{in}[S] \quad \text{successors of } B \] \text{out}[B] \quad \text{is the set of all expressions that are very busy at the end of the basic block } B. \text{in}[B] \quad \text{is the set of all expressions that are very busy at the beginning of } B. \text{used}[B] \quad \text{is the set of all expressions that are used before they are killed in } B. \text{killed}[B] \quad \text{is the set of all expressions that are killed (i.e. their value is invalidated) before they are used in } B. Exam Problem I (c) [07.430 ’95] Slide 17–50 - Consider the following routine: ``` BEGIN X := 5; Y := 10; IF e1 THEN IF e2 THEN A := X * Y; ELSE B := 3; V := X * Y; X := 1; END; ELSE Y := 2; A := X * Y; END END ``` 1. Construct the control-flow graph for the routine. 2. Construct the `used[B]` and `killed[B]` sets for each basic block of the control-flow graph. 3. Construct the resulting `in[B]` and `out[B]` sets for each basic block of the control-flow graph.
{"Source-Url": "http://www2.cs.arizona.edu/~collberg/Teaching/553/2000/Handouts/Handout-17.pdf", "len_cl100k_base": 8231, "olmocr-version": "0.1.50", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 88763, "total-output-tokens": 9597, "length": "2e13", "weborganizer": {"__label__adult": 0.0003612041473388672, "__label__art_design": 0.0003113746643066406, "__label__crime_law": 0.00031948089599609375, "__label__education_jobs": 0.0013723373413085938, "__label__entertainment": 5.78761100769043e-05, "__label__fashion_beauty": 0.0001556873321533203, "__label__finance_business": 0.0002818107604980469, "__label__food_dining": 0.000324249267578125, "__label__games": 0.0008668899536132812, "__label__hardware": 0.00223541259765625, "__label__health": 0.0004286766052246094, "__label__history": 0.00026702880859375, "__label__home_hobbies": 0.00018262863159179688, "__label__industrial": 0.0007605552673339844, "__label__literature": 0.00019609928131103516, "__label__politics": 0.00024080276489257812, "__label__religion": 0.0005183219909667969, "__label__science_tech": 0.0262603759765625, "__label__social_life": 8.666515350341797e-05, "__label__software": 0.00440216064453125, "__label__software_dev": 0.958984375, "__label__sports_fitness": 0.0004203319549560547, "__label__transportation": 0.0008029937744140625, "__label__travel": 0.00022614002227783203}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 24720, 0.05301]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 24720, 0.42267]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 24720, 0.80991]], "google_gemma-3-12b-it_contains_pii": [[0, 1099, false], [1099, 3468, null], [3468, 6458, null], [6458, 7504, null], [7504, 9830, null], [9830, 11772, null], [11772, 13907, null], [13907, 15671, null], [15671, 17581, null], [17581, 18146, null], [18146, 20765, null], [20765, 22271, null], [22271, 24245, null], [24245, 24720, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1099, true], [1099, 3468, null], [3468, 6458, null], [6458, 7504, null], [7504, 9830, null], [9830, 11772, null], [11772, 13907, null], [13907, 15671, null], [15671, 17581, null], [17581, 18146, null], [18146, 20765, null], [20765, 22271, null], [22271, 24245, null], [24245, 24720, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 24720, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 24720, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 24720, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 24720, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 24720, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 24720, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 24720, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 24720, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 24720, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 24720, null]], "pdf_page_numbers": [[0, 1099, 1], [1099, 3468, 2], [3468, 6458, 3], [6458, 7504, 4], [7504, 9830, 5], [9830, 11772, 6], [11772, 13907, 7], [13907, 15671, 8], [15671, 17581, 9], [17581, 18146, 10], [18146, 20765, 11], [20765, 22271, 12], [22271, 24245, 13], [24245, 24720, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 24720, 0.0]]}
olmocr_science_pdfs
2024-12-01
2024-12-01
31a5719aa8aa26ac2001374bb6311b15c362761c
[REMOVED]
{"len_cl100k_base": 15968, "olmocr-version": "0.1.50", "pdf-total-pages": 18, "total-fallback-pages": 0, "total-input-tokens": 81888, "total-output-tokens": 18001, "length": "2e13", "weborganizer": {"__label__adult": 0.0005779266357421875, "__label__art_design": 0.0008263587951660156, "__label__crime_law": 0.0004551410675048828, "__label__education_jobs": 0.00220489501953125, "__label__entertainment": 0.00022399425506591797, "__label__fashion_beauty": 0.0003120899200439453, "__label__finance_business": 0.0006694793701171875, "__label__food_dining": 0.0008301734924316406, "__label__games": 0.0015611648559570312, "__label__hardware": 0.001255035400390625, "__label__health": 0.0013885498046875, "__label__history": 0.000629425048828125, "__label__home_hobbies": 0.00020515918731689453, "__label__industrial": 0.000881195068359375, "__label__literature": 0.002254486083984375, "__label__politics": 0.0006184577941894531, "__label__religion": 0.0010528564453125, "__label__science_tech": 0.246337890625, "__label__social_life": 0.00017201900482177734, "__label__software": 0.0088348388671875, "__label__software_dev": 0.72705078125, "__label__sports_fitness": 0.0003674030303955078, "__label__transportation": 0.0012607574462890625, "__label__travel": 0.00026345252990722656}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 56765, 0.01421]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 56765, 0.39583]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 56765, 0.85306]], "google_gemma-3-12b-it_contains_pii": [[0, 2318, false], [2318, 5539, null], [5539, 9200, null], [9200, 12245, null], [12245, 15224, null], [15224, 18097, null], [18097, 21666, null], [21666, 24800, null], [24800, 28018, null], [28018, 31493, null], [31493, 34501, null], [34501, 38449, null], [38449, 41981, null], [41981, 45405, null], [45405, 48813, null], [48813, 52026, null], [52026, 55085, null], [55085, 56765, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2318, true], [2318, 5539, null], [5539, 9200, null], [9200, 12245, null], [12245, 15224, null], [15224, 18097, null], [18097, 21666, null], [21666, 24800, null], [24800, 28018, null], [28018, 31493, null], [31493, 34501, null], [34501, 38449, null], [38449, 41981, null], [41981, 45405, null], [45405, 48813, null], [48813, 52026, null], [52026, 55085, null], [55085, 56765, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 56765, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 56765, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 56765, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 56765, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 56765, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 56765, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 56765, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 56765, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 56765, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 56765, null]], "pdf_page_numbers": [[0, 2318, 1], [2318, 5539, 2], [5539, 9200, 3], [9200, 12245, 4], [12245, 15224, 5], [15224, 18097, 6], [18097, 21666, 7], [21666, 24800, 8], [24800, 28018, 9], [28018, 31493, 10], [31493, 34501, 11], [34501, 38449, 12], [38449, 41981, 13], [41981, 45405, 14], [45405, 48813, 15], [48813, 52026, 16], [52026, 55085, 17], [55085, 56765, 18]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 56765, 0.0]]}
olmocr_science_pdfs
2024-12-01
2024-12-01
80ead9d3f96813bc1c47f24c3e9d40be7e2ea0b3
Using classic problems to teach Java framework design H. Conrad Cunningham\textsuperscript{a,}, Yi Liu\textsuperscript{a}, Cuihua Zhang\textsuperscript{b} \textsuperscript{a}Department of Computer and Information Science, University of Mississippi, 201 Weir Hall, University, MS 38677, USA \textsuperscript{b}Department of Computer and Information Systems, Northwest Vista College, AB 135, San Antonio, TX 78251, USA Received 4 October 2004; received in revised form 22 February 2005; accepted 21 March 2005 Available online 8 August 2005 Abstract All programmers should understand the concept of software families and know the techniques for constructing them. This paper suggests that classic problems, such as well-known algorithms and data structures, are good sources for examples to use in a study of software family design. The paper describes two case studies that can be used to introduce students in a Java software design course to the construction of software families using software frameworks. The first is the family of programs that use the well-known divide and conquer algorithmic strategy. The second is the family of programs that carry out traversals of binary trees. © 2005 Elsevier B.V. All rights reserved. Keywords: Software family; Software framework; Hot spot; Design pattern; Divide and conquer; Tree traversal 1. Introduction In a classic paper [17] David Parnas observes, “Variations in application demands, variations in hardware configurations, and the ever-present opportunity to improve a program means that software will \textit{inevitably} exist in many versions”. Parnas proposes that development of a program should therefore be approached as the development of a whole family of related programs. He defines a program family as a set of programs “whose common properties are so extensive that it is advantageous to study the common properties of the programs before analyzing individual members”. If programmers can recognize and exploit these “common aspects and predicted variabilities” [24], the resulting software can be constructed to reuse code for the common parts and to enable convenient adaptation of the variable parts for specific circumstances. In a 2001 article [18], Parnas observes that there is “growing academic interest and some evidence of real industrial success in applying this idea,” yet “the majority of industrial programmers seem to ignore it in their rush to produce code”. He warns [18], “if you are developing a family of programs, you must do so consciously, or you will incur unnecessary long-term costs”. If software families are to become pervasive, future industrial programmers (i.e., students) need to learn to design and construct them effectively. This is an important challenge for computing science and software engineering curricula. How can we respond to this challenge within a college course? The general form of software family is called a software product line. A software product line is “a collection of systems sharing a managed set of features constructed from a common set of core software assets” [1]. These assets include a common software architecture shared by the products and a set of reusable software components [10]. Software product lines in their full generality are difficult to teach in the setting of a college course because their design may require extensive knowledge of the application domain and use of special-purpose languages and tools [24]. However, the form of software family called a software framework is more accessible. A framework is essentially the reusable skeleton of a software product line implemented entirely in an object-oriented programming language. The common aspects are expressed by a set of abstract and concrete “classes that cooperate closely with each other and together embody a reusable solution” [2] to problems in the application domain. The framework can be customized to a specific member of the family by “plugging in” appropriate subclasses at the supported points of variability. Frameworks are more accessible to students because the techniques build upon standard object-oriented concepts that students are taught in undergraduate courses. How can we introduce students to the concept of software frameworks? Some advocate that teaching of frameworks be integrated into the introductory computing science sequence. For example, they might be used to introduce a generalization of sorting algorithms [15] or to provide a new approach to teaching the standard introductory data structures material [23]. They might also provide interesting programming examples and exercises to reinforce object-oriented programming concepts and introduce design patterns into the introductory sequence [13,14,16]. Some textbooks use standard Java libraries such as the Collections, Swing, and input/output frameworks and case studies such as drawing pads as examples to illustrate the concepts and techniques [12]. There are at least four levels of understanding of software frameworks that students need to develop. First, because frameworks are normally implemented in an object-oriented language such as Java, students must understand the applicable language concepts, which include inheritance, polymorphism, encapsulation, and delegation. Second, they need to understand the framework concepts and techniques sufficiently well to use frameworks to build their own custom applications. Third, students should be able to do detailed design and implementation of frameworks for which the common and variable aspects are already known. Fourth, they need to learn to analyze a potential family, identify its possible common and variable aspects, and evaluate alternative framework architectures. In teaching the framework concepts, instructors must devise appropriate case studies. They wish to use several interesting and realistic, but well-focused, examples and exercises to illustrate the framework techniques. However, building a good framework requires an extensive understanding of the application domain addressed by the framework. Because students come to a course with diverse backgrounds and experiences, it may take considerable time for students to come to a sufficient understanding of an application domain to design a framework. This paper takes the view that various classic problems, such as standard algorithms and data structures, are useful in introducing framework concepts and programming techniques when little time is available to spend on the domain analysis. This approach might be used in a dedicated course on software families [5,7] or in teaching modules within an advanced Java programming or software design course. Sections 2 and 3 of this paper seek to address aspects of the second and third levels of understanding noted above—teaching the concepts so that students can use an existing framework and so that they can develop their own frameworks given an analysis of the points of commonality and variability in the family. Section 2 introduces the technical concepts and techniques for construction and use of frameworks. Section 3 illustrates these concepts and techniques using a case study that develops a framework for the family of divide and conquer algorithms and applies it to develop a quicksort application [6]. The case study assumes that the students have a basic understanding of object-oriented programming using Java and understand concepts such as inheritance, polymorphism, delegation, recursion, and sorting. Sections 4 and 5 seek to address aspects of the fourth level of framework understanding—teaching students how to analyze potential families and identify the common and variable aspects. Section 4 introduces the techniques for systematically generalizing an application to discover the points of variability. Section 5 illustrates these concepts using binary tree traversals as the basis for a family [11]. This family of applications includes members ranging from standard preorder, postorder, and in-order traversals to more complicated computations carried out by navigating through binary tree structures in a custom manner. Section 6 discusses related work, and Section 7 summarizes the paper and gives a few observations about use of the techniques in a college course. 2. Framework construction and use In beginning programming classes students are taught to focus on a specific problem and write a program to solve that problem. This is appropriate because beginning students need to learn a particular programming language and grasp specific, concrete programming skills. However, as students gain more experience in programming, they should be taught to work at higher levels of abstraction. Instructors need to shift the students’ focus to techniques for building a software family. In building a software family, it is important to separate concerns. We must separate the aspects of the design that are common to all family members from those aspects that are specific to one family member. Furthermore, we must separate the various common and variable aspects from each other and consider them independently, one at a time. We use the terms frozen spot to denote a common (or shared) aspect of the family and hot spot to denote a variable aspect of the family [22]. A software framework is a generic application that allows the creation of different specific applications from a family [21]. It is an abstract design that can be reused within a whole application domain. In a framework, the frozen spots of the family are represented by a set of abstract and concrete base classes that collaborate in some structure. A behavior that is common to all members of the family is implemented by a fixed, concrete template method in a base class. A hot spot is represented by a group of abstract hook methods. A template method calls a hook method to invoke a function that is specific to one family member. A hot spot is realized in a framework as a hot spot subsystem. A hot spot subsystem typically consists of an abstract base class, concrete subclasses of that base class, and perhaps other related classes [22]. The hook methods of the abstract base class define the interface to the alternative implementations of the hot spot. The subclasses of the base class implement the hook methods appropriately for a particular choice for a hot spot. Fig. 1 shows a UML class diagram of a hot spot subsystem. There are two principles for framework construction—unification and separation [8]. The unification principle uses inheritance to implement the hot spot subsystem. Both the template methods and hook methods are defined in the same abstract base class. The hook methods are implemented in subclasses of the base class. In Fig. 1, the hot spot subsystem for the unification approach consists of the abstract base class and its subclasses. The separation principle uses delegation to implement the hot spot subsystem. The template methods are implemented in a concrete context class; the hook methods are defined in a separate abstract class and implemented in its subclasses. The template methods thus delegate work to an instance of the subclass that implements the hook methods. In Fig. 1, the hot spot subsystem for the separation approach consists of both the client (context) class and the abstract base class and its subclasses. A framework is a system that is designed with generality and reuse in mind; and design patterns [9], which are well-established solutions to program design problems that commonly occur in practice, are the intellectual tools for achieving the desired level of generality and reuse. Two design patterns, corresponding to the two framework construction principles, are useful in implementation of the frameworks. The Template Method pattern uses the unification principle. In using this pattern, a designer should “define the skeleton of an algorithm in an operation, deferring some steps to a subclass” to allow a programmer to “redefine the steps in an algorithm without changing the algorithm’s structure” [9]. It captures the commonalities in the template method in a base class while encapsulating the differences as implementations of hook methods in subclasses, thus ensuring that the basic structure of the algorithm remains the same [8]. The Strategy pattern uses the separation principle. In using this pattern, a designer should “define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it” [9]. It extends the behavior of a client class by calling methods in another class. The common aspects (template methods) are captured in the concrete methods of the client; the variable aspects (hook methods) are declared in the abstract Strategy class and implemented by its subclasses. The behavior of the client class can thus be changed by supplying it with instances of different Strategy subclasses. What is the primary difference between the two construction principles in practice? To introduce new behaviors for hook methods, the unification principle requires programmers to implement a new subclass of the base class defining the template methods. This kind of extension by overriding often requires detailed knowledge of the base class, but it is otherwise relatively straightforward for programmers to understand and implement. The unification principle results in efficient but inflexible execution. To introduce new hook method behavior in a framework that uses the separation principle, the client code needs to instantiate an object from a class that has hook methods with the desired behaviors and supply it to the class containing the template methods. If the needed hook behaviors have been implemented previously, then the programmer must just choose an appropriate implementation from the component library. If the needed hook behaviors have not been implemented, then the programmer must implement an appropriate new class. This class is sometimes more difficult to implement than the equivalent unification solution, but its implementation usually requires less knowledge of the internal details of the class containing the template methods. An application of a framework that uses the separation principle may execute slightly less efficiently than a unification-based framework, but separation may enable the application to adapt itself at runtime by merely changing object references [8]. In the next section, we examine a simple software family and consider framework designs based on each of these design principles. 3. Divide and conquer framework To illustrate the construction and use of a framework, we can use the family of divide and conquer algorithms as an example of a software family. The divide and conquer technique solves a problem by recursively dividing it into one or more subproblems of the same type, solving each subproblem independently, and then combining the subproblem solutions to obtain a solution for the original problem. Well-known algorithms that use this technique include quicksort, mergesort, and binary search. Since this algorithmic strategy can be applied to a whole set of problems of a similar type, divide and conquer, in addition function solve (Problem p) returns Solution { if isSimple(p) return simplySolve(p); else sp[] = decompose(p); for (i= 0; i < sp.length; i = i+1) sol[i] = solve(sp[i]); return combine(sol); } Fig. 2. Divide and conquer pseudo-code. to its meaningful influence in algorithms, serves well the purpose of examining a software family. The pseudo-code for the divide and conquer technique for a problem p is shown in Fig. 2, as it might be presented in an undergraduate algorithms textbook. In this pseudo-code fragment, function solve() represents a template method because its implementation is the same for all algorithms in the family. However, functions isSimple(), simplySolve(), decompose(), and combine() represent hook methods because their implementations vary among the different family members. For example, the simplySolve() function for quicksort is quite different from that for mergesort. For mergesort, the combine() function performs the major work while decompose() is simple. The opposite holds for quicksort and binary search. The remainder of this section illustrates the construction and use of a divide and conquer framework. First, we examine how to construct a framework using the unification principle; then we apply this framework to develop an application using the quicksort algorithm. Finally, we look at how the framework can be implemented using the separation principle. 3.1. Constructing a framework using unification If the unification principle and Template Method pattern are used to structure the divide and conquer framework, then the template method solve() is a concrete method defined in an abstract class; the definitions of the four hook methods are deferred to a concrete subclass whose purpose is to implement a specific algorithm. Fig. 3 shows a design for a divide and conquer framework expressed as a Unified Modeling Language (UML) class diagram. The family includes three members: QuickSort, MergeSort, and BinarySearch. Method solve() is a final method in the base class DivConqTemplate. It is shared among all the classes. Hook methods isSimple(), simplySolve(), decompose(), and combine() are abstract methods in the base class; they are overridden in each concrete subclass (QuickSort, MergeSort, and BinarySearch). To generalize the divide and conquer framework, we introduce the two auxiliary types Problem and Solution. Problem is a type that represents the problem to be solved by the algorithm. Solution is a type that represents the result returned by the algorithm. In Java, we define these types using tag interfaces (i.e., interfaces without any methods) abstract public class DivConqTemplate { public final Solution solve(Problem p) { Problem[] pp; if (isSimple(p)) { return simplySolve(p); } else { pp = decompose(p); } Solution[] ss = new Solution[pp.length]; for(int i=0; i < pp.length; i++) { ss[i] = solve(pp[i]); } return combine(p,ss); } abstract protected boolean isSimple (Problem p); abstract protected Solution simplySolve (Problem p); abstract protected Problem[] decompose (Problem p); abstract protected Solution combine(Problem p,Solution[] ss); } Fig. 4. Template method framework implementation. as follows: public interface Problem {}; public interface Solution {}; Given the auxiliary types above, we define the abstract Template Method class DivConqTemplate as shown in Fig. 4. We generalize the combine() method to take both the description of the problem and the subproblem solution array as arguments. The divide public class QuickSortDesc implements Problem, Solution { public QuickSortDesc(int[] arr, int first, int last) { this.arr = arr; this.first = first; this.last = last; } public int getFirst () { return first; } public int getLast () { return last; } private int[] arr; // instance data private int first, last; } Fig. 5. Quicksort Problem and Solution implementation. and conquer framework thus consists of the DivConqTemplate class and the Problem and Solution interfaces. We can now consider an application built using this framework library. 3.2. Building an application of the framework In using a traditional procedure or class library, a client’s program is in control of the computation; it “calls down” to code from the library. However, frameworks usually exhibit an inversion of control. The framework’s code is in control of the computation; its template methods “call down” to the client-supplied hook methods. This section illustrates the use of the divide and conquer framework to build a quicksort application. Quicksort is an in-place sort of a sequence of values. The description of a problem consists of the sequence of values and designators for the beginning and ending elements of the segment to be sorted. To simplify the presentation, we limit its scope to integer arrays. Therefore, it is sufficient to identify a problem by the array and the beginning and ending indices of the unsorted segment. Similarly, a solution can be identified by the array and the beginning and ending indices of the sorted segment. This similarity between the Problem and Solution descriptions enables us to use the same object to describe both a problem and its corresponding solution. Thus, we introduce the class QuickSortDesc to define the needed descriptor objects as shown in Fig. 5. Given the definitions for base class DivConqTemplate and auxiliary class QuickSortDesc, we can implement the concrete subclass QuickSort as shown in Fig. 6. In a teaching module using this case study, both the framework (i.e., the abstract class) and the framework application (i.e., the implementation of quicksort) can be presented to the students so that they can discern the collaborations and relationships among the classes clearly. However, a clear distinction must be made between the framework and its application. As an exercise, the students can be assigned the task of modifying the quicksort application to handle more general kinds of objects. Other algorithms such as mergesort and binary search should also be assigned as exercises. The amount of work that each hook method has to do differs from one specific algorithm to another. In the quicksort implementation, most of the work is done in the decompose() method, which implements the splitting or pivoting operation of quicksort. In mergesort, however, more work will be done in the combine() operation because it must carry out the merge phase of the mergesort algorithm. public class QuickSort extends DivConqTemplate { protected boolean isSimple (Problem p) { return ((QuickSortDesc)p).getFirst() >= ((QuickSortDesc)p).getLast(); } protected Solution simplySolve (Problem p) { return (Solution) p ; } protected Problem[] decompose (Problem p) { int first = ((QuickSortDesc)p).getFirst(); int last = ((QuickSortDesc)p).getLast(); int[] a = ((QuickSortDesc)p).getArr(); int x = a[first]; // pivot value int sp = first; for (int i = first + 1; i <= last; i++) { if (a[i] < x) { swap (a, ++sp, i); } } swap (a, first, sp); Problem[] ps = new QuickSortDesc[2]; ps[0] = new QuickSortDesc(a,first,sp-1); ps[1] = new QuickSortDesc(a,sp+1,last); return ps; } protected Solution combine (Problem p, Solution[] ss) { return (Solution) p; } private void swap (int[] a, int first, int last) { int temp = a[first]; a[first] = a[last]; a[last] = temp; } } Fig. 6. Quicksort application. 3.3. Constructing a framework using separation As an alternative to the above design, we can use the separation principle and Strategy pattern to implement a divide and conquer framework. The UML class diagram for this approach is shown in Fig. 7. The template method is implemented in the (concrete) context class DivConqContext as shown in Fig. 8. The hook methods are defined in the (abstract) Strategy class DivConqStrategy as shown in Fig. 9. The context class delegates the hook method calls to a reference to the instance of the Strategy class that it stores internally. Note that the Strategy approach is more flexible than the Template Method approach in that it is possible to switch Strategy objects dynamically by using the setAlgorithm() method of the context class. Constructing an application of the Strategy-based framework for Quicksort requires that we implement a subclass of the abstract class DivConqStrategy that is quite similar to the QuickSort class used in the unification framework (shown in Fig. 6). The divide and conquer family of algorithms is a simple example that can be used to illustrate both approaches to framework design. It consists of a set of algorithms that should be known to the students. Hence, the application domain should be easy to explain. In the associated project, students can be given the framework and asked to construct public final class DivConqContext { public DivConqContext (DivConqStrategy dc) { this.dc = dc; } public Solution solve (Problem p) { Problem[] pp; if (dc.isSimple(p)) { return dc.simplySolve(p); } else { pp = dc.decompose(p); } Solution[] ss = new Solution[pp.length]; for (int i = 0; i < pp.length; i++) { ss[i] = solve(pp[i]); } return dc.combine(p, ss); } public void setAlgorithm (DivConqStrategy dc) { this.dc = dc; } private DivConqStrategy dc; } abstract public class DivConqStrategy { abstract public boolean isSimple (Problem p); abstract public Solution simplySolve (Problem p); abstract public Problem[] decompose (Problem p); abstract public Solution combine(Problem p, Solution[] ss); } Fig. 7. Strategy pattern for divide and conquer framework. Fig. 8. Strategy context class implementation. Fig. 9. Strategy object abstract class. applications. This requires an understanding of the framework’s design at a level sufficient for using it, without requiring the students to develop their own framework abstractions. However, the students also need experience in identifying the hot spots and developing the needed framework abstractions. We consider those generalization steps in the following sections. 4. Framework development by generalization Framework design involves incrementally evolving a design rather than discovering it in one single step. Typically, this evolution is a process of examining existing designs for family members, identifying the frozen spots and hot spots of the family, and generalizing the program structure to enable reuse of the code for frozen spots and use of different implementations for each hot spot. This generalization may be done in an informal, organic manner as codified by Roberts and Johnson in the Patterns for Evolving Frameworks [19] or it may be done using more systematic techniques. Schmid’s systematic generalization methodology is one technique [22] that seeks to identify the hot spots a priori and construct a framework systematically. This methodology identifies the following steps for construction of a framework [22]: - creation of a fixed application model, - hot spot analysis and specification, - hot spot high-level design, - generalization transformation. In Schmid's approach, the fixed application model is an object-oriented design for a specific application within the family. Once a complete model exists, the framework designer analyzes the model and the domain to discover and specify the hot spots. The designer begins by asking which of the features of the application are characteristic of all applications in the domain (i.e., frozen spots) and which need to be made flexible (i.e., hot spots). Guided by appropriate design patterns [9], the designer then replaces a fixed, specialized class at a hot spot by an abstract base class. The hot spot’s features are accessed through the common interface of the abstract class. However, the design of the hot spot subsystem enables different concrete subclasses of the base class to be used to provide the variant behaviors. Another systematic approach is function generalization [20]. Where Schmid’s methodology generalizes the class structure of the design for an application, the function generalization approach generalizes the functional structure of a prototype application to produce a generic application [4]. It introduces the hot spot abstractions into the design by replacing concrete operations by more general abstract operations or perhaps by replacing concrete data types by more abstract types. These abstract entities become “parameters” of the generalized functions. That is, the generalized functions are higher-order, having explicit or implicit parameters that are themselves functions. After generalizing the various hot spots of the application, the resulting generalized functions are used to generate a framework in an object-oriented language such as Java. The case study in the next section explains the thinking process that a designer may use in analyzing and designing a framework. It uses an informal technique motivated by Schmid’s systematic generalization and by function generalization. 5. Binary tree traversal framework As a case study on framework generalization, consider another classic problem, a binary tree traversal [11]. This case study seeks to address aspects of the fourth level of framework understanding described in Section 1—learning to analyze potential software families to identify the frozen and hot spots—as well as reinforcing and extending the students’ understanding of the principles and techniques for constructing frameworks. A binary tree is a hierarchical structure that is commonly taught in a lower-level undergraduate data structures course in a computing science curriculum. In this case study, we implement the binary tree with the \texttt{BinTree} class hierarchy, which is a structure designed according to the Composite design pattern [9] as shown in Fig. 10. The Composite pattern “lets clients treat individual objects and compositions of objects uniformly” [9]. Class \texttt{BinTree} has the Component base-class role in the pattern implementation, subclass \texttt{Node} has the Composite role, and subclass \texttt{Nil} has the Leaf role. \texttt{Nil} is also implemented according to the Singleton pattern [9], which guarantees exactly one instance exists. Fig. 11 shows the Java code for the \texttt{BinTree} class hierarchy. A traversal is a systematic technique for “visiting” all the nodes in a tree. One common traversal technique for a binary tree is the \textit{preorder traversal}. This is a depth-first traversal, that is, it accesses a node’s children before it accesses the node’s siblings. The preorder traversal can be expressed by a recursive procedure as follows: ```java procedure preorder(t) { if t null, then return; perform visit action for root node of tree t; preorder(left subtree of t); preorder(right subtree of t); } ``` The visit action varies from application to another. The \texttt{BinTree} hierarchy in Fig. 11 supports a simple preorder traversal operation \texttt{preorder()} that merely prints a node’s value when it is visited. abstract public class BinTree { public void setValue(Object v) { } // mutators public void setLeft(BinTree l) { } // default public void setRight(BinTree r) { } abstract public void preorder(); // traversal public Object getValue() { return null; } // accessors public BinTree getLeft() { return null; } // default public BinTree getRight() { return null; } } public class Node extends BinTree { public Node(Object v, BinTree l, BinTree r) { value = v; left = l; right = r; } public void setValue(Object v) { value = v; } // mutators public void setLeft(BinTree l) { left = l; } public void setRight(BinTree r) { right = r; } public void preorder() // traversal { System.out.println("Visit node with value: "+ value); left.preorder(); right.preorder(); } public Object getValue() { return value; } // accessors public BinTree getLeft() { return left; } public BinTree getRight() { return right; } private Object value; // instance data private BinTree left, right; } public class Nil extends BinTree { private Nil() { } // private to require use of getNil() public void preorder() { }; // traversal static public BinTree getNil() { return theNil; } // Singleton static public BinTree theNil = new Nil(); } Fig. 11. Binary tree class hierarchy. Building a software framework for binary tree traversals involves the general principles for framework design. We begin with the simple preorder operation and tree structure given in Fig. 11 and consider the domain of the family and identify the frozen spots and hot spots. What is the scope of the family of binary tree traversals? The family should include at least the standard kinds of depth-first traversals (e.g., preorder, postorder, and in-order) and allow flexible visit actions on the nodes. In general, the visit action will be a function on the node’s attributes and on the accumulated state of the traversal computed along the sequence of all the nodes accessed to that point in the computation. The framework should enable traversal orders other than the depth first. The framework should also support binary search trees, but it is not necessary that it support multiway trees or general graphs. What, then, are the commonalities, that is, frozen spots, that all members of the family exhibit? Considering the scope and examining the prototype application, we choose the following frozen spots: (1) The structure of the tree, as defined by the BinTree hierarchy, cannot be redefined by clients of the framework. (2) A traversal accesses every element of the tree once, unless the computation determines that it can stop before it completes the traversal. (3) A traversal performs one or more visit actions associated with an access to an element of the tree. What are the variabilities—the hot spots—that exist among members of the family of binary tree traversals? Again considering the scope and examining the prototype application, we identify the primary hot spots to be the following: (1) Variability in the visit operation’s action. It should be a function of the current node’s value and the accumulated result of the visits to the previous nodes in the traversal. (2) Variability in ordering of the visit action with respect to subtree traversals. That is, the client should be able to select preorder, postorder, in-order, etc. (3) Variability in the tree navigation technique. That is, the client should be able to select node access orders other than left-to-right, depth-first, total traversals. Now, given these variabilities, we examine how it can be introduced into a framework by generalizing the prototype application. 5.1. Generalizing the visit action In this case study, hot spot #1 requires making the visit action a feature that can be customized by the client of the framework to meet the specific application’s needs. The visit action, in general, varies from one application to another. The fact that there are visit actions associated with the access to an element is a common behavior of the framework. The visit action itself is the variable behavior that is to be captured in a hot spot subsystem. As we see in Section 2, we can introduce the variable behavior into a framework using either the unification principle (e.g., using the Template method pattern) or the separation principle (e.g., using the Strategy pattern). Because the BinTree structure is a frozen spot (i.e., cannot be changed by the framework user), we choose to use the Strategy pattern to implement variable visit behavior. This allows different visit actions to be used with the same tree structure. We introduce this hot spot into the traversal program by generalizing the classes in the BinTree hierarchy to have the Context role in the Strategy pattern. We generalize the BinTree method preorder to be a template method and define a Strategy interface PreorderStrategy for objects that implement the hook methods. The new implementation of preorder must capture the general concept of a preorder traversal but delegate the specific preorder visit action to a method in a Strategy object. We specify method visitPre on interface PreorderStrategy as the hook method to encapsulate the preorder visit action. Furthermore, we define the preorder method (which had no arguments in the prototype program) to take two arguments: a “state” object that accumulates the relevant aspects of the traversal as the nodes are accessed and an instance of the PreorderStrategy Strategy object. Fig. 12 shows the changes made to the code in Fig. 11 for this generalization step. abstract public class BinTree { abstract public Object preorder(Object ts, PreorderStrategy v); ...} public class Node extends BinTree { ...public Object preorder(Object ts, PreorderStrategy v) // traversal { ts = v.visitPre(ts, this); ts = left.preorder(ts, v); ts = right.preorder(ts, v); return ts; } ... } public class Nil extends BinTree { ...public Object preorder(Object ts, PreorderStrategy v) { return ts; } ... } public interface PreorderStrategy { abstract public Object visitPre(Object ts, BinTree t); } Fig. 12. Binary tree with generalized visit action. 5.2. Generalizing the visit order In this case study, hot spot #2 requires making the “order” of the visit actions a feature that can be customized for a specific application. That is, it must be possible to vary the order of a node’s visit action with respect to the traversals of its children. The framework should support preorder, postorder, and in-order traversals and perhaps combinations of those. A good generalization of the three standard traversals is one that potentially performs a visit action on the node at any of three different points—on first arrival (i.e., a “left” visit), between the subtree traversals (i.e., a “bottom” visit), and just before departure from the node (i.e., a “right” visit). This is sometimes called an Euler tour traversal [11]. We enable the needed variability for this hot spot by generalizing the hot spot subsystem introduced in the previous step instead of introducing a new hot spot subsystem. We generalize the behavior of the preorder method in the BinTree hierarchy and replace it by a method traverse that encodes the common features of all Euler tour traversals but delegates the visit actions at the three possible visit points to hook methods defined on the Strategy object. We also observe that there was no visit action associated with a Nil subtree in the previous versions of the program. In some applications, it might be useful to have some action associated with a visit to a Nil subtree. So we add a fourth hook method for handling this as a special case. In the framework, we thus replace the PreorderStrategy abstract public class BinTree { ... abstract public Object traverse(Object ts, EulerStrategy v); ... } public class Node extends BinTree { ... public Object traverse(Object ts, EulerStrategy v) // traversal { ts = v.visitLeft(ts,this); // upon arrival from above ts = left.traverse(ts,v); ts = v.visitBottom(ts,this); // upon return from left ts = right.traverse(ts,v); ts = v.visitRight(ts,this); // upon completion return ts; } ... } public class Nil extends BinTree { ... public Object traverse(Object ts, EulerStrategy v) { return v.visitNil(ts,this); } ... } public interface EulerStrategy { abstract public Object visitLeft(Object ts, BinTree t); abstract public Object visitBottom(Object ts, BinTree t); abstract public Object visitRight(Object ts, BinTree t); abstract public Object visitNil(Object ts, BinTree t); } Fig. 13. Binary tree with Euler traversal. interface from the previous program with a new EulerStrategy interface that defines the new hook methods. Fig. 13 shows the changes made to the code in Fig. 11 to incorporate the Euler tour traversal order for the visit actions. 5.3. Generalizing the tree navigation In this case study, hot spot #3 requires making the navigation of the tree structure a feature that can be customized to meet the needs of a specific application. In particular, it should enable variability in the order in which nodes are accessed. For example, the framework should support breadth-first traversals as well as depth-first traversals. As we consider this generalization step, two of the frozen spots are of relevance: 1. The BinTree hierarchy cannot be modified by clients of the framework. 2. A traversal must access every element of the tree once, unless the computation determines that it can stop before it completes the traversal. In the previous version of the binary tree traversal framework, the traversal technique is implemented directly by the \texttt{traverse} method of the \texttt{BinTree} hierarchy. The navigation technique implemented by this method must be made a customizable feature of the framework. However, because a client of the framework cannot modify the \texttt{BinTree} class or its subclasses, we must use the separation principle to implement the tree navigation subsystem. We could again use the Strategy pattern. However, another design pattern is more applicable to this situation—the Visitor pattern [9]. The intent of the Visitor pattern is to enable the functionality of an object structure to be extended without modifying the structure’s code. The Visitor pattern does this by putting the new functionality in a separate class. Objects of this Visitor class access the elements of the object structure to carry out the desired new computation. An element of the object structure then calls back to the Visitor’s method corresponding to the element’s type. This “double-dispatching” uses polymorphism to avoid explicit checks on the type of an object. The Visitor pattern is quite compatible with object structures designed according to the Composite design pattern. In the binary tree traversal framework design, we assign the \texttt{BinTree} class hierarchy the role of the Element hierarchy in the Visitor pattern’s description [9], and we introduce a \texttt{BinTreeVisitor} interface to take on the role of the Visitor class in the description. We also generalize the \texttt{traverse} method of the \texttt{BinTree} hierarchy and replace it by the \texttt{accept} method for the Visitor pattern. The \texttt{accept} method of a \texttt{BinTree} element takes a \texttt{BinTreeVisitor} object and delegates the work of the traversal back to an appropriate method of that visitor object. This method applies the appropriate binary tree visit actions and navigates through the tree as needed for the application. The \texttt{BinTreeVisitor} interface has methods named \texttt{visit} with overloaded implementations for each subclass in the \texttt{BinTree} hierarchy. The constraint on the framework given by frozen spot #2 (i.e., to access each node once) becomes a requirement upon the designer of the visitor classes that implement \texttt{BinTreeVisitor}. Fig. 14 illustrates the class structure of a traversal program based on the Visitor design pattern. Fig. 15 shows the Java code for the traversal program. The Visitor framework has two levels. The upper level of the framework is characterized by the Visitor pattern as described above. However, the specific designs for the Visitor objects themselves may be small frameworks. Consider a program to carry out an Euler tour traversal. We can choose to design a concrete class \texttt{EulerTourVisitor} that implements the \texttt{BinTreeVisitor} interface. Similar to the design for hot spot #2’s \texttt{traverse} method, this class delegates the specific traversal visit actions to a Strategy object of type \texttt{EulerStrategy}. Fig. 16 illustrates the class structure of this lower-level design. Fig. 17 shows its implementation in Java. The binary tree traversal framework is quite general. It supports a large set of binary tree algorithms. For example, it is possible using this framework to implement a “mapping” operation on trees. That is, it is feasible to implement a program that changes the value stored at every node of a tree by applying a mapping function to the previous value. Such a program can either be implemented directly as a \texttt{BinTreeVisitor} or as a customization of the Euler tour traversal framework. It is also possible to implement a breadth-first traversal operation by implementing an appropriate \texttt{BinTreeVisitor} class. Other interesting applications of the framework might be to use it to implement programs for binary search trees. Programming projects accompanying use of this case study in a course can require development of various applications or require the design of new kinds of BinTreeVisitor subsystems. Instructors can also ask the students to apply the analysis and design techniques to other possible families. As with the divide and conquer algorithms, binary tree structures and algorithms are well known to computing science and software engineering students. Use of this case study in an upper-level undergraduate course should not require an extensive explanation of the domain of the framework. However, this case study, and the application of the techniques to other problems, does require considerable thought and analysis on the part of the students. It is not a trivial activity for students to discover a sequence of generalization steps and effective hot spot abstractions that are appropriate for a large family of programs. 6. Related work The thesis of this paper is that classic problems, such as those related to classic algorithms and data structures, are helpful examples for instructors to use in teaching computing science and software engineering students techniques for the design of software families. This paper describes two relatively simple examples designed to help teach both the use and construction of the type of software family called a software framework. The abstract public class BinTree { public void setValue(Object v) { } // mutators public void setLeft(BinTree l) { } // default public void setRight(BinTree r) { } abstract public void accept(BinTreeVisitor v); // accept Visitor public Object getValue() { return null; } // accessors public BinTree getLeft() { return null; } // default public BinTree getRight() { return null; } } public class Node extends BinTree { public Node(Object v, BinTree l, BinTree r) { value = v; left = l; right = r; } public void setValue(Object v) { value = v; } // mutators public void setLeft(BinTree l) { left = l; } public void setRight(BinTree r) { right = r; } // accept a Visitor object public void accept(BinTreeVisitor v) { v.visit(this); } public Object getValue() { return value; } // accessors public BinTree getLeft() { return left; } public BinTree getRight() { return right; } private Object value; // instance data private BinTree left, right; } public class Nil extends BinTree { private Nil() { } // private to require use of getNil() // accept a Visitor object public void accept(BinTreeVisitor v) { v.visit(this); } static public BinTree getNil() { return theNil; } // Singleton static public BinTree theNil = new Nil(); } public interface BinTreeVisitor { abstract void visit(Node t); abstract void visit(Nil t); } Fig. 15. Binary tree using Visitor pattern. examples are aimed at advanced Java programming or software design courses in which students have not been previously exposed to frameworks in a significant way. The goal is to improve the students’ abilities to construct and use abstractions in the design of software families. Some advocate that use of frameworks be integrated into the introductory computing science sequence, e.g., into the data structures course [23]. In this approach, the understanding and use of standard data structure frameworks replace many of the traditional topics, which focus on the construction of data structures and algorithms. The availability of standard libraries such as the Java Collections framework makes this a viable approach. The argument is that when students enter the workplace, they more often face public class EulerTourVisitor implements BinTreeVisitor { public EulerTourVisitor(EulerStrategy es, Object ts) { this.es = es; this.ts = ts; } public void setVisitStrategy(EulerStrategy es) // mutators { this.es = es; } public void setResult(Object r) { ts = r; } public void visit(Node t) // Visitor hook implementations { ts = es.visitLeft(ts, t); // upon first arrival from above t.getLeft().accept(this); ts = es.visitBottom(ts, t); // upon return from left t.getRight().accept(this); ts = es.visitRight(ts, t); // upon completion of this node } public void visit(Nil t) { ts = es.visitNil(ts, t); } public Object getResult(){ return ts; } // accessor private EulerStrategy es; // encapsulates state changing ops private Object ts; // traversal state } definitions and implementations of the visitor. Note that the public interface EulerStrategy { abstract public Object visitLeft(Object ts, BinTree t); abstract public Object visitBottom(Object ts, BinTree t); abstract public Object visitRight(Object ts, BinTree t); abstract public Object visitNil(Object ts, BinTree t); } the task of using standard components to build systems than that of writing programs in which they re-implement basic data structures and algorithms. Although it is appropriate that we cultivate the use of high-level abstractions, we should be careful not to abandon the teaching of the intellectual fundamentals of computing science in a desire to train better technicians. Others have constructed small software frameworks that are useful in pedagogical settings. Of particular interest is the work by Nguyen and Wong. In work similar to the divide and conquer example in this paper, they use the Template Method and Strategy patterns and the divide and conquer algorithmic approach to develop a generalized sorting framework [15]. They believe that their design not only gives students “a concrete way of unifying seemingly disparate sorting algorithms but also” helps them understand the algorithms “at the proper level of abstraction”. In an interesting design, they extend their framework to measure algorithm performance in a non-intrusive way by using the Decorator design pattern. The goal of the divide and conquer framework in this paper differs from the goal of Nguyen and Wong’s sorting framework. This paper focuses on teaching framework use and construction. The case study seeks to support any divide and conquer algorithm, not just sorting. The use of sorting algorithms to demonstrate the framework was incidental. However, future development of the divide and conquer framework can benefit from the design techniques illustrated by Nguyen and Wong. In [13], Nguyen and Wong describe an interesting framework design that decouples recursive data structures from the algorithms that manipulate them. The design uses the State and Visitor design patterns to achieve the separation. In subsequent work, using the Strategy and Factory Method patterns, they extend this framework to enable lazy evaluation of the linear structures [14]. Nguyen and Wong’s binary search tree framework in [13] has some similarities to the binary tree traversal framework in this paper. Their work seeks to teach students in introductory data structures courses to encapsulate “variant and invariant behaviors” in separate classes and use well-defined “communication protocols” to combine them into an application program. The use of design patterns, such as Visitor and State, is central to their design technique. The binary tree traversal case study in this paper has a similar goal in the context of teaching students how to design and construct frameworks in general. However, this paper approaches the design as the systematic application of a sequence of generalizing transformations to a prototype application. This systematic technique first identifies a point of variation and then chooses a design pattern that is effective in providing the needed flexibility. While this paper uses design patterns in teaching the construction of frameworks, Christensen approaches the task from the other side [3]. He expresses concern that the conventional “catalogue-like” approaches to teaching design patterns “leave the impression that they are isolated solutions to independent problems”. To overcome this misconception, he advocates the use of well-designed frameworks to teach the effective use of design patterns. He emphasizes that “a framework makes it clear that design patterns work together, and that patterns really define roles” rather than classes. He laments that “the subject of frameworks is sadly overlooked in teaching”. The work in this paper seeks to help remedy that situation. 7. Conclusion The first author has used the divide and conquer example and related programming exercises three times in Java-based courses on software architecture. They are effective in introducing students to the basic principles of framework construction and use if care is taken to distinguish the framework from its application. However, other exercises are needed to help students learn to separate the variable and common aspects of a program family and to define appropriate abstract interfaces for the variable aspects. The binary tree traversal framework case study and a similar case study on a cosequential processing framework \cite{4,20} are designed to illustrate techniques that can help expand the ability of students to discover appropriate framework abstractions. The first author has used the cosequential processing problem (but not the case study) as the basis for a term project in a Java-based course on software engineering \cite{5,7}. It proved to be a problem that challenged the students. However, the students’ feedback indicated that more explicit attention should be paid to teaching systematic techniques for hot spot analysis and design. In summary, software frameworks and design patterns are important concepts that students should learn in an advanced programming or software design course. These concepts may seem very abstract to the students, and, therefore, we need to start with familiar, non-daunting problems. This paper suggests the use of classic problems such as divide and conquer algorithms and binary tree traversals as examples to provide a familiar, simple and understandable environment in which students can better understand the framework concepts. Design patterns, such as the Template Method pattern and the Strategy pattern, are illustrated through the design of these simple frameworks. Since students are familiar with the algorithms and data structures and may have implemented them, they can concentrate on the design process more instead of the coding process and thus learn more effectively how to design a framework and build a program family. Acknowledgements The work of Cunningham and Liu was supported, in part, by a grant from Acxiom Corporation titled “The Acxiom Laboratory for Software Architecture and Component Engineering (ALSACE)”. Liu’s work was also supported by University of Mississippi Graduate School Summer Research and Dissertation Fellowships. The authors thank Will Vaughan, Pallavi Tadepalli, and anonymous referee #1 for making several comments and suggestions that led to improvements in this paper. References \begin{enumerate} \item H.B. Christensen, Frameworks: Putting design patterns into perspective, in: Proceedings of the SIGCSE Conference on Innovation and Technology in Computer Science Education, ITiCSE, ACM, 2004, pp. 142–145. \item H.C. Cunningham, P. Tadepalli, Using function generalization to design a cosequential processing framework, Tech. Rep. UMCIS-2004-22, Department of Computer and Information Science, University of Mississippi, December 2004. \item H.C. Cunningham, Y. Liu, C. Zhang, Keeping secrets within a family: Rediscovering Parnas, in: Proceedings \item H.C. Cunningham, Y. Liu, C. Zhang, Using the divide and conquer strategy to teach Java framework design, in: Proceedings of the International Conference on the Principles and Practice of Programming in Java, \end{enumerate}
{"Source-Url": "http://pages.di.unipi.it/corradini/Didattica/AP-17/DOCS/FrameworkDesignTutorial-paper.pdf", "len_cl100k_base": 11282, "olmocr-version": "0.1.53", "pdf-total-pages": 23, "total-fallback-pages": 0, "total-input-tokens": 50587, "total-output-tokens": 13531, "length": "2e13", "weborganizer": {"__label__adult": 0.0004804134368896485, "__label__art_design": 0.0004825592041015625, "__label__crime_law": 0.00037741661071777344, "__label__education_jobs": 0.006542205810546875, "__label__entertainment": 8.088350296020508e-05, "__label__fashion_beauty": 0.0002033710479736328, "__label__finance_business": 0.0002162456512451172, "__label__food_dining": 0.000461578369140625, "__label__games": 0.0007500648498535156, "__label__hardware": 0.0006542205810546875, "__label__health": 0.0003910064697265625, "__label__history": 0.00030112266540527344, "__label__home_hobbies": 0.00011467933654785156, "__label__industrial": 0.00037479400634765625, "__label__literature": 0.0004072189331054687, "__label__politics": 0.00037169456481933594, "__label__religion": 0.0005793571472167969, "__label__science_tech": 0.00373077392578125, "__label__social_life": 0.00013625621795654297, "__label__software": 0.0036220550537109375, "__label__software_dev": 0.978515625, "__label__sports_fitness": 0.0003802776336669922, "__label__transportation": 0.0007052421569824219, "__label__travel": 0.0002532005310058594}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 59246, 0.01036]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 59246, 0.86039]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 59246, 0.85813]], "google_gemma-3-12b-it_contains_pii": [[0, 1717, false], [1717, 5561, null], [5561, 8986, null], [8986, 11776, null], [11776, 15268, null], [15268, 17942, null], [17942, 18920, null], [18920, 21892, null], [21892, 24296, null], [24296, 25210, null], [25210, 28525, null], [28525, 30566, null], [30566, 33030, null], [33030, 36210, null], [36210, 38443, null], [38443, 40362, null], [40362, 44314, null], [44314, 45693, null], [45693, 47959, null], [47959, 49707, null], [49707, 53036, null], [53036, 56515, null], [56515, 59246, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1717, true], [1717, 5561, null], [5561, 8986, null], [8986, 11776, null], [11776, 15268, null], [15268, 17942, null], [17942, 18920, null], [18920, 21892, null], [21892, 24296, null], [24296, 25210, null], [25210, 28525, null], [28525, 30566, null], [30566, 33030, null], [33030, 36210, null], [36210, 38443, null], [38443, 40362, null], [40362, 44314, null], [44314, 45693, null], [45693, 47959, null], [47959, 49707, null], [49707, 53036, null], [53036, 56515, null], [56515, 59246, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 59246, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 59246, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 59246, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 59246, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 59246, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 59246, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 59246, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 59246, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 59246, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 59246, null]], "pdf_page_numbers": [[0, 1717, 1], [1717, 5561, 2], [5561, 8986, 3], [8986, 11776, 4], [11776, 15268, 5], [15268, 17942, 6], [17942, 18920, 7], [18920, 21892, 8], [21892, 24296, 9], [24296, 25210, 10], [25210, 28525, 11], [28525, 30566, 12], [30566, 33030, 13], [33030, 36210, 14], [36210, 38443, 15], [38443, 40362, 16], [40362, 44314, 17], [44314, 45693, 18], [45693, 47959, 19], [47959, 49707, 20], [49707, 53036, 21], [53036, 56515, 22], [56515, 59246, 23]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 59246, 0.0]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
63c0ca00b0d526274669cbbc65c727c9e2e343fd
[REMOVED]
{"Source-Url": "http://www.research.ed.ac.uk/portal/files/28293677/RR_16_4.pdf", "len_cl100k_base": 14758, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 68172, "total-output-tokens": 16715, "length": "2e13", "weborganizer": {"__label__adult": 0.0004148483276367187, "__label__art_design": 0.0006084442138671875, "__label__crime_law": 0.0006451606750488281, "__label__education_jobs": 0.0037326812744140625, "__label__entertainment": 0.00022089481353759768, "__label__fashion_beauty": 0.00026154518127441406, "__label__finance_business": 0.0008668899536132812, "__label__food_dining": 0.0005788803100585938, "__label__games": 0.0013494491577148438, "__label__hardware": 0.0010290145874023438, "__label__health": 0.0010700225830078125, "__label__history": 0.0005774497985839844, "__label__home_hobbies": 0.00021207332611083984, "__label__industrial": 0.0008296966552734375, "__label__literature": 0.0012254714965820312, "__label__politics": 0.0004000663757324219, "__label__religion": 0.0006833076477050781, "__label__science_tech": 0.454345703125, "__label__social_life": 0.0001786947250366211, "__label__software": 0.0223236083984375, "__label__software_dev": 0.5068359375, "__label__sports_fitness": 0.0002810955047607422, "__label__transportation": 0.0008835792541503906, "__label__travel": 0.0002772808074951172}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 53391, 0.01097]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 53391, 0.55465]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 53391, 0.86258]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 3149, false], [3149, 7045, null], [7045, 9817, null], [9817, 12662, null], [12662, 16808, null], [16808, 21590, null], [21590, 25535, null], [25535, 29129, null], [29129, 31951, null], [31951, 35646, null], [35646, 39071, null], [39071, 42048, null], [42048, 45570, null], [45570, 50013, null], [50013, 53391, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 3149, true], [3149, 7045, null], [7045, 9817, null], [9817, 12662, null], [12662, 16808, null], [16808, 21590, null], [21590, 25535, null], [25535, 29129, null], [29129, 31951, null], [31951, 35646, null], [35646, 39071, null], [39071, 42048, null], [42048, 45570, null], [45570, 50013, null], [50013, 53391, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 53391, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 53391, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 53391, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 53391, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 53391, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 53391, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 53391, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 53391, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 53391, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 53391, null]], "pdf_page_numbers": [[0, 0, 1], [0, 3149, 2], [3149, 7045, 3], [7045, 9817, 4], [9817, 12662, 5], [12662, 16808, 6], [16808, 21590, 7], [21590, 25535, 8], [25535, 29129, 9], [29129, 31951, 10], [31951, 35646, 11], [35646, 39071, 12], [39071, 42048, 13], [42048, 45570, 14], [45570, 50013, 15], [50013, 53391, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 53391, 0.0]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
cc59e89d344d84530cff503dbdab645078eb5877
Welcome to PeakSegDisk, an R package for optimal peak detection in very large count data sequences. 1 Related work The PeakSeg R packages contain algorithms for inferring optimal segmentation models subject to the constraint that up changes must be followed by down changes, and vice versa. This ensures that the model can be interpreted in terms of peaks (after up changes) and background (after down changes). PeakSegDP the historically first PeakSeg package, [https://CRAN.R-project.org/package=PeakSegDP](https://CRAN.R-project.org/package=PeakSegDP) provides a heuristic quadratic time algorithm for computing models from 1 to S segments for a single sample. This was the original algorithm described in our ICML’15 paper, [http://jmlr.org/proceedings/papers/v37/hocking15.html](http://jmlr.org/proceedings/papers/v37/hocking15.html) but it is neither fast nor optimal, so in practice we recommend to use our newer packages below instead. PeakSegOptimal [https://CRAN.R-project.org/package=PeakSegOptimal](https://CRAN.R-project.org/package=PeakSegOptimal) provides log-linear time algorithms for computing optimal models with multiple peaks for a single sample. The algorithms are faster and more accurate than PeakSegDP, [https://arxiv.org/abs/1703.03352](https://arxiv.org/abs/1703.03352) PeakSegDisk [https://github.com/tdhock/PeakSegDisk](https://github.com/tdhock/PeakSegDisk) provides an on-disk implementation of optimal log-linear algorithms for computing multiple peaks in a single sample. Computes same models as PeakSegOptimal but works for much larger data sets because disk is used for storage instead of memory. [https://arxiv.org/abs/1810.00117](https://arxiv.org/abs/1810.00117) PeakSegJoint [https://CRAN.R-project.org/package=PeakSegJoint](https://CRAN.R-project.org/package=PeakSegJoint) provides a fast heuristic algorithm for computing models with a single common peak in 0,..., S samples. [https://arxiv.org/abs/1506.01286](https://arxiv.org/abs/1506.01286) PeakSegPipeline [https://github.com/tdhock/PeakSegPipeline](https://github.com/tdhock/PeakSegPipeline) provides a pipeline for genome-wide peak calling using the other PeakSeg packages. The remainder of this vignette is dedicated to an explanation of how to use PeakSegDisk. 2 Simulate a noisy integer vector with changes The first example we will treat is detecting peaks in a vector of integer data, with possibly the same values at adjacent positions. This is an inefficient representation for large genomic data, but it is the typical output from simulation functions like `rpois`: sim.seg <- function(seg.mean, size.mean=15){ seg.size <- rpois(1, size.mean) rpois(seg.size, seg.mean) } set.seed(1) seg.mean.vec <- c(1.5, 3.5, 0.5, 4.5, 2.5) z.list <- lapply(seg.mean.vec, sim.seg) (z.rep.vec <- unlist(z.list)) From the output above it is clear that these simulated data are integers, with some identical values at adjacent positions. Below we put these data into a data table in order to plot them along with the model using ggplot2: count.df <- data.frame( chrom="chrUnknown", chromStart=0:(length(z.rep.vec)-1), chromEnd=1:length(z.rep.vec), count=z.rep.vec) library(ggplot2) gg.count <- ggplot()+ xlab("position")+ geom_point(aes( chromEnd, count), shape=1, data=count.df) gg.count The true changepoints in the simulation are shown below. 3 Segment a vector of integers Let $z_1, \ldots, z_n \in \mathbb{Z}_+$ be the sequence of $n$ non-negative count data in z.rep.vec, and let $w_1 = \cdots = w_n = 1$ be weights which are all 1. The peak detection algorithm computes the solution to the following optimization problem: $$\begin{align*} \text{minimize} & \quad \sum_{i=1}^{n} w_i \ell(m_i, z_i) + \lambda \sum_{i=1}^{n-1} I(c_i = 1) \\ \text{subject to} & \quad c_i = 0 \Rightarrow m_i = m_{i+1} \text{ and } s_i = s_{i+1} \\ & \quad c_i = 1 \Rightarrow m_i \leq m_{i+1} \text{ and } (s_i, s_{i+1}) = (0, 1), \\ & \quad c_i = -1 \Rightarrow m_i \geq m_{i+1} \text{ and } (s_i, s_{i+1}) = (1, 0), \\ & \quad \text{start and end down: } s_1 = s_n = 0. \end{align*}$$ where \( f(m, z) = m - z \log m \) is the Poisson loss. The optimization variables are \( m_i \) for the segment mean, \( s_i \) for hidden state, and \( c_i \) for type of changepoint. The penalty term is proportional to the number of changepoint variables \( c_i \) which are equal to 1 (which is the same as the number of peaks in the resulting model). To run the peak detection algorithm a numeric penalty parameter \( \lambda \geq 0 \) must be specified by the user. The smallest value is 0 which yields max peaks, and the largest value is Inf which yields no peaks. The code below runs the peak detection algorithm on this count data vector, using the penalty parameter \( \lambda = 10.5 \): ```r fit <- list() (fit$vec <- PeakSegDisk::PeakSegFPOP_vec(z.rep.vec, 10.5)) ``` ``` $segments $> chrom chromStart chromEnd status mean $> 1: chrUnknown 69 75 background 2.166670 $> 2: chrUnknown 41 69 peak 3.714290 $> 3: chrUnknown 26 41 background 0.533333 $> 4: chrUnknown 12 26 peak 3.571430 $> 5: chrUnknown 0 12 background 1.583330 $loss $> penalty segments peaks bases bedGraph.lines mean.pen.cost total.loss equality.constraints mean.intervals max.intervals megabytes seconds $> 1: 10.5 5 2 75 60 0.01507491 -19.86938 $> $data $> chrom chromStart chromEnd count $> 1: chrUnknown 0 1 3 $> 2: chrUnknown 1 2 0 $> 3: chrUnknown 2 3 3 $> 4: chrUnknown 3 4 4 $> 5: chrUnknown 4 6 2 $> 6: chrUnknown 6 9 0 $> 7: chrUnknown 9 10 2 $> 8: chrUnknown 10 11 1 $> 9: chrUnknown 11 12 2 $>10: chrUnknown 12 13 9 $>11: chrUnknown 13 14 3 $>12: chrUnknown 14 15 5 $>13: chrUnknown 15 16 6 $>14: chrUnknown 16 17 2 $>15: chrUnknown 17 18 4 $>16: chrUnknown 18 19 1 $>17: chrUnknown 19 20 2 $>18: chrUnknown 20 21 3 $>19: chrUnknown 21 22 0 ``` The model output list above includes segments, a data table with one row for each segment mean, and loss, a data table with one row that reports the model meta-data. Of interest are: - penalty, the user-provided penalty value, - segments, the number of segments, - peaks, the number of peaks (even-numbered segments), - bases, the number of data points in repetitive form (not run-length encoding), - bedGraph.lines, the number of data points in run-length encoding form, - mean.pen.cost, the optimal mean loss plus penalty*peaks, - total.loss, the optimal total Poisson loss over all data points, - equality.constraints, the number of adjacent segment means that are equal in the optimal solution. Note that when this number is greater than 0, then there are some active equality constraints, and the optimal model is therefore not feasible for the strict inequality constraints, which implies that the optimum of the problem with strict inequality constraints is undefined, i.e. for any sub-optimal solution that satisfies the strict inequality constraints, we can find a lower cost solution that satisfies the strict inequality constraints (but is still sub-optimal), by getting closer to the solution with active equality constraints. - megabytes, the storage space on disk used by the solver, - seconds, the amount of time used by the solver, - mean.intervals, max.intervals, statistics over all intervals (candidate changepoints) computed by the functional pruning algorithm, useful for analyzing computational complexity, which is linear in the number of intervals. Note in particular that PeakSegFPOP_vec internally uses rle to construct a run-length encoding, which is passed to the solver to save time/storage. In this case the repetitive integer data vector contains 75 elements but the coverage.bedGraph data file contains only 60 lines. In real genomic data sets the difference is typically much larger. ```r gg.change+ geom_segment(aes( chromStart+0.5, mean, xend=chromEnd+0.5, yend=mean, color=model), data=data.frame(fit$vec$segments, model="fitted")) ``` It is clear from the plot above that the first three changepoints are estimated exactly and the last one is a bit over-estimated. Also note that a default plot method is defined for these objects: ```r plot(fit$vec) ``` 4 Segment a data frame Another interface that can be used on a data.frame with \( n \) rows and exactly 4 columns (chrom, chrom-Start, chromEnd, count) is `PeakSegFPDF_df`. For each row \( i \in \{1, \ldots, n\} \), let \( z_i \in \mathbb{Z}_+ \) be the non-negative count data (count column), and let \( w_i > 0 \) be the weight (equal to the number of bases, chromEnd-chromStart). The optimization problem we solve is the same as before. Note that this function does not perform run-length encoding for you: ```r (fit$df <- PeakSegDisk::PeakSegFPoP_df(count.df, 10.5)) #> $segments #> #> $loss #> #> $data ``` <table> <thead> <tr> <th>#</th> <th>chrUnknown</th> <th>29</th> <th>30</th> <th>1</th> </tr> </thead> <tbody> <tr> <td>30</td> <td>chrUnknown</td> <td>30</td> <td>31</td> <td>0</td> </tr> <tr> <td>31</td> <td>chrUnknown</td> <td>31</td> <td>32</td> <td>1</td> </tr> <tr> <td>32</td> <td>chrUnknown</td> <td>32</td> <td>33</td> <td>0</td> </tr> <tr> <td>33</td> <td>chrUnknown</td> <td>33</td> <td>34</td> <td>1</td> </tr> <tr> <td>34</td> <td>chrUnknown</td> <td>34</td> <td>35</td> <td>1</td> </tr> <tr> <td>35</td> <td>chrUnknown</td> <td>35</td> <td>36</td> <td>1</td> </tr> <tr> <td>36</td> <td>chrUnknown</td> <td>36</td> <td>37</td> <td>0</td> </tr> <tr> <td>37</td> <td>chrUnknown</td> <td>37</td> <td>38</td> <td>0</td> </tr> <tr> <td>38</td> <td>chrUnknown</td> <td>38</td> <td>39</td> <td>1</td> </tr> <tr> <td>39</td> <td>chrUnknown</td> <td>39</td> <td>40</td> <td>0</td> </tr> <tr> <td>40</td> <td>chrUnknown</td> <td>40</td> <td>41</td> <td>0</td> </tr> <tr> <td>41</td> <td>chrUnknown</td> <td>41</td> <td>42</td> <td>4</td> </tr> <tr> <td>42</td> <td>chrUnknown</td> <td>42</td> <td>43</td> <td>7</td> </tr> <tr> <td>43</td> <td>chrUnknown</td> <td>43</td> <td>44</td> <td>4</td> </tr> <tr> <td>44</td> <td>chrUnknown</td> <td>44</td> <td>45</td> <td>3</td> </tr> <tr> <td>45</td> <td>chrUnknown</td> <td>45</td> <td>46</td> <td>2</td> </tr> <tr> <td>46</td> <td>chrUnknown</td> <td>46</td> <td>47</td> <td>2</td> </tr> <tr> <td>47</td> <td>chrUnknown</td> <td>47</td> <td>48</td> <td>3</td> </tr> <tr> <td>48</td> <td>chrUnknown</td> <td>48</td> <td>49</td> <td>4</td> </tr> <tr> <td>49</td> <td>chrUnknown</td> <td>49</td> <td>50</td> <td>5</td> </tr> <tr> <td>50</td> <td>chrUnknown</td> <td>50</td> <td>51</td> <td>4</td> </tr> <tr> <td>51</td> <td>chrUnknown</td> <td>51</td> <td>52</td> <td>7</td> </tr> <tr> <td>52</td> <td>chrUnknown</td> <td>52</td> <td>53</td> <td>3</td> </tr> <tr> <td>53</td> <td>chrUnknown</td> <td>53</td> <td>54</td> <td>4</td> </tr> <tr> <td>54</td> <td>chrUnknown</td> <td>54</td> <td>55</td> <td>3</td> </tr> <tr> <td>55</td> <td>chrUnknown</td> <td>55</td> <td>56</td> <td>5</td> </tr> <tr> <td>56</td> <td>chrUnknown</td> <td>56</td> <td>57</td> <td>3</td> </tr> <tr> <td>57</td> <td>chrUnknown</td> <td>57</td> <td>58</td> <td>4</td> </tr> <tr> <td>58</td> <td>chrUnknown</td> <td>58</td> <td>59</td> <td>4</td> </tr> <tr> <td>59</td> <td>chrUnknown</td> <td>59</td> <td>60</td> <td>2</td> </tr> <tr> <td>60</td> <td>chrUnknown</td> <td>60</td> <td>61</td> <td>4</td> </tr> <tr> <td>61</td> <td>chrUnknown</td> <td>61</td> <td>62</td> <td>2</td> </tr> <tr> <td>62</td> <td>chrUnknown</td> <td>62</td> <td>63</td> <td>2</td> </tr> <tr> <td>63</td> <td>chrUnknown</td> <td>63</td> <td>64</td> <td>2</td> </tr> <tr> <td>64</td> <td>chrUnknown</td> <td>64</td> <td>65</td> <td>5</td> </tr> <tr> <td>65</td> <td>chrUnknown</td> <td>65</td> <td>66</td> <td>4</td> </tr> <tr> <td>66</td> <td>chrUnknown</td> <td>66</td> <td>67</td> <td>2</td> </tr> <tr> <td>67</td> <td>chrUnknown</td> <td>67</td> <td>68</td> <td>4</td> </tr> <tr> <td>68</td> <td>chrUnknown</td> <td>68</td> <td>69</td> <td>6</td> </tr> <tr> <td>69</td> <td>chrUnknown</td> <td>69</td> <td>70</td> <td>2</td> </tr> <tr> <td>70</td> <td>chrUnknown</td> <td>70</td> <td>71</td> <td>3</td> </tr> <tr> <td>71</td> <td>chrUnknown</td> <td>71</td> <td>72</td> <td>2</td> </tr> <tr> <td>72</td> <td>chrUnknown</td> <td>72</td> <td>73</td> <td>2</td> </tr> <tr> <td>73</td> <td>chrUnknown</td> <td>73</td> <td>74</td> <td>3</td> </tr> <tr> <td>74</td> <td>chrUnknown</td> <td>74</td> <td>75</td> <td>1</td> </tr> <tr> <td>75</td> <td>chrUnknown</td> <td>74</td> <td>75</td> <td>1</td> </tr> </tbody> </table> Note how `bedGraph.lines` is now the same size as `bases`, 75. The time/storage complexity is log-linear in the number of `bedGraph.lines`, so it is more efficient to use the run-length encoding. This can be easily done in R: ```r z.rle.vec <- rle(z.rep.vec) chromEnd <- cumsum(z.rle.vec$lengths) rle.df <- data.frame( chrom="chrUnknown", chromStart=c(0L, chromEnd[-length(chromEnd)]), chromEnd, count=z.rle.vec$values) gg.rle <- ggplot()+ geom_segment(aes(chromStart+0.5, count, xend=chromEnd+0.5, yend=count), data=rle.df)+ geom_point(aes(chromEnd, count), shape=1, data=rle.df)+ geom_vline(aes(xintercept=changepoint, color=model), data=data.frame(change.df, model="simulation"))+ scale_color_manual( values=c( simulation="black", fitted="green"))+ xlab("position") gg.rle ``` The plot above shows the run-length encoded data, with a `geom_point` for the last position in each run, and a `geom_segment` extending left to the first position. These data can be segmented as above: ```r (fit$rle <- PeakSegDisk::PeakSegFPOP_df(rle.df, 10.5)) ``` ```r table$f$segments #> chrom chromStart chromEnd status mean #> 1: chrUnknown 69 75 background 2.166670 #> 2: chrUnknown 41 69 peak 3.714290 #> 3: chrUnknown 26 41 background 0.533333 #> 4: chrUnknown 12 26 peak 3.571430 #> 5: chrUnknown 0 12 background 1.583330 ``` ```r table$f$loss #> penalty segments peaks bases bedGraph.lines mean.pen.cost total.loss #> 1: 10.5 5 2 75 60 0.01507491 -19.86938 ``` ```r table$f$data #> chrom chromStart chromEnd count #> 1: chrUnknown 0 1 3 #> 2: chrUnknown 1 2 0 #> 3: chrUnknown 2 3 3 #> 4: chrUnknown 3 4 4 #> 5: chrUnknown 4 6 2 #> 6: chrUnknown 6 9 0 #> 7: chrUnknown 9 10 2 #> 8: chrUnknown 10 11 1 #> 9: chrUnknown 11 12 2 #> 10: chrUnknown 12 13 9 #> 11: chrUnknown 13 14 3 ``` <table> <thead> <tr> <th>#</th> <th>chrUnknown</th> <th>14</th> <th>15</th> <th>5</th> </tr> </thead> <tbody> <tr> <td>13</td> <td>chrUnknown</td> <td>15</td> <td>16</td> <td>6</td> </tr> <tr> <td>14</td> <td>chrUnknown</td> <td>16</td> <td>17</td> <td>2</td> </tr> <tr> <td>15</td> <td>chrUnknown</td> <td>17</td> <td>18</td> <td>4</td> </tr> <tr> <td>16</td> <td>chrUnknown</td> <td>18</td> <td>19</td> <td>1</td> </tr> <tr> <td>17</td> <td>chrUnknown</td> <td>19</td> <td>20</td> <td>2</td> </tr> <tr> <td>18</td> <td>chrUnknown</td> <td>20</td> <td>21</td> <td>3</td> </tr> <tr> <td>19</td> <td>chrUnknown</td> <td>21</td> <td>22</td> <td>0</td> </tr> <tr> <td>20</td> <td>chrUnknown</td> <td>22</td> <td>23</td> <td>3</td> </tr> <tr> <td>21</td> <td>chrUnknown</td> <td>23</td> <td>24</td> <td>6</td> </tr> <tr> <td>22</td> <td>chrUnknown</td> <td>24</td> <td>26</td> <td>3</td> </tr> <tr> <td>23</td> <td>chrUnknown</td> <td>26</td> <td>27</td> <td>0</td> </tr> <tr> <td>24</td> <td>chrUnknown</td> <td>27</td> <td>30</td> <td>1</td> </tr> <tr> <td>25</td> <td>chrUnknown</td> <td>30</td> <td>31</td> <td>0</td> </tr> <tr> <td>26</td> <td>chrUnknown</td> <td>31</td> <td>32</td> <td>1</td> </tr> <tr> <td>27</td> <td>chrUnknown</td> <td>32</td> <td>33</td> <td>0</td> </tr> <tr> <td>28</td> <td>chrUnknown</td> <td>33</td> <td>36</td> <td>1</td> </tr> <tr> <td>29</td> <td>chrUnknown</td> <td>36</td> <td>38</td> <td>0</td> </tr> <tr> <td>30</td> <td>chrUnknown</td> <td>38</td> <td>39</td> <td>1</td> </tr> <tr> <td>31</td> <td>chrUnknown</td> <td>39</td> <td>41</td> <td>0</td> </tr> <tr> <td>32</td> <td>chrUnknown</td> <td>41</td> <td>42</td> <td>4</td> </tr> <tr> <td>33</td> <td>chrUnknown</td> <td>42</td> <td>43</td> <td>7</td> </tr> <tr> <td>34</td> <td>chrUnknown</td> <td>43</td> <td>44</td> <td>4</td> </tr> <tr> <td>35</td> <td>chrUnknown</td> <td>44</td> <td>45</td> <td>3</td> </tr> <tr> <td>36</td> <td>chrUnknown</td> <td>45</td> <td>47</td> <td>2</td> </tr> <tr> <td>37</td> <td>chrUnknown</td> <td>47</td> <td>48</td> <td>3</td> </tr> <tr> <td>38</td> <td>chrUnknown</td> <td>48</td> <td>49</td> <td>4</td> </tr> <tr> <td>39</td> <td>chrUnknown</td> <td>49</td> <td>50</td> <td>5</td> </tr> <tr> <td>40</td> <td>chrUnknown</td> <td>50</td> <td>51</td> <td>4</td> </tr> <tr> <td>41</td> <td>chrUnknown</td> <td>51</td> <td>52</td> <td>7</td> </tr> <tr> <td>42</td> <td>chrUnknown</td> <td>52</td> <td>53</td> <td>3</td> </tr> <tr> <td>43</td> <td>chrUnknown</td> <td>53</td> <td>54</td> <td>4</td> </tr> <tr> <td>44</td> <td>chrUnknown</td> <td>54</td> <td>55</td> <td>3</td> </tr> <tr> <td>45</td> <td>chrUnknown</td> <td>55</td> <td>56</td> <td>5</td> </tr> <tr> <td>46</td> <td>chrUnknown</td> <td>56</td> <td>57</td> <td>3</td> </tr> <tr> <td>47</td> <td>chrUnknown</td> <td>57</td> <td>59</td> <td>4</td> </tr> <tr> <td>48</td> <td>chrUnknown</td> <td>59</td> <td>60</td> <td>2</td> </tr> <tr> <td>49</td> <td>chrUnknown</td> <td>60</td> <td>61</td> <td>4</td> </tr> <tr> <td>50</td> <td>chrUnknown</td> <td>61</td> <td>64</td> <td>2</td> </tr> <tr> <td>51</td> <td>chrUnknown</td> <td>64</td> <td>65</td> <td>5</td> </tr> <tr> <td>52</td> <td>chrUnknown</td> <td>65</td> <td>66</td> <td>4</td> </tr> <tr> <td>53</td> <td>chrUnknown</td> <td>66</td> <td>67</td> <td>2</td> </tr> <tr> <td>54</td> <td>chrUnknown</td> <td>67</td> <td>68</td> <td>4</td> </tr> <tr> <td>55</td> <td>chrUnknown</td> <td>68</td> <td>69</td> <td>6</td> </tr> <tr> <td>56</td> <td>chrUnknown</td> <td>69</td> <td>70</td> <td>2</td> </tr> <tr> <td>57</td> <td>chrUnknown</td> <td>70</td> <td>71</td> <td>3</td> </tr> </tbody> </table> 5 Write the file yourself The interfaces discussed in the previous sections are perhaps the most intuitive for useRs, but they are also the least efficient, so they are not recommended for large data. In this section we introduce the most efficient way of using PeakSegDisk, which involves: - creating a “problem” directory for each segmentation problem (sample and genome subset), - saving the data to coverage.bedGraph in that directory, - and then running PeakSegFPOP_dir. The reason why this method is recommended for large data is because PeakSegFPOP_dir saves its results to the “problem” directory. So if a certain result has already been computed, these result files are used as a cache, and are read instead of doing computations, which saves a lot of time. The file system is used as the interface in order to support very large data sets with very little memory usage. To use PeakSegFPOP_dir the data should be saved to a chrXX-start-end/coverage.bedGraph file, where the problem directory “chrXX-start-end” should be named using a genome position string: • chrXX is the chromosome (which is irrelevant to the algorithm), • start is the 0-based first position of the region to segment (the smallest possible value is 0), • end is the 1-based end position (the smallest possible value is 1). data.dir <- file.path( tempfile(), with(rle.df, sprintf( "%s-%d-%d", chrom[1], min(chromStart), max(chromEnd)))) dir.create(data.dir, showWarnings=FALSE, recursive=TRUE) coverage.bedGraph <- file.path(data.dir, "coverage.bedGraph") write.table( rle.df, coverage.bedGraph, sep="\t", row.names=FALSE, col.names=FALSE) The next step is to run the main solver, (fit$dir <- PeakSegDisk::PeakSegFPOP_dir(data.dir, 10.5)) #> $segments #> chrom chromStart chromEnd status mean #> 1: chrUnknown 69 75 background 2.166670 #> 2: chrUnknown 41 69 peak 3.714290 #> 3: chrUnknown 26 41 background 0.533333 #> 4: chrUnknown 12 26 peak 3.571430 #> 5: chrUnknown 0 12 background 1.583330 #> #> $loss #> penalty segments peaks bases bedGraph.lines mean.pen.cost total.loss #> 1: 10.5 5 2 75 60 0.01507491 -19.86938 The underlying C++ code creates penalty-specific files such as chrXX-start-end/coverage.bedGraph_penalty=0.1_loss.tsv which are used to store/cache the results. If the files already exist (and are consistent) then PeakSegFPOP_dir just reads them; otherwise it runs the dynamic programming C++ code in order to create those files, which are then read into R. 6 Computing the model with a given number of peaks The sequentialSearch_dir function can be used to compute the optimal model with a certain number of peaks: The algorithm must evaluate several penalty values to compute the optimal model with a certain number of peaks. The \texttt{others} component of the model list above shows that - the search starts with penalty values 0 and Inf, which result in models with 26 and 0 peaks, respectively. - the next penalty evaluated is 2.21, which results in 6 peaks. - the final penalty evaluated is 7.12, which results in 2 peaks. At each step (except the first) the new penalties are computed based on the loss values found in the previous step. If present with a registered parallel future plan, the `future.apply` package is used to run the first step (penalties 0, ∞) in parallel. Note how the number of peaks and total.loss of this model is the same as the other models computed above. ```r lossDF <- function(L) data.frame(L$loss)[, names(fit$dir$loss)] do.call(rbind, lapply(fit, lossDF)) ``` ```r #> #> penalty segments peaks bases bedGraph.lines mean.pen.cost total.loss #> vec 10.500000 5 2 75 60 0.01507491 -19.86938 #> df 10.500000 5 2 75 75 0.01507491 -19.86938 #> rle 10.500000 5 2 75 60 0.01507491 -19.86938 #> dir 10.500000 5 2 75 60 0.01507491 -19.86938 #> search 7.119506 5 2 75 60 0.07507161 -19.86938 #> #> equality.constraints mean.intervals max.intervals megabytes seconds #> vec 0 4.600000 8 0.01372147 0.005 #> df 0 4.633333 8 0.01725006 0.005 #> rle 0 4.600000 8 0.01372147 0.004 #> dir 0 4.600000 8 0.01372147 0.004 #> search 0 4.558333 9 0.01362610 0.004 ``` Finally we demonstrate how the filesystem caching is especially useful for the sequential search. In the code below we ask the sequential search algorithm to compute the optimal model with four peaks: ```r four.peaks <- PeakSegDisk::sequentialSearch_dir(data.dir, 4L) four.peaks$others[, .(iteration, penalty, peaks)] ``` ```r #> #> iteration penalty peaks #> 1: 1 0.000000 26 #> 2: 1 Inf 0 #> 3: 2 2.209918 6 #> 4: 3 7.119506 2 #> 5: 4 3.304860 3 #> 6: 5 2.830674 5 #> 7: 6 3.107790 4 ``` Looking at the output above, we see that the first three iterations of the sequential search require computing models with 26, 0, 6, 2 peaks. Since all of these have been previously computed (and saved to disk), the dynamic programming algorithm does not need to be re-run, and instead the model results are simply read from the files. After that the dynamic programming is run for the subsequent iterations 4-6. In this particular example the savings in computation time is not extraordinary, but in real genomic data, this can result in substantial speed-ups.
{"Source-Url": "https://cran.r-project.org/web/packages/PeakSegDisk/vignettes/Examples.pdf", "len_cl100k_base": 8254, "olmocr-version": "0.1.50", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 35329, "total-output-tokens": 8000, "length": "2e13", "weborganizer": {"__label__adult": 0.0003714561462402344, "__label__art_design": 0.0004777908325195313, "__label__crime_law": 0.0007257461547851562, "__label__education_jobs": 0.001361846923828125, "__label__entertainment": 0.00014972686767578125, "__label__fashion_beauty": 0.0002655982971191406, "__label__finance_business": 0.0006613731384277344, "__label__food_dining": 0.0005483627319335938, "__label__games": 0.00074005126953125, "__label__hardware": 0.0013647079467773438, "__label__health": 0.0013103485107421875, "__label__history": 0.0004734992980957031, "__label__home_hobbies": 0.0002290010452270508, "__label__industrial": 0.0009813308715820312, "__label__literature": 0.00028228759765625, "__label__politics": 0.0005817413330078125, "__label__religion": 0.0005478858947753906, "__label__science_tech": 0.38525390625, "__label__social_life": 0.00023174285888671875, "__label__software": 0.06536865234375, "__label__software_dev": 0.537109375, "__label__sports_fitness": 0.0005049705505371094, "__label__transportation": 0.0004475116729736328, "__label__travel": 0.0003082752227783203}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 20115, 0.10483]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 20115, 0.09521]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 20115, 0.74444]], "google_gemma-3-12b-it_contains_pii": [[0, 2582, false], [2582, 3366, null], [3366, 4096, null], [4096, 6101, null], [6101, 6197, null], [6197, 8186, null], [8186, 8920, null], [8920, 9023, null], [9023, 10799, null], [10799, 11668, null], [11668, 12891, null], [12891, 14487, null], [14487, 15559, null], [15559, 17235, null], [17235, 17508, null], [17508, 20115, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2582, true], [2582, 3366, null], [3366, 4096, null], [4096, 6101, null], [6101, 6197, null], [6197, 8186, null], [8186, 8920, null], [8920, 9023, null], [9023, 10799, null], [10799, 11668, null], [11668, 12891, null], [12891, 14487, null], [14487, 15559, null], [15559, 17235, null], [17235, 17508, null], [17508, 20115, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 20115, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 20115, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 20115, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 20115, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 20115, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 20115, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 20115, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 20115, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 20115, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 20115, null]], "pdf_page_numbers": [[0, 2582, 1], [2582, 3366, 2], [3366, 4096, 3], [4096, 6101, 4], [6101, 6197, 5], [6197, 8186, 6], [8186, 8920, 7], [8920, 9023, 8], [9023, 10799, 9], [10799, 11668, 10], [11668, 12891, 11], [12891, 14487, 12], [14487, 15559, 13], [15559, 17235, 14], [17235, 17508, 15], [17508, 20115, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 20115, 0.26836]]}
olmocr_science_pdfs
2024-12-03
2024-12-03
52e124c11a1b53c398e6e4f985a33b62fc2c232d
[REMOVED]
{"len_cl100k_base": 12044, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 44877, "total-output-tokens": 13832, "length": "2e13", "weborganizer": {"__label__adult": 0.0004224777221679687, "__label__art_design": 0.000530242919921875, "__label__crime_law": 0.00054168701171875, "__label__education_jobs": 0.0017070770263671875, "__label__entertainment": 0.0001201629638671875, "__label__fashion_beauty": 0.00023627281188964844, "__label__finance_business": 0.0006151199340820312, "__label__food_dining": 0.0005068778991699219, "__label__games": 0.0011053085327148438, "__label__hardware": 0.002643585205078125, "__label__health": 0.0012807846069335938, "__label__history": 0.0005555152893066406, "__label__home_hobbies": 0.0002142190933227539, "__label__industrial": 0.0008463859558105469, "__label__literature": 0.00048279762268066406, "__label__politics": 0.00045418739318847656, "__label__religion": 0.000766754150390625, "__label__science_tech": 0.335205078125, "__label__social_life": 0.00011903047561645508, "__label__software": 0.00868988037109375, "__label__software_dev": 0.64111328125, "__label__sports_fitness": 0.0004162788391113281, "__label__transportation": 0.001056671142578125, "__label__travel": 0.00027108192443847656}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 51506, 0.02285]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 51506, 0.54013]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 51506, 0.92205]], "google_gemma-3-12b-it_contains_pii": [[0, 3352, false], [3352, 7119, null], [7119, 9480, null], [9480, 11837, null], [11837, 14777, null], [14777, 18046, null], [18046, 21517, null], [21517, 25192, null], [25192, 28641, null], [28641, 32105, null], [32105, 35612, null], [35612, 38990, null], [38990, 42350, null], [42350, 45732, null], [45732, 48980, null], [48980, 51506, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3352, true], [3352, 7119, null], [7119, 9480, null], [9480, 11837, null], [11837, 14777, null], [14777, 18046, null], [18046, 21517, null], [21517, 25192, null], [25192, 28641, null], [28641, 32105, null], [32105, 35612, null], [35612, 38990, null], [38990, 42350, null], [42350, 45732, null], [45732, 48980, null], [48980, 51506, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 51506, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 51506, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 51506, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 51506, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 51506, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 51506, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 51506, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 51506, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 51506, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 51506, null]], "pdf_page_numbers": [[0, 3352, 1], [3352, 7119, 2], [7119, 9480, 3], [9480, 11837, 4], [11837, 14777, 5], [14777, 18046, 6], [18046, 21517, 7], [21517, 25192, 8], [25192, 28641, 9], [28641, 32105, 10], [32105, 35612, 11], [35612, 38990, 12], [38990, 42350, 13], [42350, 45732, 14], [45732, 48980, 15], [48980, 51506, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 51506, 0.0]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
e4accca17485020097c63a3b334929af6b528e53
Lesson 1 Arithmetic with Python Worksheet K-W-L Chart <table> <thead> <tr> <th>What I Know</th> <th>What I Wonder</th> <th>What I Learned</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> </tbody> </table> New Commands ```python print("what's your name?") print(5 + 6) ``` Procedures Task 1: Translate the mathematical expressions below into Python code. Use Python to calculate the results. <table> <thead> <tr> <th>Example</th> <th>Symbol</th> <th>Name</th> <th>Python Representation</th> </tr> </thead> <tbody> <tr> <td>5 + 6 = 11</td> <td>+</td> <td>Addition</td> <td>+</td> </tr> <tr> <td>11 – 5 = 6</td> <td>-</td> <td>Subtraction</td> <td>-</td> </tr> <tr> <td>5 × 2 = 10</td> <td>×</td> <td>Multiplication</td> <td>*</td> </tr> <tr> <td>10 ÷ 5 = 2</td> <td>÷</td> <td>Division</td> <td>/</td> </tr> <tr> <td>5² = 25</td> <td>xⁿ</td> <td>Exponentiation</td> <td>**</td> </tr> <tr> <td>11 mod 5 = 1</td> <td></td> <td>Modulo</td> <td>%</td> </tr> </tbody> </table> Task 2: Calculate the results of the mathematical expressions below: 181 + 125 + 669 = ? 2160 - 439 - 57 = ? 79 × 21 × 3 × 108 = ? 40257 ÷ 1917 = ? 156⁴ = ? 40257 modulo 41 = ? Task 3: Suppose your current computing skill level is 100. If you spend 1 hour per day in practising Python, your skill level will increase by 1% per day. Create Python code to calculate the level of your computing skills if you keep doing this for 7 days. What will happen then after 180 days (and 365 days)? Lesson 2 Text and Numbers in Python Worksheet K-W-L Chart <table> <thead> <tr> <th>What I Know</th> <th>What I Wonder</th> <th>What I Learned</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> </tbody> </table> New Commands ```python print(type("What's your name?")) print(type(5 + 6)) print(type(40257 / 1917)) input("What's your name? Your answer: ") ``` Procedures Task 1: Calculate the expressions below and determine the type of data of the results: 100000 + 365.12 = ? 1989.12 - 917.8 = ? 36.6 × 50.1 = ? 100.25 × 40 = ? 3.310 = ? 2501 mod 2.5 = ? Task 2: Read the script below and identify a new function: 1. print(type(input("What's your name? Your answer: "))) 2. print(type(input("How old are you? Your answer: "))) 3. print(type(input("How tall are you? Your answer:(metre) "))) Task 3: Modify the script below and convert the data types of the input information: 1. print(type(input("Your school's postcode: "))) 2. print(type(input("Your school's name: "))) 3. print(type(input("Street/Block number nearby: "))) 4. print(type(input("Your body temperature:(°C) "))) 5. print(type(input("Today's temperature:(°C) "))) 6. print(type(input("Your lucky number: ")))} Lesson 3 Triangle Area Calculator Worksheet K-W-L Chart <table> <thead> <tr> <th>What I Know</th> <th>What I Wonder</th> <th>What I Learned</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> </tbody> </table> New Commands ```python my_var = 1 my_var = my_var + 1 ``` Procedures Step 1 Use Read and run the program. ```python 1. print("Triangle Area Calculator") 2. 3. a = float(input("Value of side a:(centimetre) ")) 4. b = float(input("Value of base b:(centimetre) ")) 5. c = float(input("Value of side c:(centimetre) ")) 6. 7. s = (a + b + c) / 2 8. 9. area = (s * (s-a) * (s-b) * (s-c)) ** 0.5 10. 11. print("The area of this triangle is", area, "square centimetres.") ``` Questions: - Why is `float()` used together with `input()`? - How can the program remember the values of three sides of a triangle? - How to calculate the semi-perimeter by using Python? - How to calculate the area by using Python? - Look at Line 11. Do you notice anything different? Step 2 Modify Task 1: Create another Triangle Area Calculator that calculates the area of a triangle with the given base and height. Task 2: Based on the program for Triangle Area Calculator, create a Triangular Prism Volume Calculator. Task 3: Create an application to calculate the capacity of a milk carton. Remember, you need to use the unit of measurement for liquids. Step 3 Create Create a calculator application that can calculate the perimeter and area of a plane shape or the volume of a solid shape, for instance a prism or prism-like figure. Lesson 4 Body Mass Index Calculator Worksheet K-W-L Chart <table> <thead> <tr> <th>What I Know</th> <th>What I Wonder</th> <th>What I Learned</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> </tbody> </table> New Commands ```python if BMI >= 30.0: # Code if BMI >= 18.5 and BMI <= 24.9: # Code ``` **Procedures** ### BMI Healthy Weight (Adults) <table> <thead> <tr> <th>BMI</th> <th>Level</th> <th>Meaning</th> </tr> </thead> <tbody> <tr> <td>Below 18.5</td> <td>Underweight</td> <td>Being underweight may lead to a weakened immune system and feeling tired.</td> </tr> <tr> <td>18.5 – 24.9</td> <td>Healthy Weight</td> <td>You have a healthy weight for your height.</td> </tr> <tr> <td>25.0 – 29.9</td> <td>Overweight</td> <td>You are heavier than is healthy for someone of your height. Try to lose weight by keeping a balanced diet and physical activity.</td> </tr> <tr> <td>30.0 and Above</td> <td>Obese</td> <td></td> </tr> </tbody> </table> *Source: UK NHS, US CDC* ### Calculate the BMI <table> <thead> <tr> <th>Name</th> <th>Height (m)</th> <th>Weight (kg)</th> <th>BMI</th> <th>Weight Status</th> </tr> </thead> <tbody> <tr> <td>(Your Name)</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Ai Fukuhara</td> <td>1.55</td> <td>48</td> <td></td> <td></td> </tr> <tr> <td>Angelina Jolie</td> <td>1.69</td> <td>54</td> <td></td> <td></td> </tr> <tr> <td>Arnold Schwarzenegger</td> <td>1.88</td> <td>113</td> <td></td> <td></td> </tr> <tr> <td>Benedict Cumberbatch</td> <td>1.83</td> <td>79</td> <td></td> <td></td> </tr> <tr> <td>Jackie Chan</td> <td>1.70</td> <td>65</td> <td></td> <td></td> </tr> <tr> <td>Kobe Bryant</td> <td>1.98</td> <td>96</td> <td></td> <td></td> </tr> <tr> <td>Malgorzata Dydek</td> <td>2.18</td> <td>101</td> <td></td> <td></td> </tr> <tr> <td>Maya Plisetskaya</td> <td>1.77</td> <td>59</td> <td></td> <td></td> </tr> <tr> <td>Sarah Hyland</td> <td>1.57</td> <td>45</td> <td></td> <td></td> </tr> <tr> <td>Serena Williams</td> <td>1.75</td> <td>70</td> <td></td> <td></td> </tr> <tr> <td>Tom Cruise</td> <td>1.70</td> <td>77</td> <td></td> <td></td> </tr> <tr> <td>Yao Ming</td> <td>2.29</td> <td>141</td> <td></td> <td></td> </tr> <tr> <td>Zoe</td> <td>1.70</td> <td>72</td> <td></td> <td></td> </tr> </tbody> </table> Step 1 Predict Read the program. ```python 1. print("BMI Calculator") 2. 3. height = float(input("Height:(metre) ")) 4. weight = float(input("Weight:(kilogram) ")) 5. 6. BMI = weight / (height**2) 7. print(BMI) 8. 9. if BMI >= 30.0: 10. print("Obese") 11. 12. if BMI >= 25.0 and BMI <= 29.9: 13. print("Overweight") 14. 15. if BMI >= 18.5 and BMI <= 24.9: 16. print("Healthy Weight") 17. 18. if BMI < 18.5: 19. print("Underweight") ``` Step 2 Run Run the program. Step 3 Investigate Task 1: Comment on the code. Briefly explain the function. Task 2: Investigate the conditions of the statements. Why does the program use the ‘≥’ and ‘≤’ operators to define the lowest and/or highest values of a range? Task 3: Investigate the indentation. Remove the leading whitespace before the ``` print("obese")/print("overweight")/print("healthy weight")/print("underweight"). Run the program and see what happens. Does the program still work? ``` Task 4: Calculate Zoe’s BMI and output her weight status. Could the program decide Zoe’s weight status? Why or why not? Step 4 Modify and Make Create a BMI Calculator for children and teenagers. References: The BMI Calculator created by the UK’s NHS: https://www.nhs.uk/live-well/healthy-weight/bmi-calculator The BMI Calculator created by the US’s CDC: For children and teenagers: https://www.cdc.gov/healthyweight/bmi/calculator.html For adults: Lesson 5 Buy Low, Sell High Worksheet K-W-L Chart <table> <thead> <tr> <th>What I Know</th> <th>What I Wonder</th> <th>What I Learned</th> </tr> </thead> </table> New Commands ```python import random def random.randint(start, end, step): # ...: elif <...>: else: ``` Procedures Step 1 Predict Read the program. ```python 1. import random 2. 3. price_a = random.randint(100, 200) 4. print("The traded price now is", price_a) 5. 6. order = int(input("Your posted price: ")) 7. 8. price_b = random.randint(100, 200) 9. print("The traded price now is", price_b) 10. 11. if order > price_b: 12. print("Current price is lower than your posted price. Buy it.") 13. 14. elif order < price_b: 15. print("Current price is higher than your posted price. Sell it.") 16. 17. else: 18. print("No transaction.") ``` Questions: - What is the control structure? - What does ‘import random’ mean? - What are the values of the variable ‘price_a’ and ‘price_b’? Step 2 Run Run the program. Step 3 Investigate Task 1: Comment on the code. Briefly explain the function. Task 2: Investigate the conditions of the statements. How does the program compare the posted price with the traded price? Task 3: What is the condition of ‘else’. Write down its condition. Step 4 Modify Task 4: Use the if statements instead to rewrite the example program. Step 5 Make Create a digital artefact with conditionals that helps with decision making. Lesson 6 Repay Loans Worksheet K-W-L Chart <table> <thead> <tr> <th>What I Know</th> <th>What I Wonder</th> <th>What I Learned</th> </tr> </thead> </table> New Commands ```python for i in range(start, end, step): round() ``` Procedures Step 1 Predict Read the program. <table> <thead> <tr> <th>Step</th> <th>Code</th> </tr> </thead> <tbody> <tr> <td>1.</td> <td>print(&quot;Loan Payment Calculator: Even Principal Payments&quot;)</td> </tr> <tr> <td>2.</td> <td></td> </tr> <tr> <td>3.</td> <td>loan = int(input(&quot;Loan Amount (GBP £): &quot;))</td> </tr> <tr> <td>4.</td> <td>term = int(input(&quot;Number of Payments (months): &quot;))</td> </tr> <tr> <td>5.</td> <td></td> </tr> <tr> <td>6.</td> <td>print(&quot;The annual interest rate is 5.4%&quot;)</td> </tr> <tr> <td>7.</td> <td>rate = 0.054</td> </tr> <tr> <td>8.</td> <td>balance = loan</td> </tr> <tr> <td>9.</td> <td></td> </tr> <tr> <td>10.</td> <td>for i in range(1, term + 1):</td> </tr> <tr> <td>11.</td> <td></td> </tr> <tr> <td>12.</td> <td>principal_payment = round(loan / term, 2)</td> </tr> <tr> <td>13.</td> <td>interest_payment = round(balance * (rate/12), 2)</td> </tr> <tr> <td>14.</td> <td>print(&quot;Repayment&quot;, i, &quot;:&quot;, principal_payment + interest_payment)</td> </tr> <tr> <td>15.</td> <td></td> </tr> <tr> <td>16.</td> <td>balance = loan - principal_payment*i</td> </tr> <tr> <td>17.</td> <td>print(&quot;Unpaid Balance: &quot;, balance)</td> </tr> </tbody> </table> Questions: - What is the control structure? - What does ‘range(1, term+1)’ mean? - How to calculate the unpaid balance of the loan after each repayment? Step 2 Run Run the program. Step 3 Investigate Task 1: Summarise the mathematical expressions. Task 2: Based on the result returned by the Loan Payment Calculator, create a graph to present the loan repayments. Step 4 Modify Task 3: Modify the program to pay the loan repayments annually. Task 4: The interest rate can be different across different repayment terms. Add the conditionals into the program you have created in the third task. <table> <thead> <tr> <th>Term (Years)</th> <th>Interest Rate</th> </tr> </thead> <tbody> <tr> <td>3</td> <td>5.4%</td> </tr> <tr> <td>5</td> <td>5.6%</td> </tr> <tr> <td>8</td> <td>6.1%</td> </tr> <tr> <td>10</td> <td>5.8%</td> </tr> </tbody> </table> Step 5 Make Create a Loan Repayment Calculator application for even total payments. Lesson 7 Toss a Coin Worksheet K-W-L Chart <table> <thead> <tr> <th>What I Know</th> <th>What I Wonder</th> <th>What I Learned</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> </tbody> </table> Procedures <table> <thead> <tr> <th>Total Flips</th> <th>Heads</th> <th>% Heads</th> <th>Tails</th> <th>% Tails</th> </tr> </thead> <tbody> <tr> <td>2</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>4</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>6</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>8</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>10</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>12</td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> Step 1 Predict Read the program. ```python 1. import random 2. 3. countheads = 0 4. counttails = 0 5. 6. n = int(input("The number of times to throw up a coin: ")) 7. 8. for i in range(0, n): 9. result = random.randint(0, 1) 10. 11. if result == 0: 12. countheads += 1 13. print(result) 14. else: 15. counttails += 1 16. print(result) 17. 18. print("Result:") 19. print("Heads up: ", countheads) 20. print("Tails up: ", counttails) 21. 22. print("Chance:") 23. print("Heads : Tails", round(countheads/n, 2), ":", round(counttails/n, 2)) ``` Questions: - How does the program represent the results of heads and tails? - How does the program count the number of heads or tails? - Explain the use of the if...else statement and the for loop. Step 2 Run Run the program. Step 3 Investigate Answer the questions. Step 4 Modify Task 1: Add a line of code to calculate the probabilities of getting heads and tails. Task 2: Change the number of the toss into a random number generated between 4040 and 80640. Task 3: Bet on the toss of the coin. Modify the example program to ask the user to input their guess before the coin-tossing experiment. Report the probability result and the betting result. Step 5 Make Based on the example program, modify the functions. Suppose the program is to model the dice-rolling process, how should you edit the code? Record the probability to get each number of the dice. Lesson 8 Guess the Number Worksheet K-W-L Chart <table> <thead> <tr> <th>What I Know</th> <th>What I Wonder</th> <th>What I Learned</th> </tr> </thead> </table> New Commands ```python while True: break ``` Procedures Step 1 Predict Read the program. ```python 1. import random 2. 3. num = random.randint(1, 100) 4. 5. t = 7 6. 7. print("Guess a number between 1 and 100. You have 7 attempts.") 8. print("Let's start.") 9. 10. while True: 11. guess = int(input("Guess the number: ")) 12. if guess == num: 13. print("BINGO!") 14. break 15. 16. elif guess > num: 17. t -= 1 18. print("High! You have", t, "attempts left.") 19. 20. elif guess < num: 21. t -= 1 22. print("Low! You have", t, "attempts left.") 23. 24. if t == 0: 25. print("The correct number is", num) 26. print("Game Over!") 27. break ``` Step 2 Run Run the program. ### Step 3 Investigate and Modify <table> <thead> <tr> <th>Round</th> <th>1st Try</th> <th>2nd Try</th> <th>3rd Try</th> <th>4th Try</th> <th>5th Try</th> <th>6th Try</th> <th>7th Try</th> <th>Number</th> </tr> </thead> <tbody> <tr> <td>Example</td> <td>7</td> <td>85</td> <td>60</td> <td>40</td> <td>20</td> <td>11</td> <td>9</td> <td>9</td> </tr> </tbody> </table> ### Note The 33 reserved words in Python: <table> <thead> <tr> <th>and</th> <th>as</th> <th>assert</th> <th>break</th> <th>class</th> <th>continue</th> </tr> </thead> <tbody> <tr> <td>def</td> <td>del</td> <td>elif</td> <td>else</td> <td>except</td> <td>finally</td> </tr> <tr> <td>for</td> <td>from</td> <td>False</td> <td>global</td> <td>if</td> <td>import</td> </tr> <tr> <td>in</td> <td>is</td> <td>lambda</td> <td>nonlocal</td> <td>not</td> <td>None</td> </tr> <tr> <td>or</td> <td>pass</td> <td>raise</td> <td>return</td> <td>try</td> <td>True</td> </tr> <tr> <td>while</td> <td>with</td> <td>yield</td> <td></td> <td></td> <td></td> </tr> </tbody> </table> Lesson 9~10 Python Quizzes Worksheet K-W-L Chart <table> <thead> <tr> <th>What I Know</th> <th>What I Wonder</th> <th>What I Learned</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> </tbody> </table> New Commands ```python import cyberpi cyberpi.display cyberpi.display.clear() cyberpi.console.print() cyberpi.console.println() cyberpi.led cyberpi.led.off() cyberpi.led.off(id="3") cyberpi.led.on() cyberpi.led.on("green", id="all") cyberpi.led.on("red", id=3) cyberpi.led.show("orange yellow cyan blue purple") cyberpi.led.play(name="firefly") cyberpi.controller.is_press() cyberpi.controller.is_press("a") cyberpi.controller.is_press("b") ``` 4) **Joystick:** ```python cyberpi.controller.is_press() cyberpi.controller.is_press("up") cyberpi.controller.is_press("down") cyberpi.controller.is_press("right") cyberpi.controller.is_press("left") cyberpi.controller.is_press("middle") ``` Procedures Features of CyberPi 1. Light sensor 2. WiFi + Bluetooth ESP32 3. Button A (Return key) 4. Button B (Confirmation key) 5. Gyroscope Accelerometer 6. Speaker Step 1 Predict Read the program. ```python 1. import cyberpi 2. cyberpi.display.clear() 3. cyberpi.led.off() 4. cyberpi.console.println("A - True") 5. cyberpi.console.println("B - False") 6. cyberpi.led.on(255, 255, 255) 7. cyberpi.console.println("Python is a compiled language.") 8. cyberpi.console.println("Your Answer:") 9. while True: 10. if cyberpi.controller.is_press("a"): 11. cyberpi.led.on(255, 0, 0) 12. cyberpi.console.println("Incorrect.") 13. cyberpi.console.println("Correct Answer: False") 14. break 15. if cyberpi.controller.is_press("b"): 16. cyberpi.led.on(0, 255, 0) 17. cyberpi.console.println("Correct!") 18. break ``` Questions: - Which module is imported? Explain why we should import this module. - How to print text on the screen? - How to light up/off the LED strip? - How to set the color of the LED? How to represent the LED colors in Python? - How to enter the answer? - How to evaluate the answer? Step 2 Run Run the program. Step 3 Investigate Investigate the physical components and API code samples of the screen, the LED strip, the buttons, and the joystick. Step 4 Modify and Make Task 1: Modify the quiz and the answer in the example program. Task 2: Modify the LED's lighting effects. Tip: Firefly: `cyberpi.led.play(name="firefly")` Rainbow: `cyberpi.led.play(name="rainbow")` Spoondrift: `cyberpi.led.play(name="spoondrift")` Meteor Shower: `cyberpi.led.play(name="meteor_blue"); cyberpi.led.play(name="meteor_green")` Flash: `cyberpi.led.play(name="flash_orange"); cyberpi.led.play(name="flash_red")` Task 3: Use the joystick instead of the buttons to enter the answer. Lesson 11 Data Protection and Passwords Worksheet K-W-L Chart <table> <thead> <tr> <th>What I Know</th> <th>What I Wonder</th> <th>What I Learned</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> </tbody> </table> Features of CyberPi Procedures Step 1 Predict Read the program. ```python 1. import cyberpi 2. 3. cyberpi.display.clear() 4. t = 0 5. 6. while True: 7. print("Create a password") 8. pin_1 = input("Type password: ") 9. pin_2 = input("Type password again: ") 10. if pin_2 == pin_1: 11. print("Success!") 12. break 13. else: 14. print("Passwords don't match. Try again.") 15. 16. print("Sign in your account") 17. cyberpi.console.println("Sign in") 18. 19. while t < 3: 20. pin = input("Password: ") 21. cyberpi.console.print("Password: ") 22. cyberpi.console.println(pin) 23. if pin == pin_1: 24. cyberpi.console.println("Success!") 25. break 26. else: 27. cyberpi.console.println("Incorrect. Try again.") 28. t += 1 29. if t == 3: 30. cyberpi.console.println("Too many failed attempts.") ``` Questions: - How to create a password for a new account? - How to verify the password entered by a user? - Compare the two `while` loops used in the example program. What is the difference between them? - Identify the syntax that enables the following function: ‘A user is given 3 attempts to enter the password of the account.’ If the user fails 3 times, the user is blocked from entering the password. Step 2 Run Run the program. Step 3 Investigate Answer the questions. Step 4 Modify Task 1: Add the function that allows the user to create a username when the user signs in. Task 2: Add some lighting effects as the indicator of a successful login. Use what you have learned to program the CyberPi. Tip: cyberpi.led.on(255, 255, 255) cyberpi.led.on(“green”, id = “all”) cyberpi.led.on(“red”, id = 3) cyberpi.led.show(“orange yellow cyan blue purple”) cyberpi.led.play(name = “firefly”) cyberpi.led.off(id = “3”) Task 3: Modify the second ‘while’ loop. Use the LEDs as an indicator to remind the number of attempts. Task 4: Modify the conditional expressions. Verify the following three conditions: The input username is incorrect; The input password is incorrect; Both the username and password are incorrect. Step 5 Make Develop a bank card reader - First, create a PIN for the bank account and store it on the computer. - When a sender starts a transaction, ask the sender to type the name (or other identification code) of the receiver and the amount of the transaction. - Then ask the sender to type the PIN. - Generate a random 4-digit verification code and display it on CyberPi’s screen. Ask the sender to enter the verification code. - Check the PIN and verification code. If both are correct, display the transaction information (including the receiver’s name or ID and the transaction amount) on the screen. However, if either the PIN or the verification code is incorrect, ask the sender to insert them again. The sender has limited attempts (for example, 3 attempts). - Ask the sender to check the transaction information and confirm the transaction by pressing Button B of the CyberPi. Lesson 12 Normal Distribution Worksheet K-W-L Chart <table> <thead> <tr> <th>What I Know</th> <th>What I Wonder</th> <th>What I Learned</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> </tbody> </table> New Commands cyberpi.display.set_brush() cyberpi.barchart.add() Features of CyberPi Procedures Step 1 Predict Read the program. 1. `import` `cyberpi`, `random` 2. 3. `cyberpi.display.clear()` 4. 5. `n = int(input("The number of times to roll 2 dice: "))` 6. `t = 0` 7. `sum_list = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]` 8. `count_list = [0, 0, 0, 0, 0, 0, 0, 0, 0]` 9. 10. `while` `t < n:` 11. `dice_x = random.randint(1, 6)` 12. `dice_y = random.randint(1, 6)` 13. `print("(", dice_x, ",", dice_y, ")")` 14. `result = dice_x + dice_y` 15. `t += 1` 16. `sum_index = sum_list.index(result)` 17. `count_list[sum_index] += 1` 18. 19. `cyberpi.display.set_brush(128, 0, 0)` 20. `cyberpi.barchart.add(round(count_list[0]/n * 200, 2))` 21. `cyberpi.display.set_brush(220, 20, 60)` 22. `cyberpi.barchart.add(round(count_list[1]/n * 200, 2))` 23. `cyberpi.display.set_brush(255, 0, 0)` 24. `cyberpi.barchart.add(round(count_list[2]/n * 200, 2))` 25. `cyberpi.display.set_brush(205, 92, 92)` 26. `cyberpi.barchart.add(round(count_list[3]/n * 200, 2))` 27. `cyberpi.display.set_brush(233, 150, 122)` 28. `cyberpi.barchart.add(round(count_list[4]/n * 200, 2))` 29. `cyberpi.display.set_brush(255, 69, 0)` 30. `cyberpi.barchart.add(round(count_list[5]/n * 200, 2))` 31. `cyberpi.display.set_brush(255, 165, 0)` 32. `cyberpi.barchart.add(round(count_list[6]/n * 200, 2))` 33. `cyberpi.display.set_brush(255, 215, 0)` 34. `cyberpi.barchart.add(round(count_list[7]/n * 200, 2))` 35. `cyberpi.display.set_brush(240, 230, 140)` 36. `cyberpi.barchart.add(round(count_list[8]/n * 200, 2))` 37. `cyberpi.display.set_brush(255, 255, 0)` 38. `cyberpi.barchart.add(round(count_list[9]/n * 200, 2))` 39. `cyberpi.display.set_brush(154, 205, 50)` 40. `cyberpi.barchart.add(round(count_list[10]/n * 200, 2))` Step 2 Run Run the program. Step 3 Investigate Investigate the points below: - The modules imported in this program; - The variables displayed in the bar chart; - Are ‘sum_list’ and ‘count_list’ variables? What are the values of them? - The function that sets the colour of the bar chart; - The function that creates the bars. Step 4 Modify and Make Task: Simulate the experiment of tossing three coins simultaneously. Calculate all the possible outcomes in this experiment and visualise the distribution with a bar chart. <table> <thead> <tr> <th>Head, Head, Head</th> <th>🐷 🐷 🐷</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> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> </tbody> </table> Lesson 13 Data Storage Worksheet K-W-L Chart <table> <thead> <tr> <th>What I Know</th> <th>What I Wonder</th> <th>What I Learned</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> </tbody> </table> New Commands ```python import psutil psutil.cpu_percent() psutil.cpu_count() psutil.cpu_freq() psutil.virtual_memory() cyberpi.linechart.add() cyberpi.chart.set_name() cyberpi.audio.play_tone() ``` Features of CyberPi Procedures Step 1 Predict Read the program. ```python 1. import cyberpi 2. import psutil 3. 4. cyberpi.chart.clear() 5. while True: 6. CPU = psutil.cpu_percent() 7. mem = psutil.virtual_memory() 8. mem_p = mem.percent 9. cyberpi.display.set_brush(0, 0, 255) 10. cyberpi.linechart.add(int(CPU)) 11. cyberpi.display.set_brush(255, 255, 0) 12. cyberpi.linechart.add(int(mem_p)) 13. print("CPU:", CPU, "% Memory:", mem_p, ") ``` Step 2 Run Run the program. Step 3 Investigate Investigate the points below: - The library for calling functions to monitor the CPU and memory usage - The two variables plotted in the line chart; - The function that plots the lines; - The function that set the color of the line. Step 4 Modify and Make Task: Add control structures and light effects to the example program. Define the thresholds of the alarm and the corresponding alarm indicators. Note: CPU performance <table> <thead> <tr> <th>Lower CPU performance</th> <th>Higher CPU performance</th> </tr> </thead> <tbody> <tr> <td>Single-core</td> <td>Multi-core</td> </tr> <tr> <td>Low clock speed</td> <td>High clock speed</td> </tr> <tr> <td>Small or no cache</td> <td>Large, multi-level cache</td> </tr> </tbody> </table> Lesson 14 Remix Culture Worksheet K-W-L Chart <table> <thead> <tr> <th>What I Know</th> <th>What I Wonder</th> <th>What I Learned</th> </tr> </thead> </table> New Commands ```python from pynput.keyboard import Key, Listener from pynput.keyboard import Button, Controller cyberpi.is_tiltleft cyberpi.is_tiltright cyberpi.is_tiltforward cyberpi.is_tiltback cyberpi.audio.play_music() ``` Features of CyberPi - Light sensor - Microphone - Electronic module interface - Button A (Return key) - HOME button (Enter CyberOS) - Power & data interface (Type-C) - WiFi + Bluetooth ESP32 - Full-color display - Button B (Confirmation key) - Gyroscope - Accelerometer - RGB LED (Five) - Speaker Procedures Step 1 Predict Read the program. 1. import cyberpi 2. from pynput.keyboard import Key, Listener 3. cyberpi.audio.set_vol(50) 4. def bar1(): 5. cyberpi.audio.play_music(60, 0.2) 6. cyberpi.audio.play_music(64, 0.2) 7. cyberpi.audio.play_music(67, 0.2) 8. def bar2(): 9. cyberpi.audio.play_music(64, 0.2) 10. cyberpi.audio.play_music(65, 0.2) 11. cyberpi.audio.play_music(69, 0.2) 12. def bar3(): 13. cyberpi.audio.play_music(64, 0.2) 14. cyberpi.audio.play_music(67, 0.2) 15. cyberpi.audio.play_music(71, 0.2) 16. def bar4(): 17. cyberpi.audio.play_music(65, 0.2) 18. cyberpi.audio.play_music(69, 0.2) 19. cyberpi.audio.play_music(72, 0.2) 20. def on_press(key): 21. if key.char == "1": 22. cyberpi.led.on("red") 23. bar1() 24. if key.char == "2": 25. cyberpi.led.on("orange") 26. bar2() 27. if key.char == "3": 28. cyberpi.led.on("yellow") 29. bar3() 30. if key.char == "4": 31. cyberpi.led.on("green") 32. bar4() 33. def on_release(key): 34. cyberpi.led.off() 35. pass 36. with Listener(on_press=on_press, on_release=on_release) as listener: 37. listener.join() Step 2 Run Run the program. Step 3 Investigate Investigate the points below: - Identify the new module that can monitor the input from your keyboard. - What is meant by the Python keyword ‘def’? - Why does it separate the set of expressions within each ‘def’ code block? - How to produce interactive sound and light effects? Step 4 Modify and Make Task 1: Modify the parameters in the example program. Use letters to replace the numeric parameters. Task 2: Modify the ‘bar’ functions. Find some pieces of songs from music textbooks and combine different parts of them together to make a new song. Consider how to combine the sound effects and LED lights.
{"Source-Url": "https://d4iqe7beda780.cloudfront.net/resources/static/main/pdf/cyberpi_python_basic_coding_material_worksheets.pdf", "len_cl100k_base": 9419, "olmocr-version": "0.1.50", "pdf-total-pages": 48, "total-fallback-pages": 0, "total-input-tokens": 76850, "total-output-tokens": 10707, "length": "2e13", "weborganizer": {"__label__adult": 0.0006437301635742188, "__label__art_design": 0.002685546875, "__label__crime_law": 0.0006756782531738281, "__label__education_jobs": 0.28662109375, "__label__entertainment": 0.0005135536193847656, "__label__fashion_beauty": 0.0004291534423828125, "__label__finance_business": 0.0013561248779296875, "__label__food_dining": 0.0013866424560546875, "__label__games": 0.0019683837890625, "__label__hardware": 0.003887176513671875, "__label__health": 0.001506805419921875, "__label__history": 0.0011501312255859375, "__label__home_hobbies": 0.0009021759033203124, "__label__industrial": 0.0021762847900390625, "__label__literature": 0.001583099365234375, "__label__politics": 0.0008311271667480469, "__label__religion": 0.0011501312255859375, "__label__science_tech": 0.280029296875, "__label__social_life": 0.0007810592651367188, "__label__software": 0.031341552734375, "__label__software_dev": 0.376708984375, "__label__sports_fitness": 0.0005803108215332031, "__label__transportation": 0.0007872581481933594, "__label__travel": 0.0003933906555175781}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 28040, 0.07532]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 28040, 0.61009]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 28040, 0.64165]], "google_gemma-3-12b-it_contains_pii": [[0, 275, false], [275, 1376, null], [1376, 1734, null], [1734, 2558, null], [2558, 2825, null], [2825, 3526, null], [3526, 4087, null], [4087, 4396, null], [4396, 6332, null], [6332, 6810, null], [6810, 7852, null], [7852, 8120, null], [8120, 8846, null], [8846, 9300, null], [9300, 9520, null], [9520, 10483, null], [10483, 11191, null], [11191, 11814, null], [11814, 12627, null], [12627, 13270, null], [13270, 13473, null], [13473, 14196, null], [14196, 14829, null], [14829, 15127, null], [15127, 15577, null], [15577, 15820, null], [15820, 15992, null], [15992, 16990, null], [16990, 17688, null], [17688, 17922, null], [17922, 18759, null], [18759, 19239, null], [19239, 20025, null], [20025, 20917, null], [20917, 21235, null], [21235, 21255, null], [21255, 21303, null], [21303, 22961, null], [22961, 23801, null], [23801, 24199, null], [24199, 24219, null], [24219, 24966, null], [24966, 25417, null], [25417, 25794, null], [25794, 26092, null], [26092, 26141, null], [26141, 27376, null], [27376, 28040, null]], "google_gemma-3-12b-it_is_public_document": [[0, 275, true], [275, 1376, null], [1376, 1734, null], [1734, 2558, null], [2558, 2825, null], [2825, 3526, null], [3526, 4087, null], [4087, 4396, null], [4396, 6332, null], [6332, 6810, null], [6810, 7852, null], [7852, 8120, null], [8120, 8846, null], [8846, 9300, null], [9300, 9520, null], [9520, 10483, null], [10483, 11191, null], [11191, 11814, null], [11814, 12627, null], [12627, 13270, null], [13270, 13473, null], [13473, 14196, null], [14196, 14829, null], [14829, 15127, null], [15127, 15577, null], [15577, 15820, null], [15820, 15992, null], [15992, 16990, null], [16990, 17688, null], [17688, 17922, null], [17922, 18759, null], [18759, 19239, null], [19239, 20025, null], [20025, 20917, null], [20917, 21235, null], [21235, 21255, null], [21255, 21303, null], [21303, 22961, null], [22961, 23801, null], [23801, 24199, null], [24199, 24219, null], [24219, 24966, null], [24966, 25417, null], [25417, 25794, null], [25794, 26092, null], [26092, 26141, null], [26141, 27376, null], [27376, 28040, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 28040, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 28040, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 28040, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 28040, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 28040, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 28040, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 28040, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 28040, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 28040, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 28040, null]], "pdf_page_numbers": [[0, 275, 1], [275, 1376, 2], [1376, 1734, 3], [1734, 2558, 4], [2558, 2825, 5], [2825, 3526, 6], [3526, 4087, 7], [4087, 4396, 8], [4396, 6332, 9], [6332, 6810, 10], [6810, 7852, 11], [7852, 8120, 12], [8120, 8846, 13], [8846, 9300, 14], [9300, 9520, 15], [9520, 10483, 16], [10483, 11191, 17], [11191, 11814, 18], [11814, 12627, 19], [12627, 13270, 20], [13270, 13473, 21], [13473, 14196, 22], [14196, 14829, 23], [14829, 15127, 24], [15127, 15577, 25], [15577, 15820, 26], [15820, 15992, 27], [15992, 16990, 28], [16990, 17688, 29], [17688, 17922, 30], [17922, 18759, 31], [18759, 19239, 32], [19239, 20025, 33], [20025, 20917, 34], [20917, 21235, 35], [21235, 21255, 36], [21255, 21303, 37], [21303, 22961, 38], [22961, 23801, 39], [23801, 24199, 40], [24199, 24219, 41], [24219, 24966, 42], [24966, 25417, 43], [25417, 25794, 44], [25794, 26092, 45], [26092, 26141, 46], [26141, 27376, 47], [27376, 28040, 48]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 28040, 0.16449]]}
olmocr_science_pdfs
2024-11-30
2024-11-30
b51d05b64d314196f8f59c5b3a956fed7aecdd7a
Contents Preface v 1 Introduction 1 2 Finite Automata 3 2.1 Turing Machines ................................................. 3 2.2 Introduction to Finite Automata ................................. 3 2.3 More Examples ..................................................... 9 2.4 Formal Definition .................................................. 13 2.5 Closure Properties ................................................. 19 3 Nondeterministic Finite Automata 27 3.1 Introduction ....................................................... 27 3.2 Formal Definition .................................................. 29 3.3 Equivalence with DFA’s ............................................ 32 3.4 Closure Properties .................................................. 36 4 Regular Expressions 41 4.1 Introduction ....................................................... 41 4.2 Formal Definition .................................................. 41 CONTENTS 4.3 More Examples ................................................. 42 4.4 Converting Regular Expressions into DFA’s .................. 44 4.5 Converting DFA’s into Regular Expressions ................. 47 4.6 Precise Description of the Algorithm ......................... 49 5 Nonregular Languages ........................................... 51 5.1 Some Examples .................................................. 51 Preface This document contains solutions to the exercises of the course notes Automata and Computability. These notes were written for the course CS345 Automata Theory and Formal Languages taught at Clarkson University. The course is also listed as MA345 and CS541. The solutions are organized according to the same chapters and sections as the notes. Here’s some advice. Whether you are studying these notes as a student in a course or in self-directed study, your goal should be to understand the material well enough that you can do the exercises on your own. Simply studying the solutions is not the best way to achieve this. It is much better to spend a reasonable amount of time and effort trying to do the exercises yourself before looking at the solutions. If you can’t do an exercise on your own, you should study the notes some more. If that doesn’t work, seek help from another student or from your instructor. Look at the solutions only to check your answer once you think you know how to do an exercise. If you needed help doing an exercise, try redoing the same exercise later on your own. And do additional exercises. If your solution to an exercise is different from the solution in this document, take the time to figure out why. Did you make a mistake? Did you forget some- thing? Did you discover another correct solution? If you’re not sure, ask for help from another student or the instructor. If your solution turns out to be incorrect, fix it, after maybe getting some help, then try redoing the same exercise later on your own and do additional exercises. Feedback on the notes and solutions is welcome. Please send comments to alexis@clarkson.edu. Chapter 1 Introduction There are no exercises in this chapter. Chapter 2 Finite Automata 2.1 Turing Machines There are no exercises in this section. 2.2 Introduction to Finite Automata 2.2.3. Missing edges go to a garbage state. In other words, the full DFA looks like this: The transition label *other* means any character that’s not a dash or a digit. Missing edges go to a garbage state. 2.2.5. 2.2.6. 2.2.7. ```cpp starting_state() { return q0 } is_accepting(q) { return true iff q is q1 } next_state(q, c) { if (q is q0) if (c is underscore or letter) return q1 else return q2 else if (q is q1) if (c is underscore, letter or digit) return q1 else return q2 else // q is q2 return q2 } ``` 2.2.8. The following assumes that the garbage state is labeled $q_9$. In the pseudocode algorithm, states are stored as integers. This is more convenient here. ```cpp starting_state() { return 0 } is_accepting(q) { return true iff q is 8 } ``` next_state(q, c) { if (q in {0, 1, 2} or {4, 5, 6, 7}) if (c is digit) return q + 1 else return 9 else if (q is 3) if (c is digit) return 5 else if (c is dash) return 4 else return 9 else if (q is 8 or 9) return 9 } 2.3. More Examples 2.3.5. 2.3.6. In all cases, missing edges go to a garbage state. a) b) 2.3.7. In all cases, missing edges go to a garbage state. a) b) c) 2.3. **MORE EXAMPLES** d) \[ \begin{array}{c} q_0 \quad 1 \quad q_1 \quad 1 \quad q_2 \end{array} \] \[ \begin{array}{c} 0 \quad 0 \quad 0,1 \end{array} \] \[ \begin{array}{c} 0,1 \end{array} \] 2.3.8. In all cases, missing edges go to a garbage state. a) \[ \begin{array}{c} q_0 \quad 1 \quad q_1 \quad 1 \quad q_2 \end{array} \] \[ \begin{array}{c} 0 \quad 0 \quad 0,1 \end{array} \] \[ \begin{array}{c} 1 \quad 1 \end{array} \] \[ \begin{array}{c} 0,1 \end{array} \] b) The idea is for the DFA to remember the last two symbols it has seen. c) Again, the idea is for the DFA to remember the last two symbols it has seen. We could simply change the accepting states of the previous DFA to \{q_{10}, q_{11}\}. But we can also simplify this DFA by assuming that strings of length less than two are preceded by 00. 2.4 Formal Definition 2.4.5. a) The DFA is $(\{q_0, q_1, q_2, \ldots, q_9\}, \Sigma, \delta, q_0, \{q_9\})$ where $\Sigma$ is the set of all characters that appear on a standard keyboard and $\delta$ is defined as follows: \[ \delta(q_i, c) = \begin{cases} q_{i+1} & \text{if } i \notin \{3, 8, 9\} \text{ and } c \text{ is digit} \\ q_9 & \text{if } i \notin \{3, 8, 9\} \text{ and } c \text{ is not digit} \end{cases} \] \[ \delta(q_3, c) = \begin{cases} q_4 & \text{if } c \text{ is dash} \\ q_5 & \text{if } c \text{ is digit} \\ q_9 & \text{otherwise} \end{cases} \] \[ \delta(q_8, c) = q_9 \quad \text{for every } c \] \[ \delta(q_9, c) = q_9 \quad \text{for every } c \] b) The DFA is \((\{q_0, q_1, q_2, q_3\}, \Sigma, \delta, q_0, \{q_2\})\) where \(\Sigma\) is the set of all characters that appear on a standard keyboard and \(\delta\) is defined as follows: \[ \delta(q_0, c) = \begin{cases} q_1 & \text{if } c \text{ is dash} \\ q_2 & \text{if } c \text{ is digit} \\ q_3 & \text{otherwise} \end{cases} \] \[ \delta(q_i, c) = \begin{cases} q_2 & \text{if } i \in \{1, 2\} \text{ and } c \text{ is digit} \\ q_3 & \text{if } i \in \{1, 2\} \text{ and } c \text{ is not digit} \end{cases} \] \[ \delta(q_3, c) = q_3 \quad \text{for every } c \] c) The DFA is \((\{q_0, q_1, q_2, \ldots, q_5\}, \Sigma, \delta, q_0, \{q_2, q_4\})\) where \(\Sigma\) is the set of all characters that appear on a standard keyboard and \(\delta\) is defined as follows: \[ \delta(q_0, c) = \begin{cases} q_1 & \text{if } c \text{ is dash} \\ q_2 & \text{if } c \text{ is digit} \\ q_3 & \text{if } c \text{ is decimal point} \\ q_5 & \text{otherwise} \end{cases} \] \[ \delta(q_i, c) = \begin{cases} q_2 & \text{if } i \in \{1, 2\} \text{ and } c \text{ is digit} \\ q_3 & \text{if } i \in \{1, 2\} \text{ and } c \text{ is decimal point} \\ q_5 & \text{if } i \in \{1, 2\} \text{ and } c \text{ is not digit or decimal point} \end{cases} \] \[ \delta(q_i, c) = \begin{cases} q_4 & \text{if } i \in \{3, 4\} \text{ and } c \text{ is digit} \\ q_5 & \text{if } i \in \{3, 4\} \text{ and } c \text{ is not digit} \end{cases} \] \[ \delta(q_5, c) = q_5 \quad \text{for every } c \] 2.4.6. The idea is for the DFA to remember the last $k$ symbols it has seen. But this is too difficult to draw clearly, so here’s a formal description of the DFA: $(Q, \{0, 1\}, \delta, q_0, F)$ where $$Q = \{q_w | w \in \{0, 1\}^* \text{ and } w \text{ has length } k\}$$ $$q_0 = q_{w_0} \text{ where } w_0 = 0^k \text{ (that is, a string of } k \text{ } 0\text{'s)}$$ $$F = \{q_w \in Q \mid w \text{ starts with a } 1\}$$ and $\delta$ is defined as follows: $$\delta(q_{au}, b) = q_{ub}$$ where $a \in \Sigma$, $u$ is a string of length $k - 1$ and $b \in \Sigma$. 2.4.7. a) The idea is for the DFA to store the value, modulo 3, of the portion of the number it has seen so far, and then update that value for every additional digit that is read. To update the value, the current value is multiplied by 10, the new digit is added and the result is reduced modulo 3. (Note that this is exactly the same DFA we designed in an example of this section for the language of strings that have the property that the sum of their digits is a multiple of 3. This is because $10 \mod 3 = 1$ so that when we multiply the current value by 10 and reduce modulo 3, we are really just multiplying by 1. Which implies that the strategy we described above is equivalent to simply adding the digits of the number, modulo 3.) b) We use the same strategy that was described in the first part, but this time, we reduce modulo $k$. Here’s a formal description of the DFA: $(Q, \Sigma, \delta, q_0, F)$ where $$Q = \{q_0, q_1, q_2, \ldots, q_{k-1}\}$$ $$\Sigma = \{0, 1, 2, \ldots, 9\}$$ $$F = \{q_0\}$$ and $\delta$ is defined as follows: for every $i \in Q$ and $c \in \Sigma$, $$\delta(q_i, c) = q_j \quad \text{where} \quad j = (i \cdot 10 + c) \mod k.$$ 2.4. FORMAL DEFINITION 2.4.8. a) The idea is for the DFA to verify, for each input symbol, that the third digit is the sum of the first two plus any carry that was previously generated, as well as determine if a carry is generated. All that the DFA needs to remember is the value of the carry (0 or 1). The DFA accepts if no carry is generated when processing the last input symbol. Here's a formal description of the DFA, where state \( q_2 \) is a garbage state: \((Q, \Sigma, \delta, q_0, F)\) where \[ Q = \{q_0, q_1, q_2\} \] \[ \Sigma = \{ [abc] \mid a, b, c \in \{0, 1, 2, \ldots, 9\} \} \] \[ F = \{q_0\} \] and \( \delta \) is defined as follows: \[ \delta(q_d, [abc]) = \begin{cases} q_0 & \text{if } d \in \{0, 1\} \text{ and } d + a + b = c \\ q_1 & \text{if } d \in \{0, 1\}, \ d + a + b \geq 10 \text{ and } (d + a + b) \mod 10 = c \\ q_2 & \text{otherwise} \end{cases} \] Here's a transition diagram of the DFA that shows only one of the 1,000 transitions that come out of each state. b) Since the DFA is now reading the numbers from left to right, it can’t compute the carries as it reads the numbers. So it will do the opposite: for each input symbol, the DFA will figure out what carry it needs from the rest of the numbers. For example, if the first symbol that the DFA sees is \([123]\), the DFA will know that there should be no carry generated from the rest of the numbers. But if the symbol is \([124]\), the DFA needs the rest of the number to generate a carry. And if a carry needs to be generated, the next symbol will have to be something like \([561]\) but not \([358]\). The states of the DFA will be used to remember the carry that is needed from the rest of the numbers. The DFA will accept if no carry is needed for the first position of the numbers (which is given by the last symbol of the input string). Here’s a formal description of the DFA, where state \(q_2\) is a garbage state: \[(Q, \Sigma, \delta, q_0, F)\] where \[Q = \{q_0, q_1, q_2\}\] \[\Sigma = \{[abc] | a, b, c \in \{0, 1, 2, \ldots, 9\}\}\] \[F = \{q_0\}\] and \(\delta\) is defined as follows: \[\delta(q_0, [abc]) = \begin{cases} q_d & \text{if } d \in \{0, 1\} \text{ and } d + a + b = c \\ q_2 & \text{otherwise} \end{cases}\] \[\delta(q_1, [abc]) = \begin{cases} q_d & \text{if } d \in \{0, 1\}, d + a + b \geq 10 \text{ and} \\ (d + a + b) \mod 10 = c \\ q_2 & \text{otherwise} \end{cases}\] \[\delta(q_2, [abc]) = q_2, \text{ for every } [abc] \in \Sigma\] 2.5. Closure Properties 2.5.3. In each case, all we have to do is switch the acceptance status of each state. But we need to remember to do it for the garbage states too. a) 2.5.4. It is important to include in the pair construction the garbage states of the DFA's for the simpler languages. (This is actually not needed for intersections but it is critical for unions.) In each case, we give the DFA's for the two simpler languages followed by the DFA obtained by the pair construction. 2.5. CLOSURE PROPERTIES a) \[ q_0 \xrightarrow{0,1} q_1 \xrightarrow{1} q_2 \xrightarrow{0,1} q_3 \] \[ q_0 \xrightarrow{1} q_1 \xrightarrow{0} q_1 \] \[ q_0 \xrightarrow{0,1} q_{00} \xrightarrow{1} q_{10} \xrightarrow{1} q_{20} \xrightarrow{1} \] \[ q_0 \xrightarrow{0,1} q_{01} \xrightarrow{0,1} q_{11} \xrightarrow{1} q_{21} \xrightarrow{0,1} q_{31} \xrightarrow{0,1} q_{30} \] b) \[ q_0 \xrightarrow{0} q_0 \quad q_0 \xrightarrow{1} q_1 \quad q_1 \xrightarrow{1} q_2 \quad q_2 \xrightarrow{0,1} q_2 \] \[ q_0 \xleftarrow{1} q_0 \quad q_1 \xleftarrow{1} q_1 \quad q_2 \xleftarrow{0,1} q_2 \] c) \[ \begin{align*} q_0 & \rightarrow q_1 \rightarrow q_2 \\ 0 & \rightarrow 0 \rightarrow 0,1 \end{align*} \] d) 2.5.5. In both cases, missing edges go to a garbage state. a) b) The dashed state and edge could be deleted. Chapter 3 Nondeterministic Finite Automata 3.1 Introduction 3.1.3. a) 3.2. Formal Definition 3.2.1. The NFA is $(Q, \{0, 1\}, \delta, q_0, F)$ where $$Q = \{q_0, q_1, q_2, q_3\}$$ $$F = \{q_3\}$$ and $\delta$ is defined by the following table <table> <thead> <tr> <th>$\delta$</th> <th>0</th> <th>1</th> <th>$\varepsilon$</th> </tr> </thead> <tbody> <tr> <td>$q_0$</td> <td>$q_0$</td> <td>$q_0, q_1$</td> <td>$-$</td> </tr> <tr> <td>$q_1$</td> <td>$q_2$</td> <td>$q_2$</td> <td>$-$</td> </tr> <tr> <td>$q_2$</td> <td>$q_3$</td> <td>$q_3$</td> <td>$-$</td> </tr> <tr> <td>$q_3$</td> <td>$-$</td> <td>$-$</td> <td>$-$</td> </tr> </tbody> </table> b) The NFA is \((Q, \{0, 1\}, \delta, q_0, F)\) where \[ Q = \{q_0, q_1, q_2, q_3\} \] \[ F = \{q_3\} \] and \(\delta\) is defined by the following table: <table> <thead> <tr> <th>(\delta)</th> <th>0</th> <th>1</th> <th>(\varepsilon)</th> </tr> </thead> <tbody> <tr> <td>(q_0)</td> <td>(q_1)</td> <td>(q_0)</td> <td>-</td> </tr> <tr> <td>(q_1)</td> <td>(q_2)</td> <td>-</td> <td>(q_0)</td> </tr> <tr> <td>(q_2)</td> <td>-</td> <td>(q_3)</td> <td>(q_1)</td> </tr> <tr> <td>(q_3)</td> <td>(q_3)</td> <td>(q_3)</td> <td>-</td> </tr> </tbody> </table> 3.2.2. The NFA accepts because the last two sequences end in the accepting state. The NFA accepts because the last three sequences end in the accepting state. 3.3 Equivalence with DFA’s 3.3.2. 3.3. EQUIVALENCE WITH DFA'S 3.3.3. a) \[ \begin{array}{c|cc} \delta' & 0 & 1 \\ \hline q_0 & q_1 & - \\ q_1 & q_1 & q_1, q_2 \\ q_2 & - & - \\ q_1, q_2 & q_1 & q_1, q_2 \\ \end{array} \] The start state is \( \{0\} \). The accepting state is \( \{q_1, q_2\} \). (As usual, the symbol \(-\) represents the state \( \emptyset \). That state is a garbage state.) b) \[ \begin{array}{c|ccc} \delta' & 0 & 1 & 1 \\ \hline q_0 & q_0, q_1 & q_0, q_2 & q_0, q_2 \\ q_1 & - & q_3 & - \\ q_2 & - & - & q_3 \\ q_3 & - & - & - \\ q_0, q_1 & q_0, q_1, q_3 & q_0, q_2, q_3 & q_0, q_2 \\ q_0, q_2 & q_0, q_1 & q_0, q_2, q_3 & q_0, q_2, q_3 \\ q_0, q_1, q_3 & q_0, q_1, q_3 & q_0, q_2 & q_0, q_2 \\ q_0, q_2, q_3 & q_0, q_1 & q_0, q_2, q_3 & q_0, q_2, q_3 \\ \end{array} \] The start state is \( \{q_0\} \). The accepting states are \( \{q_0, q_1, q_3\} \) and c)\[\begin{array}{c|cc} \delta' & 0 & 1 \\ \hline q_0 & q_0 & q_0, q_1 \\ q_1 & q_2 & q_2 \\ q_2 & - & - \\ q_0, q_1 & q_0, q_2 & q_0, q_1, q_2 \\ q_0, q_2 & q_0 & q_0, q_1 \\ q_0, q_1, q_2 & q_0, q_2 & q_0, q_1, q_2 \\ \end{array}\] The start state is \(\{q_0\}\). The accepting states are \(\{q_0, q_2\}\) and \(\{q_0, q_1, q_2\}\). d)\[\begin{array}{c|cc} \delta' & 0 & 1 \\ \hline q_0 & q_0 & q_1 \\ q_1 & q_1 & - \\ \end{array}\] The start state is \(\{q_0\}\). The accepting state is \(\{q_1\}\). (The given NFA was almost a DFA. All that was missing was a garbage state and that’s precisely what the algorithm added.) 3.3. EQUIVALENCE WITH DFA'S 3.3.4. a) <table> <thead> <tr> <th>$\delta'$</th> <th>0</th> <th>1</th> </tr> </thead> <tbody> <tr> <td>$q_0$</td> <td>$q_1$</td> <td>$-$</td> </tr> <tr> <td>$q_1$</td> <td>$q_1$</td> <td>$q_1,q_2$</td> </tr> <tr> <td>$q_2$</td> <td>$-$</td> <td>$-$</td> </tr> <tr> <td>$q_1,q_2$</td> <td>$q_1$</td> <td>$q_1,q_2$</td> </tr> </tbody> </table> The start state is $E(\{q_0\}) = \{q_0\}$. The accepting state is $\{q_1,q_2\}$. b) <table> <thead> <tr> <th>$\delta'$</th> <th>0</th> <th>1</th> </tr> </thead> <tbody> <tr> <td>$q_0$</td> <td>$q_0,q_1,q_2$</td> <td>$q_0,q_1,q_2$</td> </tr> <tr> <td>$q_1$</td> <td>$q_3$</td> <td>$-$</td> </tr> <tr> <td>$q_2$</td> <td>$-$</td> <td>$q_3$</td> </tr> <tr> <td>$q_3$</td> <td>$-$</td> <td>$-$</td> </tr> </tbody> </table> | $q_0,q_1,q_2$ | $q_0,q_1,q_2,q_3$ | $q_0,q_1,q_2,q_3$ | | $q_0,q_1,q_2,q_3$ | $q_0,q_1,q_2,q_3$ | $q_0,q_1,q_2,q_3$ | The start state is $E(\{q_0\}) = \{q_0,q_1,q_2\}$. The accepting state is $\{q_0,q_1,q_2,q_3\}$. 3.4 Closure Properties 3.4.2. Suppose that $M_i = (Q_i, \Sigma, \delta_i, q_i, F_i)$, for $i = 1, 2$. Without loss of generality, assume that $Q_1$ and $Q_2$ are disjoint. Then $N = (Q, \Sigma, \delta, q_0, F)$ where $$Q = Q_1 \cup Q_2$$ $$q_0 = q_1$$ $$F = F_2$$ and $\delta$ is defined as follows: $$\delta(q, \epsilon) = \begin{cases} \{q_2\} & \text{if } q \in F_1 \\ \emptyset & \text{otherwise} \end{cases}$$ $$\delta(q, a) = \{\delta_i(q, a)\}, \text{ if } q \in Q_i \text{ and } a \in \Sigma.$$ 3.4.4. a) In the second to last paragraph of the proof, it is claimed that \( w = x_1 \cdots x_{k+1} \), with each \( x_i \in A \). It is true that \( x_1, \ldots, x_k \) are all in \( A \) because they must lead from the start state to one of the original accepting states of \( M \). But this is not true for \( x_{k+1} \): that string could lead back to the start state instead of leading to one of the original accepting states of \( M \). In that case, \( x_{k+1} \) wouldn’t be in \( A \) and we wouldn’t be able to conclude that \( w \) is in \( A^* \). b) Consider the following DFA for the language of strings that contain at least one 1: ![DFA Diagram] If we used this idea, we would get the following NFA: ![NFA Diagram] This NFA accepts strings that contain only 0’s. These strings are not in the language \( L(M)^* \). Therefore, \( L(N) \neq L(M)^* \). 3.4.5. One proof is to notice that \( A^+ = AA^* \). Since the class of regular languages is closed under star and concatenation, we also get closure under the plus operation. An alternative proof is to modify the construction that was used for the star operation. The only change is that a new start state should not be added. The argument that this construction works is almost the same as before. If \( w \in A^+ \), then \( w = x_1 \cdots x_k \) with \( k \geq 1 \) and each \( x_i \in A \). This implies that \( N \) can accept \( w \) by going through \( M \) \( k \) times, each time reading one \( x_i \) and then returning to the start state of \( M \) by using one of the new \( \epsilon \) transitions (except after \( x_k \)). Conversely, if \( w \) is accepted by \( N \), then it must be that \( N \) uses the new \( \epsilon \) “looping back” transitions \( k \) times, for some number \( k \geq 0 \), breaking \( w \) up into \( x_1 \cdots x_{k+1} \), with each \( x_i \in A \). This implies that \( w \in A^+ \). Therefore, \( L(N) = A^+ \). 3.4.6. Suppose that \( L \) is regular and that it is recognized by a DFA \( M \) that doesn’t have exactly one accepting state. If \( M \) has no accepting states, then simply add one and make all the transitions leaving that state go back to itself. Since this new accepting state is unreachable from the start state, the new DFA still recognizes \( L \) (which happens to be the empty set). Now suppose that \( M \) has more than one state. For example, it may look like this: Then $M$ can be turned into an equivalent NFA $N$ with a single accepting state as follows: That is, we add a new accepting state, an $\epsilon$ transition from each of the old accepting states to the new one, and we make the old accepting states non-accepting. We can show that $L(N) = L(M)$ as follows. If $w$ is accepted by $M$, then $w$ leads to an old accepting, which implies that $N$ can accept $w$ by using one of the new $\epsilon$ transitions. If $w$ is accepted by $N$, then the reading of $w$ must finish with one of the new $\epsilon$ transitions. This implies that in $M$, $w$ leads to one of the old accepting states, so $w$ is accepted by $M$. 3.4.7. Suppose that $L$ is recognized by a DFA $M$. Transform $N$ into an equivalent NFA with a single accepting state. (The previous exercise says that this can be done.) Now reverse every transition in $N$: if a transition labeled $a$ goes from \( q_1 \) to \( q_2 \), make it go from \( q_2 \) to \( q_1 \). In addition, make the accepting state become the start state, and switch the accepting status of the new and old start states. Call the result \( N' \). We claim that \( N' \) recognizes \( L^R \). If \( w = w_1 \cdots w_n \) is accepted by \( N' \), it must be that there is a path through \( N' \) labeled \( w \). But then, this means that there was a path labeled \( w_n \cdots w_1 \) through \( N \). Therefore, \( w \) is the reverse of a string in \( L \), which means that \( w \in L^R \). It is easy to see that the reverse is also true. Chapter 4 Regular Expressions 4.1 Introduction 4.1.5. a) \((- \cup \epsilon)DD^*\) b) \((- \cup \epsilon)DD^* \cup (- \cup \epsilon)D^* \cdot DD^*\) c) \(_(_ \cup L \cup D)^*(L \cup D)(_ \cup L \cup D)^* \cup L(_ \cup L \cup D)^*\) d) \(D^7 \cup D^{10} \cup D^3 - D^4 \cup D^3 - D^3 - D^4\) 4.2 Formal Definition There are no exercises in this section. 4.3 More Examples 4.3.1. \( 0 \cup 1 \cup 0\Sigma^*0 \cup 1\Sigma^1 \). 4.3.2. a) \( 0\Sigma^*1 \). b) \( \Sigma1\Sigma^* \). c) \( \Sigma^{k-1}1\Sigma^* \). 4.3.3. a) \( (00 \cup 11)\Sigma^* \). b) \( \Sigma^*(00 \cup 11) \). c) \( \Sigma^*1\Sigma \). d) \( \Sigma^*1\Sigma^{k-1} \). 4.3.4. a) \( \Sigma^*1\Sigma^* \). b) \( 0^*10^* \). c) \( \Sigma^*1\Sigma^*1\Sigma^* \). d) \( 0^* \cup 0^*10^* \). e) \( (\Sigma^*1)^k\Sigma^* \). 4.3.5. a) \( \varepsilon \cup 1\Sigma^* \cup \Sigma^*0 \). b) \( \varepsilon \cup \Sigma \cup \Sigma0\Sigma^* \). c) \((\varepsilon \cup \Sigma)^{k-1} \cup \Sigma^{k-1}0\Sigma^*\). Another solution: \((\bigcup_{i=0}^{k-1} \Sigma^i) \cup \Sigma^{k-1}0\Sigma^*\). 4.3.6. a) \(01\Sigma^* \cup 11\Sigma*0\Sigma^*\). b) \(\Sigma^*1\Sigma^*1\Sigma^* \cup \Sigma^*0\Sigma*0\Sigma^*\). c) One way to go about this is to focus on the first two 1’s that occur in the string and then list the ways in which the 0 in the string can relate to those two 0’s. Here’s what you get: \[11^+ \cup 011^+ \cup 101^+ \cup 11^+01^*.\] d) Let \(E_0 = (1^*01^*0)^*1^*\) and \(D_0 = (1^*01^*0)^*1^*01^*\). The regular expression \(E_0\) describes the language of strings with an even number of 0’s while \(D_0\) describes the language of strings with an odd number of 0’s. Then the language of strings that contain at least two 1’s and an even number of 0’s can be described as follows: \[E_01E_01E_0 \cup E_01D_01D_0 \cup D_01E_01D_0 \cup D_01D_01E_0.\] 4.3.7. a) \((00)^*\#11^+\). b) \((00)^*11^+\). 4.4 Converting Regular Expressions into DFA’s 4.4.1. a) 4.5 Converting DFA's into Regular Expressions 4.5.1. a) We first add a new accepting state: We then remove state $q_1$: We remove state $q_2$: $$01^*1(0 \cup 01^*1)^*1$$ The final regular expression is $$(01^*1(0 \cup 01^*1)^*1)(\varepsilon \cup 01^*1(0 \cup 01^*1)^*)$$ b) First, we add a new accepting state: Then, we notice that state $q_2$ cannot be used to travel between the other two states. So we can just remove it: We remove state $q_1$: The final regular expression is $(0 \cup 0^+1)^*0^+$. 4.6. Precise Description of the Algorithm 4.6.1. The GNFA is \((Q, \{a, b, c\}, \delta, q_0, F)\) where \[ Q = \{q_0, q_1, q_2\} = \{q_0, q_2\} \] \[ F = \{q_2\} \] and \(\delta\) is defined by the following table: <table> <thead> <tr> <th>(\delta)</th> <th>(q_0)</th> <th>(q_1)</th> <th>(q_2)</th> </tr> </thead> <tbody> <tr> <td>(q_0)</td> <td>(a \cup b^+ c)</td> <td>(b)</td> <td>(c \cup b^+ a)</td> </tr> <tr> <td>(q_1)</td> <td>(c)</td> <td>(b)</td> <td>(a)</td> </tr> <tr> <td>(q_2)</td> <td>(b)</td> <td>(c)</td> <td>(a)</td> </tr> </tbody> </table> 4.6.2. The GNFA is \((Q, \{a, b, c\}, \delta, q_0, F)\) where \[ Q = \{q_0, q_2\} = \{q_0, q_2\} \] \[ F = \{q_2\} \] and \(\delta\) is defined by the following table: <table> <thead> <tr> <th>(\delta)</th> <th>(q_0)</th> <th>(q_2)</th> </tr> </thead> <tbody> <tr> <td>(q_0)</td> <td>(a \cup b^+ c)</td> <td>(c \cup b^+ a)</td> </tr> <tr> <td>(q_2)</td> <td>(b \cup c b^* c)</td> <td>(a \cup c b^* a)</td> </tr> </tbody> </table> Chapter 5 Nonregular Languages 5.1 Some Examples 5.1.1. Suppose that \( L = \{0^n 1^{2n} \mid n \geq 0\} \) is regular. Let \( M \) be a DFA that recognizes \( L \) and let \( n \) be the number of states of \( M \). Consider the string \( w = 0^n 1^{2n} \). As \( M \) reads the 0’s in \( w \), \( M \) goes through a sequence of states \( r_0, r_1, r_2, \ldots, r_n \). Because this sequence is of length \( n+1 \), there must be a repetition in the sequence. Suppose that \( r_i = r_j \) with \( i < j \). Then the computation of \( M \) on \( w \) looks like this: This implies that the string \( 0^i 0^{n-j} 1^{2n} = 0^{n-(j-i)} 1^{2n} \) is also accepted. But since this string no longer has exactly $n$ 0’s, it cannot belong to $L$. This contradicts the fact that $M$ recognizes $L$. Therefore, $M$ cannot exist and $L$ is not regular. 5.1.2. Suppose that $L = \{0^i1^j \mid 0 \leq i \leq 2j\}$ is regular. Let $M$ be a DFA that recognizes $L$ and let $n$ be the number of states of $M$. Consider the string $w = 0^{2n}1^n$. As $M$ reads the first $n$ 0’s in $w$, $M$ goes through a sequence of states $r_0, r_1, r_2, \ldots, r_n$. Because this sequence is of length $n + 1$, there must be a repetition in the sequence. Suppose that $r_i = r_j$ with $i < j$. Then the computation of $M$ on $w$ looks like this: ![Diagram](image) Now consider going twice around the loop. This implies that the string $0^i0^{2(j-i)}0^{2n-j}1^n = 0^{2n+(j-i)}1^n$ is also accepted. But since this string has more than $2n$ 0’s, it does not belong to $L$. This contradicts the fact that $M$ recognizes $L$. Therefore, $M$ cannot exist and $L$ is not regular. 5.1.3. Suppose that $L = \{ww^R \mid w \in \{0, 1\}^*\}$ is regular. Let $M$ be a DFA that recognizes $L$ and let $n$ be the number of states of $M$. Consider the string $w = 0^n1^n0^n$. As $M$ reads the first $n$ 0’s of $w$, $M$ goes through a sequence of states $r_0, r_1, r_2, \ldots, r_n$. Because this sequence is of length $n + 1$, there must be a repetition in the sequence. Suppose that $r_i = r_j$ with $i < j$. Then the computation of $M$ on $w$ looks like this: This implies that the string $0^i 0^{n-j} 110^n = 0^{n-(j-i)} 110^n$ is also accepted. But this string does not belong to $L$. This contradicts the fact that $M$ recognizes $L$. Therefore, $M$ cannot exist and $L$ is not regular.
{"Source-Url": "http://people.clarkson.edu/~alexis/CS345/Notes/solutions.pdf", "len_cl100k_base": 9997, "olmocr-version": "0.1.53", "pdf-total-pages": 59, "total-fallback-pages": 0, "total-input-tokens": 122456, "total-output-tokens": 12401, "length": "2e13", "weborganizer": {"__label__adult": 0.0006089210510253906, "__label__art_design": 0.0007786750793457031, "__label__crime_law": 0.00044155120849609375, "__label__education_jobs": 0.00566864013671875, "__label__entertainment": 0.00028324127197265625, "__label__fashion_beauty": 0.0003483295440673828, "__label__finance_business": 0.0003058910369873047, "__label__food_dining": 0.0008192062377929688, "__label__games": 0.0025119781494140625, "__label__hardware": 0.0019216537475585935, "__label__health": 0.0011377334594726562, "__label__history": 0.0006499290466308594, "__label__home_hobbies": 0.00024127960205078125, "__label__industrial": 0.0008707046508789062, "__label__literature": 0.0017461776733398438, "__label__politics": 0.0004498958587646485, "__label__religion": 0.0012607574462890625, "__label__science_tech": 0.1951904296875, "__label__social_life": 0.00023794174194335935, "__label__software": 0.007526397705078125, "__label__software_dev": 0.775390625, "__label__sports_fitness": 0.00048160552978515625, "__label__transportation": 0.0009317398071289062, "__label__travel": 0.0002765655517578125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 26563, 0.06643]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 26563, 0.5103]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 26563, 0.77777]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 0, null], [0, 983, false], [983, 1412, null], [1412, 2709, null], [2709, 3091, null], [3091, 3156, null], [3156, 3156, null], [3156, 3374, null], [3374, 3491, null], [3491, 3498, null], [3498, 3505, null], [3505, 4145, null], [4145, 4481, null], [4481, 4575, null], [4575, 4647, null], [4647, 5129, null], [5129, 5473, null], [5473, 6179, null], [6179, 7684, null], [7684, 8559, null], [8559, 9434, null], [9434, 10443, null], [10443, 11916, null], [11916, 12092, null], [12092, 12406, null], [12406, 12792, null], [12792, 13008, null], [13008, 13121, null], [13121, 13121, null], [13121, 13124, null], [13124, 13235, null], [13235, 13309, null], [13309, 13309, null], [13309, 13705, null], [13705, 14184, null], [14184, 14261, null], [14261, 14296, null], [14296, 15148, null], [15148, 15776, null], [15776, 16463, null], [16463, 16972, null], [16972, 17937, null], [17937, 19391, null], [19391, 20296, null], [20296, 20913, null], [20913, 21275, null], [21275, 21832, null], [21832, 22804, null], [22804, 22862, null], [22862, 22862, null], [22862, 22862, null], [22862, 23139, null], [23139, 23374, null], [23374, 24201, null], [24201, 24201, null], [24201, 24873, null], [24873, 26334, null], [26334, 26563, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 0, null], [0, 983, true], [983, 1412, null], [1412, 2709, null], [2709, 3091, null], [3091, 3156, null], [3156, 3156, null], [3156, 3374, null], [3374, 3491, null], [3491, 3498, null], [3498, 3505, null], [3505, 4145, null], [4145, 4481, null], [4481, 4575, null], [4575, 4647, null], [4647, 5129, null], [5129, 5473, null], [5473, 6179, null], [6179, 7684, null], [7684, 8559, null], [8559, 9434, null], [9434, 10443, null], [10443, 11916, null], [11916, 12092, null], [12092, 12406, null], [12406, 12792, null], [12792, 13008, null], [13008, 13121, null], [13121, 13121, null], [13121, 13124, null], [13124, 13235, null], [13235, 13309, null], [13309, 13309, null], [13309, 13705, null], [13705, 14184, null], [14184, 14261, null], [14261, 14296, null], [14296, 15148, null], [15148, 15776, null], [15776, 16463, null], [16463, 16972, null], [16972, 17937, null], [17937, 19391, null], [19391, 20296, null], [20296, 20913, null], [20913, 21275, null], [21275, 21832, null], [21832, 22804, null], [22804, 22862, null], [22862, 22862, null], [22862, 22862, null], [22862, 23139, null], [23139, 23374, null], [23374, 24201, null], [24201, 24201, null], [24201, 24873, null], [24873, 26334, null], [26334, 26563, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 26563, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 26563, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 26563, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 26563, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 26563, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 26563, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 26563, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 26563, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 26563, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 26563, null]], "pdf_page_numbers": [[0, 0, 1], [0, 0, 2], [0, 983, 3], [983, 1412, 4], [1412, 2709, 5], [2709, 3091, 6], [3091, 3156, 7], [3156, 3156, 8], [3156, 3374, 9], [3374, 3491, 10], [3491, 3498, 11], [3498, 3505, 12], [3505, 4145, 13], [4145, 4481, 14], [4481, 4575, 15], [4575, 4647, 16], [4647, 5129, 17], [5129, 5473, 18], [5473, 6179, 19], [6179, 7684, 20], [7684, 8559, 21], [8559, 9434, 22], [9434, 10443, 23], [10443, 11916, 24], [11916, 12092, 25], [12092, 12406, 26], [12406, 12792, 27], [12792, 13008, 28], [13008, 13121, 29], [13121, 13121, 30], [13121, 13124, 31], [13124, 13235, 32], [13235, 13309, 33], [13309, 13309, 34], [13309, 13705, 35], [13705, 14184, 36], [14184, 14261, 37], [14261, 14296, 38], [14296, 15148, 39], [15148, 15776, 40], [15776, 16463, 41], [16463, 16972, 42], [16972, 17937, 43], [17937, 19391, 44], [19391, 20296, 45], [20296, 20913, 46], [20913, 21275, 47], [21275, 21832, 48], [21832, 22804, 49], [22804, 22862, 50], [22862, 22862, 51], [22862, 22862, 52], [22862, 23139, 53], [23139, 23374, 54], [23374, 24201, 55], [24201, 24201, 56], [24201, 24873, 57], [24873, 26334, 58], [26334, 26563, 59]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 26563, 0.06972]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
b7012dfc790d7c84ff20b4a78290c6d8c5cf94b9
STIX™ Version 2.0. Part 5: STIX Patterning Committee Specification Draft 0402 / Public Review Draft 0402 24 February 03 May 2017 Specification URIs This version: http://docs.oasis-open.org/cti/stix/v2.0/csprd02/part5-stix-patterning/stix-v2.0-csprd02-part5-stix-patterning.docx (Authoritative) http://docs.oasis-open.org/cti/stix/v2.0/csprd02/part5-stix-patterning/stix-v2.0-csprd02-part5-stix-patterning.html http://docs.oasis-open.org/cti/stix/v2.0/csprd02/part5-stix-patterning/stix-v2.0-csprd02-part5-stix-patterning.pdf Previous version: http://docs.oasis-open.org/cti/stix/v2.0/csprd01/part5-stix-patterning/stix-v2.0-csprd01-part5-stix-patterning.docx (Authoritative) http://docs.oasis-open.org/cti/stix/v2.0/csprd01/part5-stix-patterning/stix-v2.0-csprd01-part5-stix-patterning.html http://docs.oasis-open.org/cti/stix/v2.0/csprd01/part5-stix-patterning/stix-v2.0-csprd01-part5-stix-patterning.pdf Previous version: N/A Latest version: http://docs.oasis-open.org/cti/stix/v2.0/stix-v2.0-part5-stix-patterning.docx (Authoritative) http://docs.oasis-open.org/cti/stix/v2.0/stix-v2.0-part5-stix-patterning.html http://docs.oasis-open.org/cti/stix/v2.0/stix-v2.0-part5-stix-patterning.pdf Technical Committee: OASIS Cyber Threat Intelligence (CTI) TC Chair: Richard Struse (Richard.Struse@HQ.DHS.GOV), DHS Office of Cybersecurity and Communications (CS&C) Editors: Ivan Kirillov (ikirillov@mitre.org), MITRE Corporation Trey Darley (trey@kingfisherops.com), Kingfisher Operations, sprl Ivan Kirillov (ikirillov@mitre.org), MITRE Corporation Additional artifacts: This prose specification is one component of a Work Product that also includes: • **STIX™ Version 2.0. Part 4: Cyber Observable Objects.** [http://docs.oasis-open.org/cti/stix/v2.0/csprd02/part4-cyber-observable-objects/stix-v2.0-csprd02-part4-cyber-observable-objects.html](http://docs.oasis-open.org/cti/stix/v2.0/csprd02/part4-cyber-observable-objects/stix-v2.0-csprd02-part4-cyber-observable-objects.html). • **(this document) STIX™ Version 2.0. Part 5: STIX Patterning.** [http://docs.oasis-open.org/cti/stix/v2.0/csprd02/part5-stix-patterning/stix-v2.0-csprd02-part5-stix-patterning.html](http://docs.oasis-open.org/cti/stix/v2.0/csprd02/part5-stix-patterning/stix-v2.0-csprd02-part5-stix-patterning.html). **Related work:** This specification replaces or supersedes: This specification is related to: • **TAXII™ Version 2.0.** Edited by Bret Jordan and John Wunder, Mark Davidson, and Bret Jordan. Latest version: [http://docs.oasis-open.org/cti/taxii/v2.0/taxii-v2.0.html](http://docs.oasis-open.org/cti/taxii/v2.0/taxii-v2.0.html). Work in progress. **Abstract:** Structured Threat Information Expression (STIX™) is a language for expressing cyber threat and observable information. This document defines a patterning language to enable the detection of possibly malicious activity on networks and endpoints. **Status:** This document was last revised or approved by the OASIS Cyber Threat Intelligence (CTI) TC on the above date. The level of approval is also listed above. Check the “Latest version” location noted above for possible later revisions of this document. Any other numbered Versions and other technical work produced by the Technical Committee (TC) are listed at [https://www.oasis-open.org/committees/cti_home.php?wg_abbrev=cti#technical](https://www.oasis-open.org/committees/cti_home.php?wg_abbrev=cti#technical). TC members should send comments on this specification to the TC’s email list. Others should send comments to the TC’s public comment list, after subscribing to it by following the instructions at the “Send A Comment” button on the TC’s web page at [https://www.oasis-open.org/committees/cti/](https://www.oasis-open.org/committees/cti/). This Committee Specification Public Review Draft is provided under the Non-Assertion Mode of the OASIS IPR Policy, the mode chosen when the Technical Committee was established. For information on whether any patents have been disclosed that may be essential to implementing this specification, and any offers of patent licensing terms, please refer to the Intellectual Property Rights section of the TC’s web page ([https://www.oasis-open.org/committees/cti/ipr.php](https://www.oasis-open.org/committees/cti/ipr.php)). Note that any machine-readable content (Computer Language Definitions) declared Normative for this Work Product is provided in separate plain text files. In the event of a discrepancy between any such plain text file and display content in the Work Product’s prose narrative document(s), the content in the separate plain text file prevails. **Citation format:** When referencing this specification the following citation format should be used: **[STIX-v2.0-Pt5-Patterning]** Notices Copyright © OASIS Open 2017. All Rights Reserved. All capitalized terms in the following text have the meanings assigned to them in the OASIS Intellectual Property Rights Policy (the "OASIS IPR Policy"). The full Policy may be found at the OASIS website. This document and translations of it may be copied and furnished to others, and derivative works that comment on or otherwise explain it or assist in its implementation may be prepared, copied, published, and distributed, in whole or in part, without restriction of any kind, provided that the above copyright notice and this section are included on all such copies and derivative works. However, this document itself may not be modified in any way, including by removing the copyright notice or references to OASIS, except as needed for the purpose of developing any document or deliverable produced by an OASIS Technical Committee (in which case the rules applicable to copyrights, as set forth in the OASIS IPR Policy, must be followed) or as required to translate it into languages other than English. The limited permissions granted above are perpetual and will not be revoked by OASIS or its successors or assigns. This document and the information contained herein is provided on an "AS IS" basis and OASIS DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY OWNERSHIP RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. OASIS requests that any OASIS Party or any other party that believes it has patent claims that would necessarily be infringed by implementations of this OASIS Committee Specification or OASIS Standard, to notify OASIS TC Administrator and provide an indication of its willingness to grant patent licenses to such patent claims in a manner consistent with the IPR Mode of the OASIS Technical Committee that produced this specification. OASIS invites any party to contact the OASIS TC Administrator if it is aware of a claim of ownership of any patent claims that would necessarily be infringed by implementations of this specification by a patent holder that is not willing to provide a license to such patent claims in a manner consistent with the IPR Mode of the OASIS Technical Committee that produced this specification. OASIS may include such claims on its website, but disclaims any obligation to do so. OASIS takes no position regarding the validity or scope of any intellectual property or other rights that might be claimed to pertain to the implementation or use of the technology described in this document or the extent to which any license under such rights might or might not be available; neither does it represent that it has made any effort to identify any such rights. Information on OASIS' procedures with respect to rights in any document or deliverable produced by an OASIS Technical Committee can be found on the OASIS website. Copies of claims of rights made available for publication and any assurances of licenses to be made available, or the result of an attempt made to obtain a general license or permission for the use of such proprietary rights by implementers or users of this OASIS Committee Specification or OASIS Standard, can be obtained from the OASIS TC Administrator. OASIS makes no representation that any information or list of intellectual property rights will at any time be complete, or that any claims in such list are, in fact, Essential Claims. The name "OASIS" is a trademark of OASIS, the owner and developer of this specification, and should be used only to refer to the organization and its official outputs. OASIS welcomes reference to, and implementation and use of, specifications, while reserving the right to enforce its marks against misleading uses. Please see https://www.oasis-open.org/policies-guidelines/trademark for above guidance. STIX™, CYBOX™, AND TAXII™ (STANDARD OR STANDARDS) AND THEIR COMPONENT PARTS ARE PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT THESE STANDARDS OR ANY OF THEIR COMPONENT PARTS WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE STANDARDS OR THEIR COMPONENT PARTS WILL BE ERROR FREE, OR ANY WARRANTY THAT THE DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE STANDARDS OR THEIR COMPONENT PARTS. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT OR ITS CONTRACTORS OR SUBCONTRACTORS BE LIABLE FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF, RESULTING FROM, OR IN ANY WAY CONNECTED WITH THESE STANDARDS OR THEIR COMPONENT PARTS OR ANY PROVIDED DOCUMENTATION, WHETHER OR NOT BASED UPON WARRANTY, CONTRACT, TORT, OR OTHERWISE, WHETHER OR NOT INJURY WAS SUSTAINED BY PERSONS OR PROPERTY OR OTHERWISE, AND WHETHER OR NOT LOSS WAS SUSTAINED FROM, OR AROSE OUT OF THE RESULTS OF, OR USE OF, THE STANDARDS, THEIR COMPONENT PARTS, AND ANY PROVIDED DOCUMENTATION. THE UNITED STATES GOVERNMENT DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THE STANDARDS OR THEIR COMPONENT PARTS ATTRIBUTABLE TO ANY THIRD PARTY, IF PRESENT IN THE STANDARDS OR THEIR COMPONENT PARTS AND DISTRIBUTES IT OR THEM "AS IS." # Table of Contents 1 Introduction .................................................................................................................. 6 1.0.1 IPR Policy ............................................................................................................. 6 1.1 Terminology ............................................................................................................. 6 1.2 Normative References .............................................................................................. 6 1.3 Non-Normative Reference ....................................................................................... 7 1.4 ANTLR Grammar ..................................................................................................... 7 1.5 Naming Requirements .............................................................................................. 8 1.5.1 Property Names and String Literals ................................................................. 8 1.5.2 Reserved Names ................................................................................................. 8 1.6 Document Conventions ......................................................................................... 8 1.6.1 Naming Conventions ......................................................................................... 8 1.6.2 Font Colors and Style ....................................................................................... 8 2 Definitions .................................................................................................................. 9 2.1 Constants ............................................................................................................... 11 3 STIX Patterns ............................................................................................................. 14 4 Pattern Expressions .................................................................................................... 16 4.1 Observation Expressions ...................................................................................... 16 4.1.1 Observation Expression Qualifiers ............................................................... 17 4.1.2 Observation Operators ............................................................................... 18 4.1.3 Operator Precedence .................................................................................. 19 4.2 Comparison Expression ....................................................................................... 19 4.2.1 Comparison Operators ............................................................................. 20 4.2.2 String Comparison ..................................................................................... 22 4.2.3 Binary Type Comparison ........................................................................... 22 4.2.4 Native Format Comparison ...................................................................... 22 5 Object Path Syntax .................................................................................................... 24 5.1 Basic Object Properties ....................................................................................... 24 5.2 List Object Properties ......................................................................................... 24 5.3 Dictionary Object Properties .............................................................................. 25 5.4 Object Reference Properties .............................................................................. 25 6 Examples .................................................................................................................... 27 7 Conformance .............................................................................................................. 30 7.1 Pattern Producer .................................................................................................. 30 7.2 Pattern Consumer ............................................................................................... 30 7.3 Conformance Levels ............................................................................................ 30 7.3.1 Level 1: Basic Conformance .................................................................... 30 7.3.2 Level 2: Basic Conformance plus Observation Operators ...................... 31 7.3.3 Level 3: Full Conformance ......................................................................... 31 Appendix A. Glossary .................................................................................................... 32 Appendix B. Acknowledgments ..................................................................................... 33 Appendix C. Revision History ....................................................................................... 34 1 Introduction In order to detect a large proportion of malicious behavior in the course of defending our networks, it is necessary to correlate telemetry from both host-based and network-based tools. Before undertaking work on STIX Patterning, as a technical subcommittee we made a thorough effort to evaluate whether there was already an existing patterning language that would support our use cases available as an open standard. In particular, we considered whether it would be possible to extend the syntax of Snort or Yara rather than create an entirely new language. This was eventually ruled out as unfeasible, both from a technical perspective as well as taking into consideration that from a licensing/IPR perspective, extending either of those languages under the auspices of OASIS would have been problematic. Given that STIX Patterning exists to support STIX Indicators, consider what value Indicator-sharing provides: a mechanism for communicating how to find malicious code and/or threat actors active within a given network. Among the essential tools widely deployed by defenders are SIEMs (or similar data processing platforms capable of consuming, correlating, and interrogating large volumes of network and host-based telemetry.) These data processing platforms utilize proprietary query languages. As development began on STIX Patterning, one of the principal design goals was to create an abstraction layer capable of serializing these proprietary correlation rules so as to enhance the overall value proposition of indicator-sharing. In order to enhance detection of possibly malicious activity on networks and endpoints, a standard language is needed to describe what to look for in a cyber environment. The STIX Patterning language allows matching against timestamped Cyber Observable data (such as STIX Observed Data Objects) collected by a threat intelligence platform or other similar system so that other analytical tools and systems can be configured to react and handle incidents that might arise. This first language release is focused on supporting a common set of use cases and therefore allows for the expression of an initial set of patterns that producers and consumers of STIX can utilize. As more complex patterns are deemed necessary, the STIX patterning language will be extended in future releases to improve its effectiveness as an automated detection/remediation method. 1.0.1 IPR Policy This Committee Specification Public Review Draft is provided under the Non-Assertion Mode of the OASIS IPR Policy, the mode chosen when the Technical Committee was established. For information on whether any patents have been disclosed that may be essential to implementing this specification, and any offers of patent licensing terms, please refer to the Intellectual Property Rights section of the TC’s web page (https://www.oasis-open.org/committees/cti/ipr.php). 1.1 Terminology The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in [RFC2119]. All text is normative except for examples and any text marked non-normative. CAPEC—Common Attack Pattern Enumeration and Classification Consumer—Any entity that receives STIX content. CTI—Cyber Threat Intelligence Entity—Anything that has a separately identifiable existence (e.g., organization, person, group, etc.). IEP—FIRST (Forum of Incident Response and Security Teams) Information Exchange Policy Instance—A single occurrence of a STIX object version. MTI—Mandatory To Implement MVP—Minimally Viable Product Object Creator—The entity that created or updated a STIX object (see section 3.3 of STIX™ Version 2.0 Part 1: STIX Core Concepts). Object Representation—An instance of an object version that is serialized as STIX. Producer—Any entity that distributes STIX content, including object creators as well as those passing along existing content. SDO—STIX Domain Object SRO—STIX Relationship Object STIX—Structured Threat Information Expression STIX Content—STIX documents, including STIX Objects, STIX Objects grouped as bundles, etc. STIX Object—A STIX Domain Object (SDO) or STIX Relationship Object (SRO) TAXII—An application layer protocol for the communication of cyber threat information. TLP—Traffic Light Protocol TTP—Tactic, technique, or procedure; behaviors and resources that attackers use to carry out their attacks 1.2 Normative References 1.3 Non-Normative Reference 1.4 ANTLR Grammar The latest ANTLR grammar for the patterning specification can be found on Github in the Pattern Grammar repository [Pattern Grammar]. Note that this grammar is non-normative and is intended solely as an aid to implementers. 1.5 Naming Requirements 1.5.1 Property Names and String Literals In the JSON serialization all property names and string literals MUST be exactly the same, including case, as the names listed in the property tables in this specification. For example, the SDO common property created_by_ref must result in the JSON key name "created_by_ref". Properties marked required in the property tables MUST be present in the JSON serialization. 1.5.2 Reserved Names Reserved property names are marked with a type called RESERVED and a description text of "RESERVED FOR FUTURE USE". Any property name that is marked as RESERVED MUST NOT be present in STIX content conforming to this version of the specification. 1.5.6 Document Conventions 1.5.6.1 Naming Conventions All type names, property names, and literals are in lowercase, except when referencing canonical names defined in another standard (e.g., literal values from an IANA registry). Words in property names are separated with an underscore(_), while words in type names and string enumerations are separated with a dash (-). All type names, property names, object names, and vocabulary terms are between three and 250 characters long. In the JSON serialization all property names and string literals MUST be exactly the same, including case, as the names listed in the property tables in this specification. For example, the Cyber Observable Object property extensions must result in the JSON key name "extensions". Properties marked required in the property tables MUST be present in the JSON serialization. 1.5.6.2 Font Colors and Style The following color, font and font style conventions are used in this document: - The Consolas font is used for all type names, property names and literals. - type names are in red with a light red background - hashes=type - property names are in bold style - protocols - literals (values) are in greenblue with a greenblue background - SHA-256 - In an object's property table, if a common property is being redefined in some way, then the background is dark gray. - All examples in this document are expressed in JSON. They are in Consolas 9-point font, with straight quotes, black text and a light bluegrey background, and 2-space indentation. - Parts of the example may be omitted for conciseness and clarity. These omitted parts are denoted with the ellipses (...). 2 Common Data Types # Definitions The terms defined below are used throughout this document. <table> <thead> <tr> <th>Terms</th> <th>Definitions</th> <th>Example</th> </tr> </thead> <tbody> <tr> <td>whitespace</td> <td>Any Unicode code point that has WSpace set as a property, for example, line feeds, carriage returns, tabs, and spaces.</td> <td>n/a</td> </tr> <tr> <td>Observation</td> <td>Observations represent data about systems or networks that is observed at a particular point in time - for example, information about a file that existed, a process that was observed running, or network traffic that was transmitted between two IPs. In STIX, Observations are represented by Observed Data SDOs, with their first_observed timestamp defining the observation time.</td> <td>n/a</td> </tr> <tr> <td>Comparison Expression</td> <td>Comparison Expressions are the basic components of Observation Expressions. They consist of an Object Path and a constant joined by a Comparison Operator (listed in section 4.2.1, Comparison Operators).</td> <td>user-account:value = 'Peter'</td> </tr> <tr> <td>Comparison Operators</td> <td>Comparison Operators are used within Comparison Expressions to compare an Object Path against a constant or set of constants.</td> <td>MATCHES</td> </tr> <tr> <td>Object Path</td> <td>Object Paths define which properties of Cyber Observable Objects should be evaluated as part of a Comparison Expression. Cyber Observable Objects and their properties are defined in STIX™ Version 2.0. Part 4: Cyber Observable Objects.</td> <td>ipv6-addr:value</td> </tr> <tr> <td>Observation Expression</td> <td>Observation Expressions consist of one or more Comparison Expressions joined with Boolean Operators and surrounded by square brackets. An Observation Expression may consist of two Observation Expressions joined by an Observation Operator. This may be applied</td> <td>[ipv4-addr:value = '203.0.113.1' OR ipv4-addr:value = '203.0.113.2'] or (with Observation Operator):</td> </tr> </tbody> </table> Observation Expressions may optionally be followed by one or more Qualifiers further constraining the result set. Qualifiers may be applied to all of the Observation Expressions joined with Observation Operators; in this case, parentheses should be used to group the set of Observation Expressions, with the Qualifier following the closing parenthesis. ### Boolean Operators Boolean Operators are used to combine Comparison Expressions within an Observation Expression. (Comparison Expressions) user-account:value = 'Peter' OR user-account:value = 'Mary' ### Qualifier Qualifiers provide a restriction on the Observations that are considered valid for matching the preceding Observation Expression. [file:name = 'foo.dll'] START '2016-06-01T00:00:00Z' STOP '2016-07-01T00:00:00Z' ### Observation Operators Observation Operators are used to combine two Observation Expressions operating on two different Observed Data instances into a single pattern. [ipv4-addr:value = '198.51.100.5'] AND [ipv4-addr:value = '198.51.100.10'] ### Pattern Expression A Pattern Expression represents a valid instance of a Cyber Observable pattern. The most basic Pattern Expression consists of a single Observation Expression containing a single Comparison Expression. [file:size = 25536] ## 2.1 Constants The data types enumerated below are supported as operands within Comparison Expressions. This table is included here as a handy reference for implementers. Note that unlike Cyber Observable Objects (which are defined in terms of the MTI JSON serialization), STIX Patterns are Unicode strings, regardless of the underlying serialization, hence the data types defined in the table below in some cases differ from the definitions contained in [STIX™ Version 2.0. Part 3: Cyber Observable Core Concepts](https://docs.oasis-open.org/mitre-stix/v2.0/stix-schema-v2.0.xsd). Each constant defined in Patterning has a limited set of Cyber Observable Data types that they are allowed to be compared against. In some cases, there are multiple Cyber Observable Data Types that could be compared against a STIX Patterning Constant; this is due to the fact that certain Cyber Observable Data Types are semantically indistinguishable because of their JSON serialization. The Cyber Observable Comparable Data Type(s) column in the table below defines these limitations. <table> <thead> <tr> <th>STIX Patterning Constant</th> <th>Cyber Observable Comparable Data Type(s)</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>boolean</td> <td>boolean</td> <td>A constant of boolean type encodes truth or falsehood. Boolean truth is denoted by the literal true and falsehood by the literal false.</td> </tr> <tr> <td>binary</td> <td>binary</td> <td>A constant of binary type is a base64 encoded array of octets (8-bit bytes) per [RFC4648]. The base64 string MUST be surrounded by single quotes (apostrophes (’’ U+0027) and prefixed by a 'b' (U+0062). Line feeds in the base64 encoded data MUST be supported and ignored, but are not required to be inserted. Example: b'ABI='</td> </tr> <tr> <td>hex</td> <td>binary</td> <td>A constant of hex type encodes an array of octets (8-bit bytes) as hexadecimal. The string MUST consist of an even number of hexadecimal characters, which are the digits '0' through '9' and the letters 'a' through 'f'. The hex string MUST be surrounded by single quotes (apostrophes (’’ U+0027) and prefixed by an 'h' (U+0068). Example: h'0012'</td> </tr> <tr> <td>integer</td> <td>integer</td> <td>A constant of integer type encodes a signed decimal number in the usual fashion (e.g., 123). In the case of positive integers, the integer MUST be represented as-is, omitting the plus sign (’+’ U+002b). Negative integers MUST be represented by prepending a hyphen-minus (’−’ U+002d). When compared against a Cyber Observable</td> </tr> </tbody> </table> <table> <thead> <tr> <th>Type</th> <th>Subtype</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>float</td> <td></td> <td>The full value must be compared and must not be truncated. For example, the result of comparing a STIX Patterning constant integer value of 1 to a Cyber Observable float value of 1.5 is not equal. The valid range of values is defined in <a href="https://docs.oasis-open.org/stix/2.0/pstix20/v2.0-ps/stix2-v2.0-ps.html">STIX™ Version 2.0. Part 3: Cyber Observable Core Concepts</a>.</td> </tr> <tr> <td>integer</td> <td>float</td> <td>A constant of float type encodes a floating point number in the usual fashion (e.g., 123.456). In the case of positive floating point number, the floating point number <strong>MUST</strong> be represented as-is, omitting the <code>+</code> (U+002b). Negative floating point numbers <strong>MUST</strong> be represented by prepending a <code>-</code> (hyphen-minus (U+002d)). The valid range of values is defined in <a href="https://docs.oasis-open.org/stix/2.0/pstix20/v2.0-ps/stix2-v2.0-ps.html">STIX™ Version 2.0. Part 3: Cyber Observable Core Concepts</a>.</td> </tr> <tr> <td>string</td> <td></td> <td>A constant of string type encodes a string as a list of Unicode code points surrounded by single quotes (apostrophes (U+0027)). The escape character is the backslash (\ (U+005c). Only the single quote or the backslash may follow, and in that case, the respective character is used for the sequence. If a string only contains codepoints less than (U+0100), then the string <strong>MAY</strong> be converted to a binary type value (if needed for comparison). The mapping is code point U+0000 to 00 through U+00ff to ff.</td> </tr> <tr> <td>timestamp</td> <td></td> <td>A constant of timestamp type encodes a STIX timestamp (as specified in section 2.10 of <a href="https://docs.oasis-open.org/stix/2.0/pstix20/v2.0-ps/stix2-v2.0-ps.html">STIX™ Version 2.0 Part 1: STIX Core Concepts</a>) as a string. The timestamp string <strong>MUST</strong> be surrounded by single quotes (apostrophes (U+0027)) and prefixed with a 't' (U+0074). Example: <code>t’2014-01-13T07:03:17Z’</code></td> </tr> </tbody> </table> 3 STIX™ Patterns STIX Patterns are composed of multiple building blocks, ranging from simple key-value comparisons to more complex, context-sensitive expressions. The most fundamental building block is the Comparison Expression, which is a comparison between a single property of a Cyber Observable Object and a given constant using a Comparison Operator. As a simple example, one might use the following Comparison Expression (contained within an Observation Expression) to match against an IPv4 address: ``` [ipv4-addr:value = '198.51.100.1/32'] ``` Moving up a level of complexity, the next building block of a STIX Pattern is the Observation Expression, which consists of one or more Comparison Expressions joined by Boolean Operators and bounded by square brackets. An Observation Expression refines which set of Cyber Observable data (i.e., as part of an Observation) will match the pattern, by selecting the set that has the Cyber Observable Objects specified by the Comparison Expressions. An Observation Expression consisting of a single Comparison Expression is the most basic valid STIX Pattern. Building upon the previous example, one might construct an Observation Expression to match against multiple IPv4 addresses and an IPv6 address: ``` [ipv4-addr:value = '198.51.100.1/32' OR ipv4-addr:value = '203.0.113.33/32' OR ipv6-addr:value = '2001:0db8:dead:beef:dead:beef:dead:0001/128'] ``` Observation Expressions may be followed by one or more Qualifiers, which allow for the expression of further restrictions on the set of data matching the pattern. Continuing with the above example, one might use a Qualifier to state that the IP addresses must be observed several times in repetition: ``` [ipv4-addr:value = '198.51.100.1/32' OR ipv4-addr:value = '203.0.113.33/32' OR ipv6-addr:value = '2001:0db8:dead:beef:dead:beef:dead:0001/128'] REPEATS 5 TIMES ``` The final, highest level building block of STIX Patterning combines two or more Object Expressions via Observation Operators, yielding a STIX Pattern capable of matching across multiple STIX Observed Data SDOs. Building further upon our previous example, one might use an Observation Operator to specify that an observation of a particular domain name must follow the observation of the IP addresses (note the use of parentheses to encapsulate the two Observation Expressions), along with a different Qualifier to state that both the IP address and domain name must be observed within a specific time window: ``` ([ipv4-addr:value = '198.51.100.1/32' OR ipv4-addr:value = '203.0.113.33/32' OR ipv6-addr:value = '2001:0db8:dead:beef:dead:beef:dead:0001/128'] FOLLOWEDBY [domain-name:value = 'example.com']) WITHIN 600 SECONDS ``` The diagram below depicts a truncated version of the various STIX Patterning components in the above example. Pattern ``` [[ipv4-addr.value = 'x' OR ipv4-addr.value = 'y'] FOLLOWEDBY [domain-name.value = 'z']] WITHIN 600 SECONDS ``` Pattern ``` [[ipv4-addr.value = 'x' OR ipv4-addr.value = 'y'] FOLLOWEDBY [domain-name.value = 'z']] WITHIN 600 SECONDS ``` 4 Pattern Expressions Pattern Expressions evaluate to true or false. They comprise one or more Observation Expressions joined by Observation Operators. Pattern Expressions are evaluated against a set of specific Observations. If one or more of those Observations match the Pattern Expression, then it evaluates to true. If no Observations match, the Pattern Expression evaluates to false. Pattern Expressions MUST be encoded as Unicode strings. Whitespace (i.e., Unicode code points where WSpace=Y) in the pattern string is used to delimit parts of the pattern, including keywords, constants, and field objects. Whitespace characters between operators, including line feeds and carriage returns, MUST be allowed. Multiple whitespace characters in a row MUST be treated as a single whitespace character. An invalid pattern resulting from parsing error or invalid constants (e.g., an invalid hex or binary constant) MUST NOT match any Observations. 4.1 Observation Expressions Observation Expressions comprise one or more Comparison Expressions, joined via Boolean Operators. Observation Expressions MUST be delimited by square brackets \[ \text{left square bracket} (\[' U+005b) and \] \text{right square bracket} (\'] U+005d). One or more Observation Expression Qualifiers MAY be provided after the closing square bracket or closing parenthesis of an Observation Expression. Observation Expressions MAY be joined by Observation Operators. Individual Observation Expressions (e.g., \[[a = b]\]) match against a single Observation, i.e., a single STIX Observed Data instance. In cases where matching against multiple Observations is required, two or more Observation Expressions may be combined via Observation Operators, indicating that the pattern must be evaluated against two or more distinct Observations. When matching an Observation against an Observation Expression, all Comparison Expressions contained within the Observation Expression MUST match against the same Cyber Observable Object, including referenced objects. An Observation Expression MAY contain Comparison Expressions with Object Paths that are based on different object types, but such Comparison Expressions MUST be joined by OR. The Comparison Expressions of an Observation Expression that use AND MUST use the same base Object Path, e.g., file: For example, consider the following Pattern Expression: \[(\text{type-}a:\text{property}-j = 'W' \text{ AND type-}a:\text{property}-k = 'X') \text{ OR (type-}b:\text{property}-m = 'Y' \text{ AND type-}b:\text{property}-n = 'Z')\] This expression can match an Observable with an object of either type-\text{a} or type-\text{b}, but both Comparison Expressions for that specific type must evaluate to true for the same object. Comparison Expressions that are intended to match a single object type can be joined by either AND or OR. For example: \[(\text{type-}a:\text{property}-j = 'W' \text{ AND type-}a:\text{property}-k = 'X' \text{ OR type-}a:\text{property}-l = 'Z')\] As AND has higher precedence than OR, the preceding example requires an Observation to have either both property-\text{j} = 'W' and property-\text{k} = 'X' or just property-\text{l} = 'Z'. Observation Expressions, along with their Observation Operators and optional Qualifiers, **MAY** be surrounded with parenthesis to delineate which Observation Expressions the Qualifiers apply to. For example: ``` ([ a ] AND [ b ] REPEATS 5 TIMES) WITHIN 5 MINUTES ``` The preceding example results in one `a` and 5 `b`'s that all match in a 5 minute period. As another example: ``` ([ a ] AND [ b ]) REPEATS 5 TIMES WITHIN 5 MINUTES ``` The preceding example results in 5 `a`'s and 5 `b`'s (10 Observations) that all match in a 5 minute period. ### 4.1.1 Observation Expression Qualifiers Each Observation Expression **MAY** have additional temporal or repetition restrictions using the respective `WITHIN`, `START/STOP`, and `REPEATS` keywords. <table> <thead> <tr> <th>Qualifiers</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>a REPEATS x TIMES</code></td> <td><code>a</code> <strong>MUST</strong> be an Observation Expression or a preceding Qualifier. <code>a</code> <strong>MUST</strong> match exactly <code>x</code> times, where each match is a different Observation. <code>x</code> <strong>MUST</strong> be a positive integer.</td> </tr> <tr> <td></td> <td>This is purely a shorthand way of writing: “<code>a</code>” followed by “AND <code>a</code>”, <code>x</code>-1 times.</td> </tr> <tr> <td></td> <td>Example: <code>b</code> FOLLOWEDBY <code>c</code> REPEATS 5 TIMES</td> </tr> <tr> <td></td> <td>In this example, the <code>REPEATS</code> applies to <code>c</code>, and it does not apply to <code>b</code>. The results will be <code>b</code> plus 5 <code>c</code>'s where all 5 <code>c</code>'s were observed after the <code>b</code>. Note that there is only a single Qualifier in this example; more complex patterns may use more than one.</td> </tr> <tr> <td><code>a WITHIN x SECONDS</code></td> <td><code>a</code> <strong>MUST</strong> be an Observation Expression or a preceding Qualifier. All Observations matched by <code>a</code> <strong>MUST</strong> occur, or have been observed, within the specified time window. <code>x</code> <strong>MUST</strong> be a positive floating point value.</td> </tr> <tr> <td></td> <td>If there is a set of two or more Observations matched by <code>a</code>, the most recent Observation timestamp contained within that set <strong>MUST NOT</strong> be equal to or later than the delta of the earliest Observation timestamp within the set plus the specified time window.</td> </tr> <tr> <td></td> <td>Example: {<code>[file:hashes.&quot;SHA-256&quot;:'SHA-256' = '13987239847...']</code> AND [win-registry-key:key = 'hkey']) WITHIN 120 SECONDS}</td> </tr> </tbody> </table> The above Pattern Expression looks for a file hash and a registry key that were observed within 120 seconds of each other. The parentheses are needed to apply the WITHIN Qualifier to both Observation Expressions. \[ a \text{ START } x \text{ STOP } y \] \( a \) MUST be an Observation Expression or a preceding Qualifier. All Observations that match \( a \) MUST have an observation time \( \geq x \) and \( < y \). \( x \) and \( y \) MUST be a timestamp as defined in section 2.10 of STIX™ Version 2.0. Part 1: STIX Core Concepts. 4.1.2 Observation Operators Two or more Observation Expressions MAY be combined using an Observation Operator in order to further constrain the set of Observations that match against the Pattern Expression. <table> <thead> <tr> <th>Observation Operators</th> <th>Description</th> <th>Associativity</th> </tr> </thead> <tbody> <tr> <td>[ a ] <strong>AND</strong> [ b ]</td> <td>( a ) and ( b ) MUST both be Observation Expressions and MUST both evaluate to true on different Observations.</td> <td>Left to right</td> </tr> <tr> <td>[ a ] <strong>OR</strong> [ b ]</td> <td>( a ) and ( b ) MUST both be Observation Expressions and one of ( a ) or ( b ) MUST evaluate to true on different Observations.</td> <td>Left to right</td> </tr> <tr> <td>[ a ] <strong>FOLLOWEDBY</strong> [ b ]</td> <td>( a ) and ( b ) MUST both be Observation Expressions. Both ( a ) and ( b ) MUST both evaluate to true, where the observation timestamp associated with ( b ) is greater than or equal to the observation timestamp associated with ( a ) and MUST evaluate to true on different Observations.</td> <td>Left to right</td> </tr> </tbody> </table> For example, consider the following Pattern Expression: \[ [ a = 'b' ] \text{ FOLLOWEDBY } [ c = 'd' ] \text{ REPEATS 5 TIMES} \] The preceding expression says to match an Observation with \( a \) equal to 'b' that precedes 5 occurrences of Observations that have \( c \) equal to 'd', for a total of 6 Observations matched. This interpretation is due to qualifiers not being greedy, and is equivalent to \([ a = 'b' ] \text{ FOLLOWEDBY } ([ c = 'd' ] \text{ REPEATS 5 TIMES})\). Alternatively, using parenthesis to group the initial portion, we get the following example: \(([ a = 'b' ] \text{ FOLLOWEDBY } [ c = 'd' ]) \text{ REPEATS 5 TIMES}\) The preceding expression will match 5 pairs of Observations where \( a \) equals 'b' followed by an Observation where \( c \) is equal to 'd', for a total of 10 Observations matched. 4.1.3 Operator Precedence Operator associativity and precedence may be overridden by the use of parentheses. Unless otherwise specified, operator associativity (including for parentheses) is left-to-right. Precedence in the below table is from highest to lowest. <table> <thead> <tr> <th>Operators</th> <th>Associativity</th> <th>Valid Scope</th> </tr> </thead> <tbody> <tr> <td>()</td> <td>left to right</td> <td>Observation Expression or Pattern Expression, Observation Expression and Qualifier</td> </tr> <tr> <td>AND</td> <td>left to right</td> <td>Observation Expression, Pattern Expression</td> </tr> <tr> <td>OR</td> <td>left to right</td> <td>Observation Expression, Pattern Expression</td> </tr> <tr> <td>FOLLOWEDBY</td> <td>left to right</td> <td>Pattern Expression</td> </tr> </tbody> </table> 4.2 Comparison Expression Comparison Expressions are the most basic components of STIX Patterning, comprising an Object Path and a constant joined by a Comparison Operator. Each Comparison Expression is a singleton, and so they are evaluated from left to right. A Boolean Operator joins two Comparison Expressions together. In the following table, $a$ or $b$ is either a Comparison Expression or a composite expression (which may be composed recursively) consisting of two or more Comparison Expressions joined with Boolean Operators and enclosed by parentheses. <table> <thead> <tr> <th>Boolean Operator</th> <th>Description</th> <th>Associativity</th> </tr> </thead> <tbody> <tr> <td>$a \text{ AND } b$</td> <td>$a$ and $b$ MUST both be Comparison Expressions or a composite expression (which may be composed recursively) consisting of two or more Comparison Expressions joined with Boolean Operators and enclosed by parentheses. $a$ and $b$ MUST both evaluate to true on the same Observation.</td> <td>Left to right</td> </tr> <tr> <td>$a \text{ OR } b$</td> <td>$a$ and $b$ MUST both be Comparison Expressions or a composite expression (which may be composed recursively) consisting of two or more Comparison Expressions joined with Boolean Operators and enclosed by parentheses. Either $a$ or $b$ MUST evaluate to true.</td> <td>Left to right</td> </tr> </tbody> </table> ### 4.2.1 Comparison Operators The table below describes the available Comparison Operators for use in Comparison Expressions; in the table, *a* **MUST** be an Object Path and *b* **MUST** be a constant. If the arguments to the Comparison Operators are of incompatible types (e.g., the Object Path is an integer and the constant is a string), the results are false; the sole exception is the `!=` operator in which case the result is true. Some STIX Patterning constants and Cyber Observable data types may be comparable in a Comparison Expression. For example, the *hex* and *binary* types both represent binary data, and their representative binary data is that which must be compared for equality. See section 2.1 for type compatibility between STIX Patterning and Cyber Observable types. A Comparison Operator **MAY** be preceded by the modifier **NOT**, in which case the resultant Comparison Expression is logically negated. <table> <thead> <tr> <th>Comparison Operator</th> <th>Description</th> <th>Example</th> </tr> </thead> <tbody> <tr> <td><code>a = b</code></td> <td><em>a</em> and <em>b</em> <strong>MUST</strong> be equal (transitive), where <em>a</em> <strong>MUST</strong> be an Object Path and <em>b</em> <strong>MUST</strong> be a constant of the same data type as the Object property specified by <em>a</em>.</td> <td><code>file:name = 'foo.dll'</code></td> </tr> <tr> <td><code>a ! = b</code></td> <td><em>a</em> and <em>b</em> <strong>MUST NOT</strong> be equal (transitive), where <em>a</em> <strong>MUST</strong> be an Object Path and <em>b</em> <strong>MUST</strong> be a constant of the same data type as the Object property specified by <em>a</em>.</td> <td><code>file:size != 4112</code></td> </tr> <tr> <td><code>a &gt; b</code></td> <td><em>a</em> is numerically or lexically greater than <em>b</em>, where <em>a</em> <strong>MUST</strong> be an Object Path and <em>b</em> <strong>MUST</strong> be a constant of the same data type as the Object property specified by <em>a</em>.</td> <td><code>file:size &gt; 256</code></td> </tr> <tr> <td><code>a &lt; b</code></td> <td><em>a</em> is numerically or lexically less than <em>b</em>, where <em>a</em> <strong>MUST</strong> be an Object Path and <em>b</em> <strong>MUST</strong> be a constant of the same data type as the Object property specified by <em>a</em>.</td> <td><code>file:size &lt; 1024</code></td> </tr> <tr> <td><code>a &lt;= b</code></td> <td><em>a</em> is numerically or lexically less than or equal to <em>b</em>, where <em>a</em> <strong>MUST</strong> be an Object Path and <em>b</em> <strong>MUST</strong> be a constant of the same data type as the Object property specified by <em>a</em>.</td> <td><code>file:size &lt;= 25145</code></td> </tr> <tr> <td><code>a &gt;= b</code></td> <td><em>a</em> is numerically or lexically greater than or equal to <em>b</em>, where <em>a</em> <strong>MUST</strong> be an Object Path and <em>b</em> <strong>MUST</strong> be a constant of the same data type as the Object property specified by <em>a</em>.</td> <td><code>file:size &gt;= 33312</code></td> </tr> <tr> <td><code>a IN (x,y,...)</code></td> <td><em>a</em> <strong>MUST</strong> be an Object Path and <strong>MUST</strong> evaluate to one of the values enumerated in the set of <em>x</em>,<em>y</em>,... (transitive). The set values in <em>b</em> <strong>MUST</strong> be constants of homogenous data type and <strong>MUST</strong> be valid data types for the Object Property specified by <em>a</em>. The return value is true if <em>a</em> is equal to one of the values in the list. If <em>a</em> is not equal to any of the items in the list, then the Comparison Expression evaluates to false.</td> <td><code>process:name IN ('proccy', 'proximus', 'badproc')</code></td> </tr> </tbody> </table> ### a LIKE b $a$ MUST be an Object Path and MUST match the pattern specified in $b$ where any '%\' is 0 or more characters and '_' is any one character. This operator is based upon the SQL LIKE clause and makes use of the same wildcards. The string constant $b$ MUST be NFC normalized [Davis] prior to evaluation. **Example** ```plaintext directory:path LIKE 'C:\Windows\%\foo' ``` ### a MATCHES b $a$ MUST be an Object Path and MUST be matched by the pattern specified in $b$, where $b$ is a string constant containing a PCRE compliant regular expression. $a$ MUST be NFC normalized [Davis] before comparison if the property is of string type. Regular expressions MUST be conformant to the syntax defined by the Perl-compatible Regular Expression (PCRE) library [http://www.pcre.org/original/doc/html/pcrepattern.html](http://www.pcre.org/original/doc/html/pcrepattern.html). The search function MUST be used. The DOTALL option MUST be specified. The standard beginning and end anchors may be used in the pattern to obtain match behavior. In the case that the property is binary (e.g., the property name ends in _bin or _hex), then the UNICODE flag MUST NOT be specified. **Example** ```plaintext directory:path MATCHES '^C:\Windows\w+$' ``` <table> <thead> <tr> <th>Set Operator</th> <th>Description</th> <th>Example</th> </tr> </thead> <tbody> <tr> <td><strong>a ISSUBSET b</strong></td> <td>When $a$ is a set that is wholly contained by the set $b$, the Comparison Expression evaluates to true. $a$ MUST be an Object Path referring to the value property of an Object of type ipv4-addr or ipv6-addr. $b$ MUST be a valid string representation of the corresponding Object type (as defined in STIX™ Version 2.0. Part 4: Cyber Observable Objects). For example, if ipv4-addr:value was 198.51.100.0/27, ISSUBSET '198.51.100.0/24' would evaluate to true. In the case that both $a$ and $b$ evaluate to an identical single IP address or an identical IP subnet, the Comparison Expression evaluates to true.</td> <td>ipv4-addr:value ISSUBSET '198.51.100.0/24'</td> </tr> <tr> <td><strong>a ISSUPERSET b</strong></td> <td>When $a$ is a set that wholly contains the set specified by $b$, the Comparison Expression evaluates to true. $a$ MUST be an Object Path referring either an ipv4-addr or ipv6-addr Object.</td> <td>ipv4-addr:value ISSUPERSET '198.51.100.0/24'</td> </tr> </tbody> </table> 4.2.2 String Comparison For simple string operators, i.e., "\"\"", "\"\"", "\"\"", "\"\"", "\"\"", and "\"\"", as collation languages and methods are unspecified, a simple code point (binary) comparison **MUST** be used. If one string is longer than the other, but otherwise equal, the longer string is greater than, but not equal to, the shorter string. Unicode normalization **MUST NOT** be performed on the string. This means that combining marks [Davis] are sorted by their code point, not the NFC normalized value. E.g., 'o' U+006f < 'oz' U+006f U+007a < 'ò' U+006f U+0300 < 'z' U+007a < 'ò' U+00f2. Although Unicode recommends normalizing strings for comparisons, the use of combining marks may be significant, and normalizing by default would remove this information. NFC normalization is, however, required for other Comparison Operators, e.g., LIKE and MATCHES. 4.2.3 Binary Type Comparison When the value of two binary object properties are compared, they are compared as unsigned octets. That is, 00 is less than ff. If one value is longer than the other, but they are otherwise equal, the longer value is considered greater than, but not equal to, the shorter value. 4.2.4 Native Format Comparison The Cyber Observable Object's value **MUST** be in its native format when doing the comparison. For example, Cyber Observable Object properties that use the binary type (defined in section 2.2 of STIX™ Version 2.0. Part 3: Cyber Observable Core Concepts) must have their value decoded into its constituent bytes prior to comparison. This also means that Object Properties which use the hex type must be decoded into raw octets prior to being evaluated. In cases where a binary Cyber Observable Object property (i.e., one ending with _bin or _hex) is evaluated against a string constant, the string constant **MUST** be converted into a binary constant when all of the constituent string code points are less than U+0100. If this conversion is not possible, the comparison **MUST** evaluate to false, unless the comparison operator is !=, in which case it **MUST** evaluate to true. For example given the following object, where the payload_bin property is of binary type: ```json { "0":{ "type": "artifact", "mime_type": "application/octet-stream", "payload_bin": "dGhpcyBpcyBhIHRlc3Q= } } ``` The pattern "artifact:payload_bin = 'dGhpcyBpcyBhIHRlc3Q='" would evaluate to false, while the following patterns would all evaluate to true: "artifact:payload_bin = 'this is a test'", "artifact:payload_bin = b'dGhpcyBpcyBhIHRlc3Q='", and "artifact:payload_bin = h'7468697320697320612074657374'". 5 Object Path Syntax Defined below is the syntax for addressing properties of Cyber Observable Objects within a STIX Pattern. The following notation is used throughout the definitions below: <table> <thead> <tr> <th>Notation</th> <th>Definition</th> </tr> </thead> <tbody> <tr> <td><code>&lt;object-type&gt;</code></td> <td>The type of Cyber Observable Object to match against. This <strong>MUST</strong> be the value of the <code>type</code> field specified for a given Cyber Observable Object in an Observation.</td> </tr> <tr> <td><code>&lt;property_name&gt;</code></td> <td>The name of a Cyber Observable Object property to match against. This <strong>MUST</strong> be a valid property name as specified in the definition of the Cyber Observable Object type referenced by the <code>&lt;object-type&gt;</code> notation.</td> </tr> </tbody> </table> If the `<property_name>` contains a dash (`-` U+002d) or a dot (full stop (`.` U+002e), the `<property_name>` **MUST** be enclosed in double quotes (apostrophes (" U+0027). Properties that are nested (i.e., are children of other properties in a Cyber Observable Object) **MUST** be specified using the syntax `<property_name>.<property_name>`, where the `<property_name>` preceding the `.` is the name of the parent property and the one following is the name of the child property. If the property name is a reference to another Cyber Observable Object, the referenced Object **MUST** be dereferenced, so that its properties function as if they are nested in the Object that it is referenced by. For example, if the `src_ref` property of the Network Traffic Object references an IPv4 Address Object, the value of this IPv4 address would be specified by `network-traffic:src_ref.value`. 5.1 Basic Object Properties Any non-`dictionary` and non-`list` property that is directly specified on a Cyber Observable Object. **Syntax** ```plaintext``` <object-type>:<property_name> ``` **Example** `file:size` 5.2 List Object Properties Any property on a Cyber Observable Object that uses the `list` data type. Syntax <object-type>:<property_name>[list_index].<property_name> Where the first <property_name> MUST be the name of an Object property of type list and [list_index] MUST be one of the following: - An integer in the range of 0..N-1, where N is the length of the list. If list_index is out of range, the result of any operation is false. - The literal '*' indicates that if any of the items contained within a list matches against the Comparison Expression, the Comparison Expression evaluates to true. Example file:extensions.windows-pebinary.sections[*].entropy > 7.0 The above example will return true if any PE section has an entropy property whose value is greater than 7.0. 5.3 Dictionary Object Properties Any property on a Cyber Observable Object that uses the dictionary data type. Syntax <object-type>:<property_name>.<key_name> Where <property_name> MUST be the name of an Object property of type dictionary and <key_name> MUST be the name of key in the dictionary. Examples file:hashes.MD5.ssdeep file:extensions.raster-image.image_height 5.4 Object Reference Properties Any property on a Cyber Observable Object that uses the object-ref data type, either as a singleton or as a list (i.e., list of type object-ref). Syntax <object-type>:<property_name>.<dereferenced_object_property> Where <property_name> MUST be the name of an Object property of type object-ref and <dereferenced_object_property> MUST be the name of a valid property of the dereferenced Object (i.e., the Object in an Observation that is referenced via <property_name>). For cases where <property_name> is a list of type object-ref, the corresponding syntax applies: Accordingly, the same semantics for list indices as defined in section 5.2 apply in this case. **Examples** ```plaintext e-mail-message:from_ref.value = 'mary@example.com' directory:containsRefs[*].name = 'foobar.dll' ``` 6 Examples Note: the examples below are NOT JSON encoded. This means that some characters, like double quotes, are not escaped, though they will be when encoded in a JSON string. Matching a File with a SHA-256 hash ``` [file:hashes."SHA-256", 'SHA-256' = 'aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f'] ``` Matching an Email Message with a particular From Email Address and Attachment File Name Using a Regular Expression ``` [email-message:from_ref.value MATCHES '.+\@example\.com$' AND email-message:body_multipart[*].body_raw_ref.name MATCHES '^Final Report.+\.exe$'] ``` Matching a File with a SHA-256 hash and a PDF MIME type ``` [file:hashes."SHA-256", 'SHA-256' = 'aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f' AND file:mime_type = 'application/x-pdf'] ``` Matching a File with SHA-256 or a MD5 hash (e.g., for the case of two different end point tools generating either an MD5 or a SHA-256), and a different File that has a different SHA-256 hash, against two different Observations ``` [file:hashes."SHA-256", 'SHA-256' = 'bf07a7fbb825fc0aae7bf4a1177b2b31fcf8a3feeaf7092761e18c859ee52a9c' OR file:hashes.MD5 = 'cead3f77f66da6ec00f57d76c9a6879f' ] AND [file:hashes."SHA-256", 'SHA-256' = 'aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f'] ``` Matching a File with a MD5 hash, followed by (temporally) a Registry Key Object that matches a value, within 5 minutes ``` [['(file:hashes.MD5 = '79054025255fb1a26e4bc422aef54eb4') FOLLOWEDBY [win-registry-key:key = 'HKEY_LOCAL_MACHINE\foo\bar']]] WITHIN 300 SECONDS ``` Matching three different, but specific Unix User Accounts ``` [user-account:account_type = 'unix' AND user-account:user_id = '1007' AND user-account:account_login = 'Peter'] AND [user-account:account_type = 'unix' AND user-account:user_id = '1008' AND user-account:account_login = 'Paul'] AND [user-account:account_type = 'unix' AND user-account:user_id = '1009' AND user-account:account_login = 'Mary'] ``` Matching an Artifact Object PCAP payload header ``` [artifact:mime_type = 'application/vnd.tcpdump.pcap' AND artifact:payload_bin MATCHES '\\xd4\\xc3\\xb2\\xa1\\x00\\x84\\x00'] ``` Matching a File Object with a Windows file path ``` [file:name = 'foo.dll' AND file:parent_directory_ref.path = 'C:\\Windows\\System32'] ``` Matching on a Windows PE File with high section entropy [file:extensions.windows-pebinary-ext.sections[*].entropy > 7.0] Matching on a mismatch between a File Object magic number and mime type [file:mime_type = 'image/bmp' AND file:magic_number_hex = h'ffd8'] Matching on Network Traffic with a particular destination [network-traffic:dst_ref.type = 'ipv4-addr' AND network-traffic:dst_ref.value = '203.0.113.33/32'] Matching on Malware Beaconing to a Domain Name [network-traffic:dst_ref.type = 'domain-name' AND network-traffic:dst_ref.value = 'example.com'] REPEATS 5 TIMES WITHIN 1800 SECONDS Matching on a Domain Name with IPv4 Resolution [domain-name:value = 'www.528.info' AND domain-name:resolves_to_refs[*].value = '198.51.100.1/32'] Matching on a URL [url:value = 'http://example.com/foo' OR url:value = 'http://example.com/bar'] Matching on an X509 Certificate Matching on a Windows Registry Key [windows-registry-key:key = 'HKEY_CURRENT_USER\Software\CryptoLocker\Files' OR windows-registry-key:key = 'HKEY_CURRENT_USER\Software\Microsoft\CurrentVersion\Run\CryptoLocker_0388'] Matching on a File with a set of properties Matching on an Email Message with specific Sender and Subject [email-message:sender_ref.value = 'jdoe@example.com' AND email-message:subject = 'Conference Info'] Matching on a Custom USB Device [x-usb-device:usbdrive.serial_number = '57583331433343231313937'] Matching on Two Processes Launched with a Specific Set of Command Line Arguments Within a Certain Time Window [process:command_line MATCHES '^.+>add GlobalSign.cer -c -s -r localMachine Root$'] FOLLOWEDBY [process:command_line MATCHES'^.+>add GlobalSign.cer -c -s -r localMachineTrustedPublisher$'] WITHIN 300 SECONDS Matching on a Network Traffic IP that is part of a particular Subnet Matching on several different combinations of Malware Artifacts. Note the following pattern requires that both a file and registry key exist, or that one of two processes exist. ``` ([file:name = 'foo.dll'] AND [win-registry-key:key = 'HKEY_LOCAL_MACHINE\foo\bar']) OR [process:name = 'fooproc' OR process:name = 'procfoo'] ``` 7 Conformance Implementers of the STIX Patterning language are not required to support the full capabilities provided by the language. Rather, implementers are strongly encouraged to support as much of STIX Patterning as feasible, given the capabilities of their products, but only required to support the minimum conformance level (defined below) necessary for their particular use cases. For example, the vendor of a network intrusion detection system (NIDS) that looks for malicious network traffic may only need to implement the Comparison Operators and support basic Observation Expressions to explicitly match against network traffic and IP addresses. While the STIX Patterning language specification is tightly coupled with the STIX Cyber Observable object data models, it is understood that in many (or even most) implementations STIX Patterns will be used as an abstraction layer for transcoding into other proprietary query formats. STIX Patterns may be evaluated directly against a corpus of STIX Observed Data instances but they may also, for example, be translated into some query syntax for a packet inspection device. In this second case, the STIX Patterns are in fact evaluated in the context of data passing on the wire, not in the form of STIX Cyber Observables. The STIX Patterning language’s Observation Operators allow for the creation of patterns that explicitly match across multiple Observations; however, the language purposefully does not specify anything about the source of the underlying data for each Observation. For example, depending on a particular patterning implementation, the data for a pattern that matches on network traffic could come from an endpoint or from a NIDS. It is incumbent upon implementers to ascertain the appropriate data sources (where applicable) for each Observation within a given pattern. 7.1 Pattern Producer Software that creates STIX patterns is known as a “Pattern Producer”. Such software MUST support the creation of patterns that conform to all normative statements and formatting rules in this document. Pattern Producers MUST specify their conformance in terms of the conformance levels defined in section 7.3. 7.2 Pattern Consumer Software that consumes STIX patterns is known as a “Pattern Consumer”. Such software MUST support the consumption of patterns that conform to all normative statements and formatting rules in this document. Pattern Consumers MUST specify their conformance in terms of the conformance levels defined in section 7.3. 7.3 Conformance Levels 7.3.1 Level 1: Basic Conformance Software that conforms to the minimum required aspects of the patterning specification, is known as a “Level 1 STIX Patterning Implementation”. Such software MUST support the following features by conforming to all normative statements and behaviors in the referenced sections: - Single Observation Expressions (omitting Qualifiers), as described in section 4.1 - All Comparison Operators, as described in section 4.2.1 This level of conformance is intended primarily for software that is deployed at endpoints or network boundaries and which is architecturally unable to maintain state, as would be required in order to support Qualifiers such as WITHIN. 7.3.2 Level 2: Basic Conformance plus Observation Operators Software that supports the minimum required aspects of the patterning specification but can operate on multiple Observations, is known as a "Level 2 STIX Patterning Implementation". Such software MUST support the following features by conforming to all normative statements and behaviors in the referenced sections: - Single and Compound Observation Expressions (omitting Qualifiers) as described in section 4.1 - All Comparison Operators, as described in section 4.2.1 - The AND Observation Operator, as described in section 4.1.2 - The OR Observation Operator, as described in section 4.1.2 This level of conformance is intended primarily for software such as HIDS that can detect patterns across separate Observations but may not support temporal-based patterning. 7.3.3 Level 3: Full Conformance Software that is fully conformant with all of the capabilities of the patterning specification is known as a "Level 3 STIX Patterning Implementation". Such software MUST support the following features by conforming to all normative statements and behaviors in the referenced sections: - Section 2. Definitions - Section 3. STIX Patterns - Section 4. Pattern Expressions - Section 5. Object Path Syntax This level of conformance is intended primarily for software such as SIEMs that support temporal-based patterning and can also aggregate and detect patterns across multiple and disparate sources of Observations. Appendix A. Glossary CAPEC - Common Attack Pattern Enumeration and Classification Consumer - Any entity that receives STIX content CTI - Cyber Threat Intelligence Embedded Relationship - A link (an "edge" in a graph) between one STIX Object and another represented as a property on one object containing the ID of another object Entity - Anything that has a separately identifiable existence (e.g., organization, person, group, etc.) IEP - FIRST (Forum of Incident Response and Security Teams) Information Exchange Policy Instance - A single occurrence of a STIX object version MTI - Mandatory To Implement MVP - Minimally Viable Product Object Creator - The entity that created or updated a STIX object (see section 3.3 of STIX™ Version 2.0, Part 1: STIX Core Concepts). Object Representation - An instance of an object version that is serialized as STIX Producer - Any entity that distributes STIX content, including object creators as well as those passing along existing content SDO - STIX Domain Object (a "node" in a graph) SRO - STIX Relationship Object (one mechanism to represent an "edge" in a graph) STIX - Structured Threat Information Expression STIX Content - STIX documents, including STIX Objects, STIX Objects grouped as bundles, etc. STIX Object - A STIX Domain Object (SDO) or STIX Relationship Object (SRO) STIX Relationship - A link (an "edge" in a graph) between two STIX Objects represented by either an SRO or an embedded relationship TAXII - An application layer protocol for the communication of cyber threat information TLP - Traffic Light Protocol TTP - Tactic, technique, or procedure; behaviors and resources that attackers use to carry out their attacks Appendix B. Acknowledgments The contributions of the OASIS Cyber Threat Intelligence (CTI) Technical Committee members, enumerated in STIX™ Version 2.0. Part 1: STIX Core Concepts, are gratefully acknowledged. ## Appendix C. Revision History <table> <thead> <tr> <th>Revision</th> <th>Date</th> <th>Editor</th> <th>Changes Made</th> </tr> </thead> <tbody> <tr> <td>02</td> <td>2017-04-24</td> <td>Bret Jordan, John Wunder, Rich Piazza, Ivan Kirillov, Trey Darley</td> <td>Changes made from first public review</td> </tr> </tbody> </table>
{"Source-Url": "http://docs.oasis-open.org/cti/stix/v2.0/csprd02/part5-stix-patterning/stix-v2.0-csprd02-part5-stix-patterning-DIFF.pdf", "len_cl100k_base": 16181, "olmocr-version": "0.1.53", "pdf-total-pages": 34, "total-fallback-pages": 0, "total-input-tokens": 93771, "total-output-tokens": 18519, "length": "2e13", "weborganizer": {"__label__adult": 0.0009145736694335938, "__label__art_design": 0.0012569427490234375, "__label__crime_law": 0.015838623046875, "__label__education_jobs": 0.0026378631591796875, "__label__entertainment": 0.0003609657287597656, "__label__fashion_beauty": 0.0004019737243652344, "__label__finance_business": 0.001544952392578125, "__label__food_dining": 0.0004506111145019531, "__label__games": 0.0030040740966796875, "__label__hardware": 0.005084991455078125, "__label__health": 0.0006871223449707031, "__label__history": 0.0009665489196777344, "__label__home_hobbies": 0.000316619873046875, "__label__industrial": 0.001983642578125, "__label__literature": 0.0009026527404785156, "__label__politics": 0.0014801025390625, "__label__religion": 0.0009260177612304688, "__label__science_tech": 0.23779296875, "__label__social_life": 0.00021469593048095703, "__label__software": 0.110107421875, "__label__software_dev": 0.61181640625, "__label__sports_fitness": 0.0003845691680908203, "__label__transportation": 0.0006031990051269531, "__label__travel": 0.00028252601623535156}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 72097, 0.03048]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 72097, 0.47247]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 72097, 0.7862]], "google_gemma-3-12b-it_contains_pii": [[0, 1967, false], [1967, 6593, null], [6593, 11066, null], [11066, 12059, null], [12059, 17106, null], [17106, 20547, null], [20547, 22662, null], [22662, 25037, null], [25037, 25057, null], [25057, 27528, null], [27528, 29398, null], [29398, 31487, null], [31487, 34041, null], [34041, 36861, null], [36861, 37110, null], [37110, 40305, null], [40305, 43252, null], [43252, 45639, null], [45639, 48138, null], [48138, 51082, null], [51082, 53352, null], [53352, 55689, null], [55689, 55987, null], [55987, 58317, null], [58317, 59985, null], [59985, 60209, null], [60209, 62592, null], [62592, 64550, null], [64550, 64879, null], [64879, 67882, null], [67882, 69602, null], [69602, 71288, null], [71288, 71499, null], [71499, 72097, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1967, true], [1967, 6593, null], [6593, 11066, null], [11066, 12059, null], [12059, 17106, null], [17106, 20547, null], [20547, 22662, null], [22662, 25037, null], [25037, 25057, null], [25057, 27528, null], [27528, 29398, null], [29398, 31487, null], [31487, 34041, null], [34041, 36861, null], [36861, 37110, null], [37110, 40305, null], [40305, 43252, null], [43252, 45639, null], [45639, 48138, null], [48138, 51082, null], [51082, 53352, null], [53352, 55689, null], [55689, 55987, null], [55987, 58317, null], [58317, 59985, null], [59985, 60209, null], [60209, 62592, null], [62592, 64550, null], [64550, 64879, null], [64879, 67882, null], [67882, 69602, null], [69602, 71288, null], [71288, 71499, null], [71499, 72097, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 72097, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 72097, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 72097, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 72097, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 72097, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 72097, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 72097, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 72097, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 72097, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 72097, null]], "pdf_page_numbers": [[0, 1967, 1], [1967, 6593, 2], [6593, 11066, 3], [11066, 12059, 4], [12059, 17106, 5], [17106, 20547, 6], [20547, 22662, 7], [22662, 25037, 8], [25037, 25057, 9], [25057, 27528, 10], [27528, 29398, 11], [29398, 31487, 12], [31487, 34041, 13], [34041, 36861, 14], [36861, 37110, 15], [37110, 40305, 16], [40305, 43252, 17], [43252, 45639, 18], [45639, 48138, 19], [48138, 51082, 20], [51082, 53352, 21], [53352, 55689, 22], [55689, 55987, 23], [55987, 58317, 24], [58317, 59985, 25], [59985, 60209, 26], [60209, 62592, 27], [62592, 64550, 28], [64550, 64879, 29], [64879, 67882, 30], [67882, 69602, 31], [69602, 71288, 32], [71288, 71499, 33], [71499, 72097, 34]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 72097, 0.12524]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
0a2d35f4eef8588f5fc133176bcf8c43125d7841
Managing Software Requirements Changes through Change Specification and Classification Shalinka Jayatilleke, Richard Lai, and Karl Reed Department of Computer Science and Information Technology La Trobe University, Victoria. 3086, Australia {s.jayatilleke, R.Lai, k.reed}@latrobe.edu.au Abstract: Software requirements changes are often inevitable due to the changing nature of running a business and operating the Information Technology (IT) system which supports the business. As such, managing software requirements changes is an important part of software development. Past research has shown that failing to manage software requirements changes effectively is a main contributor to project failure. One of the difficulties in managing requirements changes is the lack of effective methods for communicating changes from the business to the IT professionals. In this paper, we present an approach to managing requirements change by improving the change communication and elicitation through a method of change specification and a method of classification. Change specification provides a way such that communication ambiguities can be avoided between business and IT staff. The change classification mechanism identifies the type of the changes to be made and preliminary identification of the actions to be taken. We illustrate the usefulness of the methods by applying them to a case study of course management system. Keywords: Requirements change, change specification, change classification, ontology, terminology. 1. Introduction The inevitable development of globalization, service-oriented environments and continuous technological advances compel organizations to change their strategies and business processes to meet customer demand. In addition, there is the impact of software evolution and maintenance. Although change is an evident factor in today’s highly competitive business environment, many organizations find themselves at the losing end of this game. Volatile nature of business requirements usually increases the cost of development [1-6] and also poses a threat to the project schedule [3]. Changing requirements are considered one of the main contributors to project failure [7-9]. The real problem is not the changing nature of requirements, but the lack of understanding of this volatility. Change management, therefore, is a critical task for organizations. A preliminary version of this paper was presented at the 2013 Australian Software Engineering Conference Requirements engineering consists of a set of core activities that are in reality interleaved and iterative [10]. Requirements change is part of this requirements engineering process and it is not a standalone activity but consists of several core activities that can be described as a process. This process begins with communicating the requirements change (change request). Successfully completing this step will result in the elicitation of the correct goals in relation to the changes (change goals), which is the next step in the process. Understanding the change goals leads to the proper execution of the third step, which is representing the change in the system design. The second and third steps effectively assist the analysis of the requirements change to assess its appropriateness and whether it should be accepted. The final step in the process is based on the results of the analysis. Depending on the outcome, a change can be accepted or rejected. Therefore, the final outcome of the change request depends heavily on the first step. This process is iterative, usually due to the inability of management to agree to the change request and due to insufficient information. It is further hindered due to poor change communication, misinterpretation of change goals, incorrect representation of changes in the system design, discrepancies in analysing the changes, and inaccurate decision making in relation to the requested changes. One of the key reasons for difficulty in managing change occurs at its initiation. Effective interpretation and communication change, from the customer to the development level has proved to be a challenging task [11-14]. Some literature suggests that this is due to the lack of a formal process specifying change [11, 14]. The specification method used by change originators should be understood by both business and IT personnel since it is the bridge between the change originators (users, customers, etc.) and the change implementers (system analysts, designers, developers, etc.) [15-17]. Therefore, being able to specify and understand the requirements change should make the process of incorporating the change into the existing design or system more seamless. In this paper, we present an approach to managing requirements change by improving the change communication and elicitation through a method of change specification and a method of classification. Change specification provides a way such that communication ambiguities can be avoided between business and IT staff. This is the first step towards better and effective management of requirements change in rapidly changing business environments. The change specification process is incomplete without classifying the changes. The change classification mechanism identifies the type of the changes to be made and preliminary identification of the actions to be taken. To aim readers to have a better understanding of the change specification and classification methods, we use a simple mail order system as a running example. Finally, we illustrate their usefulness by applying them to a case study of course management system. A preliminary version of this paper was presented at the 2013 Australian Software Engineering Conference [18]. The following items are contained in this paper but not in [18]: (i) a discussion on the related work to give better understanding of our methods; (ii) a description of the overview of the methods; (iii) a justification of the use of Goal Question Metrics (GQM) and Resource Development Framework (RDF) approach; and (iv) to illustrate the usefulness of our methods, the results of applying them to a running example and a case study. 2. Overview of the Methods In this section, we present an overview of our approach to managing requirements changes through a method of change specification and a method of classification. Managing change begins with an understanding of what is involved in this phenomenon. But as previous studies have proven, there is no real consensus on the nature of change, rather there are disparate multifaceted views and approaches. We therefore see the need for a versatile, consolidated, solution that brings these together. Based on previous research work and also through industrial interviews described later, we were able to pinpoint the gap in change identification. There is an inadequacy in applying change identification in the practical context. Figure 1 using the IDF0 notation shows the broad layout of the methods aiming to overcome this limitation. Once a change is requested, the layout follows two steps: 1) Change specification 2) Change classification Fig. 1. Layout of overview of the methods Change specification denotes a way of specifying a change so that communication ambiguities can be avoided between business and IT staff. Once a requirement change has been initiated from the client side, this method will use the system design diagram as an input to map out the location of the change. In order to create the specification template we will use two established methods, i.e. Goal Question Metrics (GQM) [19] and Resource Description Framework (RDF) [20]. We will also use a set of additional questions to enable better identification when using the specification template output. The purpose of using GQM and RDF is to establish terminology and ontology (respectively) concepts in the specification method. The use of terminology will enable the specification template to have standardized terms whilst ontology will ensure a logical connection between the terms used in the specification template. The purpose of using both terminology and ontology is further discussed in section 3.2.1. The outcome of the specification template will be the identification of the location, purpose and focus of the change. GQM approach, which was developed by Basili and Weiss and expanded by Rombach [19], is the most widely known goal-focused approach for measurement in software. One of the reasons for its success is that it is adaptable to many different organizations (e.g. Philips, Siemens, NASA) [19]. Another reason for the success of GQM is that it aligns with organizational directions and goals. Rather than using a bottom-up method (generally problematic) [21], metrics are defined top-down. This way the measurements are linked to organizational goals [21-23]. This same concept can be applied in describing change. If the changes described are linked to goals, then understanding and application of such changes could be far more efficient [24]. Introduced by Tim Berners-Lee in 1998, RDF is an ontology language for making statements about resources [20]. It was designed for describing Web resources such as Web pages. However, RDF does not require that resources be retrievable on the Web. RDF resources may be physical objects, abstract concepts, in fact anything that has an identity. Thus, RDF defines a language for describing just about anything. Furthermore software modeling languages and methodologies can benefit from the integration with ontology languages such as RDF in various ways, e.g. by reducing language ambiguity, enabling validation and automated consistency checking [25]. Given the benefits of both GQM and RDF, it was deemed appropriate to use these methods for specifying requirements changes. With these being the general benefits of GQM and RDF, their specific purpose and use in the specification method are described in detail below. The change classification method uses the outcome of the specification template to expand on the type of change along with preliminary guidance for action to be taken in managing the change. The classification itself is based on the concepts of change taxonomy that was found in existing change management literature and refined using unstructured interviews of practitioners in the field of change management. The outcome of the change classification will provide software developers with a better understanding of what the change is and the preliminary guidance on how to incorporate the change into the existing system. We believe the combination of change specification and classification leads to a better realisation of changes requested. 2.1 A Running Example To aim readers to have a better understanding of the change specification and classification methods, we will use a simple mail order system for CDs and DVDs as a running example which is described below. Diskwiz is a company which sells CDs and DVDs by mail order. Customer orders are received by the sales team, which checks that customer details are completed properly on the order form (for example, delivery address and method of payment). If they are not, a member of the sales team contacts the customer to get the correct details. Once the correct details are confirmed, the sales team passes a copy of the order through to the warehouse team to pick and pack, and a copy to the finance team to raise an invoice. Finance raises an invoice and sends it to the customer within 48 hours of the order being received. When a member of the warehouse team receives the order, they check the real-time inventory system to make sure the discs ordered are in stock. If they are, they are collected from the shelves, packed and sent to the customer within 48 hours of the order being received, so that the customer receives the goods at the same time as the invoice. If the goods are not in stock, the order is held in a pending file in the warehouse until the stock is replenished, whereupon the order is filled. This process can be illustrated by the following system design diagram. The example consists of a scenario where the specification method is applied in specifying the change and the change classification method is used to identify change type and corresponding action. The scenario is as follows: The management is not satisfied with some parts of the process and point out that the following issue should be rectified: “It is identified, due to a design error, there is no communication between finance and the warehouse to confirm discs are in stock so that the order can be shipped. Therefore finance could be raising invoices when the order has not been sent.” 3. The Change Specification Method Figure 3 represents collaboration of the different entities of the change specification method. The change specification consists of three key elements: a system design diagram, a specification template and additional questions. The foundation of specification component is made up of GQM and RDF. The GQM-RDF combination is a result of amalgamating ontology and terminology which in this paper, we refer to as onto-terminology. A detailed description of the onto-terminological concept and the interaction of the three elements in specifying changes are explained in the following sections. We point out that in fact, or method is “system description technique agnostic”; and, could be used in any environment where a systematic system description methodology has been used, reducing the adoption costs. According to Figure 3, an important input is the use of system design diagrams. In this cases where the initiation of the change takes place on the business side. Therefore, the initial part of the change specification should be familiar to the business personnel involved. To achieve this, system design diagrams are used as part of the change specifying process where the notations and the language used are more business related. Any business analyst communicating a requirement change to the IT side should be capable of understanding and interpreting a system design diagram. ![Diagram of Change Specification Process] **Fig. 3. Layout of the change Specification** The successful application of the change specification calls for a few key assumptions. First, the specification of changes may take place at the operational level of the organization. We believe that as changes flow from an executive level (top) to the operational level (bottom), they become less abstract, making it easier to feed the change into the specification and classification methods. Second, in reality, for a system to be stable, the changes being made are proportionately small (5% – 10%) in comparison to the complete system [26]. On the other hand, if the change requires more than a 50% change to the system, it is usually implemented in a successive release of the current system. Finally, a design diagram (preferably the system design diagram) should be available for mapping the change to the system. ### 3.1 Specification Prerequisites Although there is a plethora of ways to describe change, most fall into ad-hoc methods of communication. In the authors’ view, a void exists which could be filled by a more effective and efficient template and a set of guidelines that can be used to communicate requirements change. Given the current trend of business being more service-oriented, the change specification should be a bridge between customer requirements and the final product [27]. The new specification template introduced in this paper will reflect this. The following two key properties are essential for a specification method to be both functional and constructive [27]. A primary objective for the specification method is user friendliness to ensure ease of adoption. It is important to recognize that the process of specifying either requirements or changes to requirements is a human activity process [27-29]. Therefore, the method used for such specifications should be human friendly [27]. The initial response to a new method is generally resistance and an unwillingness to use it [27, 30]. This is usually because the difficulty level of the new method is unknown to the users. Also, both businesses and IT stakeholders involved in the change management process tend to trust tried and tested methods of specifying change simply because there are no “surprises” in store. For these reasons, rather than inventing an entirely new method, we have opted to use a combination of existing methods which we believe has the most desirable qualities of a specification method and with which the users are familiar. This, in our view, will minimize the short-term productivity losses associated with learning new process, and also reduce the likelihood of opposition. The second property is the method style. Text-based specification methods are formed using either natural language or formal language [27]. Although easier to understand, the drawback in using natural language is that it may be interpreted in different ways, resulting in ambiguities. Whereas a mathematically influenced formal language may be ideal for a computer, it may not be human friendly. Therefore, it is important to find a balance in textual illustration. Also equally important is that both business and IT stakeholders involved in the process understand the specification method. To achieve this, we introduce a semi-formal method which is aided by system design diagrams. 3.2 Onto-terminology Framework The Purpose of Ontology and Terminology. The specification method introduced in this work is a means of semi-formal communication of requirements change. And for this method to be both informative and useful, it needs to satisfy several conditions. A specification method should take into consideration: standardised terms, the usage of the terms, connotative information and linguistic relationships as well as a logical and philosophical point of view of the standardised terms [31]. We point out that these features stem from two different concepts i.e. terminology and ontology. The relationship between terminologies and ontologies has been the subject of analysis by others, as we see from the following discussions. Terminology is a “set of designations belonging to one special language” [32]. The main purpose of using terminology in a specification method is to eliminate ambiguity and ensure the use of standard terms [31]. International standards state that the goal of terminology is to clarify and standardize concepts for communication between humans [32]. This is a crucial property of our proposals as this is a method of conveying changes in requirements from business personnel to IT personnel. However, terminology generally lacks computational representation as well as logic [33]. Of these, our concern with regard to change specification is logic. Logical accuracy will ensure that the action taken to implement the change is correct. Therefore terminology, on its own, cannot be considered for the semi-formal framework of the change specification method. Ontologies are similar to terminologies in that both the communication of concepts. According to Gruber [34], ontology describes a concept and its relationships in a way that can be manipulated logically. The way ontology defines a concept depends entirely on the formal language used for the communication of the concept. Ontology is not a terminology [31]. In fact, ontology lacks the standardized terms and linguistic relationships of a concept which are key features in terminology [31]. These features are imperative to change specification as they build the actual form of communication terms to be used in the specification. The conceptualization of the change specification method needs to be guided by both linguistic and logical principles. Given the strengths and weaknesses of terminology and ontology, the combination of these two concepts will provide a better framework for the specification. Onto-terminology, which results from this combination, formally defines the concept (ontology logic) as well as explains the term and its usage from a linguistic point of view (terminology). **Building the relationship between GQM and RDF.** To ensure the correct combination of logic and terminology, we have selected two well-known methods where one represents terminology and the other represents ontology. A generalization of GQM is used as the linguistic function of the specification method representing terminology. It is important to note that the abstraction of GQM relates to the goal specification and not to the questions or the metrics. The purpose of using GQM is that it enables the extraction of specific terms that define the requirements change. Since these terms have been successfully utilized to extract business goals [21, 22], we found it’s use satisfactory in change specification. The logical connections for the terms are sourced from RDF representing the ontology component specification. However, it can also be used to link information stored in any information source that can be ontologically defined [33]. Three terms are extracted from the goal specification of GQM that can best describe a requirement change; Object, Purpose and Focus (of change). The meanings of these three elements have been adjusted for the purpose of describing change. The Object needs to be changed due to the Purpose using the Focus. The terms extracted from RDF are Object, Attribute and Value, which is referred to as the RDF triplet [33]. The logical relationship of the RDF triplet can be stated as Object O has an Attribute A with a Value V (Professor; Reads; a Book). The rationale behind the correspondence between RDF triplet and to the GQM terms is due to the similarity and the meanings of the terms, which is described in Table 1. <table> <thead> <tr> <th>RDF term</th> <th>GQM term</th> <th>Correspondence</th> <th>Rationale</th> </tr> </thead> <tbody> <tr> <td>Object</td> <td>Object</td> <td>One-to-one</td> <td>Same concept</td> </tr> <tr> <td>Attribute</td> <td>Purpose</td> <td>One-to-one</td> <td>Both terms are activities. Purpose is an activity that is generated due to various business requirements.</td> </tr> <tr> <td>Value</td> <td>Focus</td> <td>One-to-one</td> <td>Value of RDF creates the significance for Attribute (of RDF). Focus of GQM creates the significance for Object (of GQM) by activating the term Purpose of GQM.</td> </tr> </tbody> </table> GQM terms alone could have been used if the three terms have a logical connection; and we have explained above as to why it is important to have this logical connection in a specification language. The main reason for using RDF is hence to create the logical relationship between GQM terms. Figure 4 represents the relationship mapping between RDF and GQM. As such, the logical relationships between GQM terms can be stated as Object O needs Purpose P by using Focus F. Given the logical connection established, any change specified (regardless of the application of the system) using the GQM terms will satisfy the requirements of a semi-formal method of communication as stipulated above (see 4.2.1). From now, we shall use these three terms in the specification method. The framework presented in Figure 5 is based on the above relationship and is the foundation of the specification method. The three elements OBJECT, PURPOSE and FOCUS are used to capture the requirement change. The OBJECT of change is any activity in the system design which needs a PURPOSE to change. This purpose is created as a result of changing business goals, customer requirements, etc. The object is changed by the FOCUS of change, where any change type can denote the focus. Therefore, each activity in the system design is an object, each changing business goal and customer requirement is a purpose and each change type is a focus. During the preliminary studies we examined several different types of change request forms from industry to understand what information is vital for understanding a requirement change and how it was presented. We discovered two common denominators that should be included in our specification tool. First, the type of change which assists the system designers to understand the action they need to take in order to accomplish the change. Second, the reason for change which gives a better insight as to why the change was requested. The template designed for the change specification based on the framework in Figure 4 is given in Table 2. By selecting the object of change using the system design diagram, designers and decision makers can accurately locate the main target of change, resulting in a clarification of the location of change. Knowing the reason for the change through the purpose ensures that change implementers are able to clarify the need for the change. The focus of change acts as advice on the basic implementation needed to execute the change, resulting in the clarification of the action of change. It indicates to the designers what to do instead of how to do the change. We believe that clearly describing the location, need and action of a change request using this template will resolve much of the existing miscommunication issues. **Table 2. Template for change specification** <table> <thead> <tr> <th><strong>Description</strong></th> <th></th> </tr> </thead> <tbody> <tr> <td>OBJECT</td> <td>The activity name according to the system design diagram</td> </tr> <tr> <td>PURPOSE</td> <td>The reason for the change (can be descriptive)</td> </tr> <tr> <td>FOCUS</td> <td>Select from Add, Delete, Modify or Activity Relocation</td> </tr> <tr> <td></td> <td>(description given in table 6)</td> </tr> </tbody> </table> An additional question (see Table 3) is used along with the above template based on the focus of change that investigates additional inputs and/or outputs required for the change. Answer to this question will be used as input for the change classification method, which is discussed below. **Table 3. List of addition questions** <table> <thead> <tr> <th>Focus of change</th> <th>Additional question</th> </tr> </thead> <tbody> <tr> <td>Add</td> <td>Need addition Input/output?</td> </tr> <tr> <td>Delete</td> <td>Connected to neighbor activity with input/output?</td> </tr> <tr> <td>Modify</td> <td>Input/output modification?</td> </tr> <tr> <td></td> <td>If Yes; Input modification?</td> </tr> <tr> <td></td> <td>Output modification?</td> </tr> <tr> <td>Activity Relocation</td> <td>Relocation requires input/output?</td> </tr> </tbody> </table> 3.4 **Results of Applying It to the Running Example** By applying the change specification method to the running example, we obtain the following results. **Table 4. Application of the Change specification method** <table> <thead> <tr> <th>OBJECT</th> <th>A4 and A5</th> </tr> </thead> <tbody> <tr> <td>PURPOSE</td> <td>Resolution of design error</td> </tr> <tr> <td>FOCUS</td> <td>Add</td> </tr> <tr> <td>Additional Question</td> <td>Need additional Input/output? Y</td> </tr> </tbody> </table> We have used the templates given in Tables 2 and 3 in order to populate the information in Table 4. It is mentioned in the change scenario that this change is required due to a design error. Therefore, the purpose of this change is listed as a resolution for a design error. The activities that are affected by the change are identified through the design diagram to be Check Stock (A4) and Send Invoice (A5). This is again based on the change scenario. The analyst then needs to decide with which focus this change will be executed. In this particular case, it is determined that a new activity needs to be added to handle the change. The next step is to identify if the addition of the new activity would cause new input/output between the existing activities (A4 and A5) and the new activity. As we are trying to bridge the communication between A4 and A5, based on Table 3 it is most likely that such input/output would be generated and therefore the answer to the additional question is ‘Yes’. 4. **The Change Classification Method** The main purpose of change classification method is to ensure that change implementers are able to identify and understand unambiguously the requirement change [11, 35]. Therefore it is essential that the classification itself is not complex. The change specification method is incomplete without having to classify the change as it provides a further understanding of the underlying causes of requirements change [35, 36]. This is the first step towards better and effective management of requirements change in this rapidly changing environment. Other studies [11, 37] also suggests that a classification of change is a scientific step to improve our ability in understanding requirements evolution. 4.1 **Preliminary Studies** To explore the scope and complexity of the existing change classifications and determine the criteria for our change classification, two key investigative methods were undertaken. Firstly, a literature review of existing research on change management with a focus on change classification was undertaken. Keyword searches included change management, change classification, change types, change taxonomy, and change specification. The total result of 43 included journal papers and text books. This was filtered using selection criteria which were limited to articles referring to classification, type and taxonomy which yielded in 12 academic works [1, 3, 11, 13, 35-42]. These papers allowed us to extract the most common and regular change types used in the industry. Secondly, unstructured interviews of 15 practitioners in the field of change management were conducted. Table 5 summarizes the important questions discussed and how they are related to this study. Respondents included project managers, business analysts, IT analysts, and software architects. Since these practitioners were from several software development organizations, the methods followed in change management was quite diverse. One of the key findings was the difficulty in relaying the business requirement change down the IT development line. A secondary related problem which arouse was the misinterpretation of the requirement change and business goal. There were many cases where parts of the final product did not meet the customer satisfaction as the changes requested had not been implemented appropriately. This justified our efforts in creating a change classification that facilitated better understanding of the requested change. We used these interviews to further confirm the change types identified through the literature survey and were able to gain better insight to improve the change classification. ### Table 5. Key question of the interview <table> <thead> <tr> <th>Question</th> <th>Purpose</th> </tr> </thead> <tbody> <tr> <td>How often are changes requested and where do they originate from?</td> <td>To understand the frequency of change request and where they are usually generated from</td> </tr> <tr> <td>What are the types of changes that are often requested?</td> <td>To identify the different types of changes</td> </tr> <tr> <td>Is there a process for requesting change? If so, what are the details?</td> <td>To identify the steps involved in a change request and what vital information needs to be captured</td> </tr> <tr> <td>What are the difficulties in communicating change?</td> <td>To understand the existing problems in the industry and what is lacking in their process of change communication</td> </tr> <tr> <td>Is unambiguous communication of change important? If so, why?</td> <td>To identify if there is a need for a new method of specification and classification of change</td> </tr> </tbody> </table> ### 4.2 Taxonomy Development Our classification is based on previous work-see [1, 3, 38, 39]. Table 6, demonstrates how each previous work has influenced the creation of taxonomy. However, further adjustment was made to improve the classification as mentioned above. The focus of change represents the most common forms of changes found in requirement change requests. Table 7 lists the detailed description of these basic changes. Changes *Add*, *Modify* and *Delete* were identified initially as the classification as a result of both previous literature and practitioner interviews. Change, *Activity Relocation* was included as a result of information gathered through the interviews as we discovered, is a frequent form of change requested. In normal circumstances, combinations of these basic change types can be used to represent more complicated change scenarios. These same change focuses were used in the specification method in order to create a clear connection between the two methods. Application of Table 7 in the classification method can be described as follows. The change focus and the answer to the additional question of the specification method will be used in the classification method as follows. For example, if ‘Add’ was selected as the change focus and the answer was ‘Yes’ to the question ‘Need additional input and/or output?’, then according to Table 4 the linking interface(s) of the new activity and the neighboring activities will mismatch. Therefore the change will be categorised under ‘Add’ change focus with ‘Mismatched links’. The 4th column in Table 6 represents the necessary action to be executed for each change type. ‘Modification’ change focus is divided into three types of change. Inner property modification will deal with modifications done to the variables and operation of an activity that does not affect its external links (input/output) to neighboring activities. Input and output data modification will respectfully affect neighboring activities linked to the input/output of the target activity as well as the internal properties of the target activity depending on the input and/or output added to it. In ‘Delete’ change focus with ‘Matched links’, no modification is needed once the target activity has been removed. The rationale behind this action is that the deleted activity does not provide any output or take in any input from its neighbors. In contrast, with ‘Mismatched links’, once the target activity is deleted, the neighboring activities have to be modified depending on the input/output connection(s) to the deleted activity. Activity relocation will involve moving an activity from its current location and linking it into a new location in the system design. This can be achieved in two ways. One, the activity being relocated is not linked to its neighbors through input/output and able to relocate to the new position without any modifications to the neighboring activity. Two, the target activity in the current location and the new location are affected through input/output and needs to be modified. **Table 6. Key literature used in creation of classification** <table> <thead> <tr> <th>Previous work</th> <th>Concepts extracted</th> <th>Application to the classification</th> </tr> </thead> <tbody> <tr> <td>Nurmuliani, Zowghi &amp; Williams [1]</td> <td>Common types of changes used (add, delete, modify) and classification of changes</td> <td>Helped in creation of the most common focus types</td> </tr> <tr> <td>McGee &amp; Greer [3]</td> <td>Change causes and use of experts in defining a taxonomy</td> <td>Leading to different change activities and the use of change practitioners</td> </tr> <tr> <td>Nurmuliani, Zowghi &amp; Williams [38]</td> <td>Categories of change</td> <td>Helped in creation of the most common focus types</td> </tr> <tr> <td>Xiao, Quo &amp; Zou [39]</td> <td>Primitive changes in business functions</td> <td>Further expression of change types</td> </tr> </tbody> </table> Table 7. Detailed change description <table> <thead> <tr> <th>Change focus</th> <th>Answer to Additional Question</th> <th>Change type</th> <th>Action</th> </tr> </thead> <tbody> <tr> <td>Add</td> <td>No</td> <td>Matched links</td> <td>Add new activity without changing the current activity or any connected links</td> </tr> <tr> <td></td> <td>Yes</td> <td>Mismatched links</td> <td>Add new activity by changing the activity and/or connected links</td> </tr> <tr> <td>Modification</td> <td>No</td> <td>Inner property modification</td> <td>Modify the implementation of a activity without changing the connected links</td> </tr> <tr> <td></td> <td>Yes</td> <td>Input data modification</td> <td>Modify the input link and internal properties of a activity</td> </tr> <tr> <td></td> <td>Yes</td> <td>Output data modification</td> <td>Modify the output link and internal properties of a activity</td> </tr> <tr> <td>Delete</td> <td>No</td> <td>Matched links</td> <td>Delete activity without changing the activity or connected links</td> </tr> <tr> <td></td> <td>Yes</td> <td>Mismatched links</td> <td>Delete activity by changing the activity and/or connected links</td> </tr> <tr> <td>Activity Relocation</td> <td>No</td> <td>Relocation with matched links</td> <td>Relocate existing activity without changing the activity or connected links</td> </tr> <tr> <td></td> <td>Yes</td> <td>Relocation with mismatched links</td> <td>Relocate new activity by changing the activity and/or connected links</td> </tr> </tbody> </table> At implementation time, the key elements of the two methods (specification and classification) are incorporated into a single table (see Table 8). In the table, change number refers to the number given to each change as they are requested. The object, purpose and focus in Table 8 correspond to the information given in Table 2 i.e. activity name according to the system design diagram (this is the activity affected by the change), reason for change and select from Add, Delete, Modify or Activity relocation respectively. The additional question selected from Table 3 will be based on what has been selected for the focus and the information provided through the content of Table 2. Change type and action can be sourced from Table 7 based on the information provided for object, focus and additional question respectively. The possibility columns represent how each change may be described using different focuses. This may not apply to all changes. The ability to create multiple possibilities which will be based on the experience of the analyst and complexity of the change. This feature was added to the implementation template to provide more diversity and flexibility of communicating a change. Having multiple possibilities also provides flexibility of how the change can be implemented. Table 8. Template for implementation <table> <thead> <tr> <th>Change No.</th> <th>Possibility 01</th> <th>Possibility 02</th> <th>Possibility n</th> </tr> </thead> <tbody> <tr> <td>OBJECT</td> <td></td> <td></td> <td></td> </tr> <tr> <td>PURPOSE</td> <td></td> <td></td> <td></td> </tr> <tr> <td>FOCUS</td> <td></td> <td></td> <td></td> </tr> <tr> <td>Additional Question</td> <td></td> <td></td> <td></td> </tr> </tbody> </table> RESULT <table> <thead> <tr> <th>CHANGE TYPE</th> <th>Possibility 01</th> <th>Possibility 02</th> <th>Possibility n</th> </tr> </thead> <tbody> <tr> <td>ACTION</td> <td></td> <td></td> <td></td> </tr> </tbody> </table> 4.3 Results of Applying It to the Running Example By applying the template for implementation for the above scenario, we obtain the following result as given in Table 9: Table 9. Application of the implementation template <table> <thead> <tr> <th>Change 01</th> <th>Possibility 01</th> <th>Possibility 02</th> </tr> </thead> <tbody> <tr> <td>OBJECT</td> <td>$A_4$ and $A_5$</td> <td>$A_4$ and $A_5$</td> </tr> <tr> <td>PURPOSE</td> <td>Resolution of design error</td> <td>Resolution of design error</td> </tr> <tr> <td>FOCUS</td> <td>Add</td> <td>Modify</td> </tr> <tr> <td>Additional Question</td> <td>Need addition Input/output? Y</td> <td>Input/output modification? Y</td> </tr> </tbody> </table> Result <table> <thead> <tr> <th>Change Type</th> <th>Possibility 01</th> <th>Possibility 02</th> </tr> </thead> <tbody> <tr> <td>Action</td> <td>Add new activity between $A_i$ and $A_j$ (Mismatched links)</td> <td>Inner property modification and Output data modification $A_i$ and input data modification of $A_j$</td> </tr> </tbody> </table> In Table 9, we describe the two possibilities for the scenario provided in the running example. For both possibilities, the object and the purpose remains the same and coincide with what has been discussed in Table 4. We are of the opinion that there are two ways this change can be described and the focus of each possibility demonstrates this fact. Possibility 1 was introduced in Table 4. The sections above the Results row of Table 9 is based on applying Tables 2 and 3 of change specification and were discussed in section 3.4. Based on the information provided for the Focus and Additional question, change type and action can be extracted from Table 7. This extraction is shown in Table 9, for each possibility based on the different change focus which has been identified. In the case of Possibility 1, the focus identified is ‘Add’ and the additional question has been given an answer ‘yes’. When this information is mapped to Table 7, it provides a change type of ‘Mismatched links’, which requires a change action of ‘Add new activity by changing the activity and/or connected links’. When adding the new activity between A<sub>4</sub> and A<sub>5</sub>, connections need to be made with both activities. Therefore, both A<sub>4</sub> and A<sub>5</sub> will be directly affected by this addition. In both possibilities, all activities that are connected to A<sub>4</sub> and A<sub>5</sub> will be indirectly affected by the alterations. 5. An Application of the Methods Yin [43, 44] explained the usefulness of using case studies to explore the merits of an application of a research idea/hypothesis. We therefore demonstrate the usefulness of the change specification and classification methods by applying them to a software project case study. We make two key assumptions with the case study that the project is in a state where the requirements elicitation has occurred and the process diagram has been established. We have already used a simple case study as a running example. The case study introduced in this section enable us to illustrate the versatility of the methods by way of using various change focus, various change types and how the outcome of the change classification differs with the need for input/output modifications. 5.1 The Case Study Figure 6 represents a partial system design diagram of a course management system adopted from [45]. The diagram illustrates the relationships and some dependencies the activities have with each other. The relationships denoted in the diagram can be defined as follows: - Requires (Req): An activity A<sub>1</sub> requires an activity A<sub>2</sub> if A<sub>1</sub> is fulfilled only when A<sub>2</sub> is fulfilled. A<sub>2</sub> can be treated as a pre-condition for A<sub>1</sub> [45]. - Refines (Ref): An activity A<sub>1</sub> refines an activity A<sub>2</sub> if A<sub>2</sub> is derived from A<sub>1</sub> by adding more details to it [45]. - Contains (Con): An activity A<sub>1</sub> contains information from A<sub>2</sub>...A<sub>n</sub> if A<sub>1</sub> is the conjunction of the contained information from A<sub>2</sub>...A<sub>n</sub> [45]. The identification of these relationships is beneficial in determining the impact of change when applying our methods to the case study. The detailed purpose of each activity is described as follows: A1. The system allows end-users to provide profile and context information for registration. A2. The system provides functionality to search for other people registered in the system. A3. The system provides functionality to allow end-users to log into the system with their password. A4. The system supports three types of end-users (administrator, lecturer and student). A5. The system allows lecturers to set an alert on an event. A6. The system maintains a list of events about which the students can be notified. A7. The system notifies the students about the occurrence of an event as soon as the event occurs. A8. The system actively monitors all events. A9. The system notifies students about the events in the lectures in which they are enrolled. A10. The system allows students to enroll in lecturers. A11. The system allows lecturers to send e-mail to students enrolled in the lecture given by that lecturer. A12. The system allows students to be assigned to teams for each lecture. A13. The system allows lecturers to send e-mail to students in the same group. A14. The system allows lecturers to modify the content of the lectures. A15. The system gives different access rights to different types of end-users. A16. The system supports two types of end-users (lecturer and student) and it will provide functionality to allow end-users to log into the system with their password. Fig. 6. Partial system design diagram of a course management system. 5.2 Applying Them to the Case Study The example consists of two scenarios, where we apply the specification and classification methods. These scenarios are based on our observations as university academics who use similar course management systems. The following hypothetical new requirements are identified: 1. In an emergency, it would be more effective to send an SMS notification to students as well as an email. 2. Marking attendance manually tends to be rather ineffective, especially when a census needs to be carried out. It would be better to mark attendance electronically. The application of the implementation template yields the following results. **Table 10. Change 01 result** <table> <thead> <tr> <th>Change 01</th> <th>Possibility 01</th> <th>Possibility 02</th> </tr> </thead> <tbody> <tr> <td><strong>Object</strong></td> <td>Enrol for lectures A₁₀</td> <td>Send email to all students A₁₁</td> </tr> <tr> <td><strong>Purpose</strong></td> <td>Functionality enhancement</td> <td>Functionality enhancement</td> </tr> <tr> <td><strong>Focus</strong></td> <td>Add</td> <td>Modify</td> </tr> <tr> <td><strong>Additional Question</strong></td> <td>Need additional Input / Output? Y</td> <td>Input/output modification? Y</td> </tr> </tbody> </table> **Table 11. Change 02 result** <table> <thead> <tr> <th>Change 02</th> <th>Possibility 01</th> </tr> </thead> <tbody> <tr> <td><strong>Object</strong></td> <td>Enrol for lectures A₁₀</td> </tr> <tr> <td><strong>Purpose</strong></td> <td>Identification of new requirement</td> </tr> <tr> <td><strong>Focus</strong></td> <td>Add</td> </tr> <tr> <td><strong>Additional Question</strong></td> <td>Need additional Input / Output? Y</td> </tr> </tbody> </table> **Table 5.3 Discussion of the Results** Tables 10 and 11 demonstrate how the specification and classification methods can be applied to this case study. The template given in Table 8 has been used for obtaining the result for each change. Multiple possibilities can be created for each change event, depending on the event, availability of existing activities and various combinations that could be incorporated to realize the change. Such an instance has been provided for the 1st change event. In this change, the need to send SMS to students can be accomplished by either creating a new activity or modifying an existing activity \(A_{11}\). As such, when creating a new activity, it requires information from \(A_{10}\). Therefore, the activity directly affected by the event is \(A_{10}\). Rest of the table for the case study follows the process as explained through the simple stock control example. In the second change event, we considered only one possibility. The requirement is to allow lecturers to mark attendance electronically. There doesn’t seem to be any existing activity that can be modified to serve this purpose, therefore the only option is to create a new activity. As such a new activity is created that requires student information, which is provided by \(A_{10}\). Therefore, the activity directly affected by the event is \(A_{10}\) and the rest of the table also follows the same principle as explained through the simple stock control example. This example demonstrates how the specification and classification methods can be used to generate multiple possibilities for a single change. This outcome provides decision makers with the option of choosing the most appropriate way of implementing the change. The example above illustrates the way these methods can help both business and IT personnel involved, analyse business changes and thereby assist in the change management process. At the business level, the business analyst can use Tables 1 and 2 to define and describe the requirements change without any ambiguities. As a result of this IT personnel are able to not only understand the change but also understand the need for change and identify the location of change. 6. **Comparison with Related Work** We shall describe what the literature has said about the related work and concepts like taxonomies and classification which are important concepts in studying change identification and classification. 6.1 **Taxonomies** 1) Research analysing change uses a plethora of techniques in order to build a taxonomy that can be used to identify changes as well as their impact. One such mechanism is the use of requirement engineering artifacts, such as use cases. The research done by Basirati et al. [46] establishes a taxonomy of common changes based on their observation of changing use cases that can then be used in other projects to predict and understand RCs. They also contribute to this research space by identifying which parts of use cases are prone to change as well as what changes would create difficulty in application, contributing also to the impact analysis of change. 2) The taxonomy developed by Buckley et al. [47], proposes a software change taxonomy based on characterizing the mechanisms of change and the factors that influence software change. This research emphasizes the underlying mechanism of change by focusing on the technical aspects (i.e. how, when, what and where) rather than the purpose of change (i.e. the why) or the stakeholders of change (i.e. who) as other taxonomies have done. This taxonomy provides assistance in selecting tools for change management that assist in identifying the changes correctly. 3) McGee and Greer [3] developed a taxonomy based on the source of Requirements Change (RC) and their classification according to the change source domain. The taxonomy allows change practitioners to make distinctions between factors that contribute to requirements uncertainty, leading to the better visibility of change identification. This taxonomy also facilitates better recording of change data which can be used in future projects or the maintenance phase of the existing project to anticipate the future volatility of requirements. 4) Gosh et al. [48] emphasize the importance of having the ability to proactively identify potentially volatile requirements and being able to estimate their impact at an early stage is useful in minimizing the risks and cost overruns. To this effect, they developed a taxonomy that is based on four RC attributes i.e. phases (design, development and testing), actions (add, modify and delete), sources (emergent, consequential, adaptive and organizational) and categories of requirements (functional, non-functional, user interface and deliverable). 5) The taxonomy established by Briand et al. [41] is the initial step in a full-scale change management process of UML models. In their research, they establish that change identification is the first step in the better management of RCs. The classification of the change taxonomy is based on the types of changes that occur in UML models. They then use this taxonomy to identify changes between two different versions of UML models and finally to determine the impact of such changes. 6.2 Classifications There are many benefits of using a classification, the main benefits being to manage change to enable change implementers to identify and understand the requirements of change without ambiguity [49, 50]. The classification of RC has been studied in various directions. Table 12 lists the different directions which have been the subjects of studies. 6.3 Other Change Identification Methods 1) Kobayashi and Maekawa [4] proposed a model that defines the change requirements using the aspects where, who, why and what. This allows the system analyst to identify the change in more detail, resulting in better impact identification as well as risk and effort estimation. This method consists of verification and validation and can be used to observe the RCs throughout the whole lifecycle of the system. 2) The change identification method usually has a pre-established base upon which its semantics are built. Ecklund’s [42] approach to change management is a good example of this. The approach utilizes use cases (change cases) to specify and predict future changes to a system. The methodology attempts to identify and incorporate the anticipated future changes into a system design in order to ensure the consistency of the design. Table 12. Direction is change classification <table> <thead> <tr> <th>Direction</th> <th>Parameters</th> <th>Comment</th> </tr> </thead> <tbody> <tr> <td>Type [40, 48, 50-54]</td> <td>Add, Delete, Modify</td> <td>The most common way of classifying change.</td> </tr> <tr> <td>Reason [13, 50, 51]</td> <td>Defect fixing, Missing requirements, Functionality enhancement, Product strategy, Design improvement, Scope reduction, Redundant functionality, Obsolete functionality, Erroneous requirements, Resolving conflicts, Clarifying requirements, Improve, Maintain, Cease, Extend, Introduce</td> <td>Helps determine the causes of change and understand change process and related activities.</td> </tr> <tr> <td>Drivers [56]</td> <td>Environmental change, RC, Viewpoint change, Design change</td> <td>Helps change estimation and reuse of requirements.</td> </tr> </tbody> </table> 6.4 Identifying limitations and comparison We use the work listed in Table 13 (discussed above) to describe the limitations of the existing work and compare our methods to define what has been achieved. An examination of the work reported above lead to the identification of four key limitations: 1. There is little agreement and commonality between the studies; 2. for the process of specification and classification of change to be used successfully, in our view it needs to be a part of the same process (change request); they complement each other by providing a better understanding of the requirements change; 3. there has been little emphasis on designing specification methods related to change; and 4. a common limitation of the above classifications is the lack of guidance in applying them to change management activities. As a result, we believe that a void exists in the practical application of change specification and classification and our methods address this research gap. ## Table 13. Comparison with the related work <table> <thead> <tr> <th>Technique</th> <th>Limitations</th> <th>What our methods can address</th> </tr> </thead> <tbody> <tr> <td>Basirati et al. [46] and Ecklund [42]</td> <td>Can only be applied if use cases are available or used in the development process.</td> <td>They are applied at a design phase, which enables the identification of changes at an early stage. Can be used as long as there is a form of design diagram of the system.</td> </tr> <tr> <td>Buckley et al. [47]</td> <td>It did not directly address issues arising from miscommunication of change.</td> <td>They can be directly used for managing changes for the purpose of identifying changes.</td> </tr> <tr> <td>McGee and Greer [3] and Ecklund [42]</td> <td>They are limited to providing assistance in predicting change.</td> <td>They provide a way of communicating change as well identifying them in an early stage as to where and how the change should be applied.</td> </tr> <tr> <td>Gosh et al. [48]</td> <td>Only used for identification of change.</td> <td>Provide preliminary guidance on how to manage the changes.</td> </tr> <tr> <td>Briand et al. [41]</td> <td>Can be used only if UML models are available.</td> <td>Can be used as long as there is a form of design diagram for the system.</td> </tr> <tr> <td>Kobayashi and Maekawa [4]</td> <td>This is a complex method for verifying changes.</td> <td>They address change management issues arising from miscommunication.</td> </tr> </tbody> </table> ## 7. Conclusions and Future Work The purpose of the change specification and classification methods presented in this paper is to manage requirements change by improving change communication and elicitation. Under normal circumstances, business changes flow from the business side to the IT side. Therefore, the impact of this study belongs to both these categories i.e. business and IT. First, considering the business side, we ensure a requirements change has been clearly communicated to the IT side. As mentioned earlier, there is often difficulty in promoting effective dialogue about the nature of the change between these two parties. Therefore, a change specification method would be essential for business analysts in communicating change. Second, on the IT side, it is critical that change enablers have a mutual understanding of not only the precise nature of the change but also the reason for its existence, i.e. its purpose. This insight translates into a better realization of the requirements change. Equally important is a quick response from IT in redesigning the system to suit the requirements change. The three main categories: object, purpose and focus of the change specification method enhance understanding while the classification of the change type and the resulting action assists system designers to incorporate the change into the system design much faster. Given the above impact of our methods, we believe that there are substantial benefits of specification and classification methods that will lead to improvements in the change management process. In our view, the benefits of these methods are: • Promotes a mutual understanding of requirements change between business and IT through the templates provided by Tables 2 and 3. • Supports the decision-making process by helping to determine the need for the change. • Assists in determining the best course of action in implementing the requirements change through Table 7. In future work, we plan to use the multiple change identification possibilities to evaluate the best course of action to enable system designers to respond quickly to change requests. Furthermore, we suggest it will be useful in evaluating the interdependencies of these change requests as they relate to interdependencies of the system requirements and its implementation. Identification of interdependencies between changes can lead to identification of conflicts between requirement changes. Also, it would be valuable if it were possible identify the difficulty level and priority of the changes so that resources such as time and effort can be allocated more effectively. Identifying the difficult level of the change would further result in assisting the decision of the plausibility of implementing the change. References 1. Nurmuliani, N., Zowghi, D., Williams, S. P.: Requirements volatility and its impact on change effort: Evidence-based research in software development projects. In Proceedings of the 11th Australian Workshop on Requirements Engineering. (2006) Involved in Changing Software Requirements. Software Engineering Research and Practice, the 4th International Conference on Software Engineering Advances, 51-58. (2009) Proceedings of the 8th International Conference and Workshop on Engineering of Computer Based Systems, 171-178. (2001) Proceedings of the International Conference on Information Management and Engineering, 37-41. (2009) 6. André, C., Mallet, F.: Specification and verification of time requirements with CCSL and Sons, Inc. (1997) Shalinka Jayatilleke holds a BSc (Hons) from Institute of Technological Studies (Affiliated to Troy University, USA), an MSc from Sri Lanka Institute of Information Technology and present reading for a PhD (in computer science) at La Trobe University, Australia. She is currently an Associate lecturer at La Trobe University with an academic career of 12 years. His current research interests are requirements engineering and change management. Richard Lai holds a BE (Hons) and a MEngSc from the University of New South Wales and a PhD from La Trobe University, Australia. He has spent about 10 years in the computer industry prior to joining La Trobe University in 1989. His current research interests include component-based software system, software measurement, requirements engineering, and global software development. Karl Reed holds an Assc. Dip. in Communications Engineering from the RMIT and an MSc in Computer Architecture from Monash University. After 12 years in industry he joined Monash University in 1976. He moved to La Trobe University in 1988. His research interests include software testing, compilable restricted natural languages, web-page design, high-level software re-use, design isomorphism, organisational resilience, cloud computing and industry policy. Received: November 30, 2016; Accepted: July 2, 2017.
{"Source-Url": "http://www.comsis.org/pdf.php?id=612-1611", "len_cl100k_base": 12820, "olmocr-version": "0.1.53", "pdf-total-pages": 26, "total-fallback-pages": 0, "total-input-tokens": 77656, "total-output-tokens": 15804, "length": "2e13", "weborganizer": {"__label__adult": 0.0003788471221923828, "__label__art_design": 0.0008177757263183594, "__label__crime_law": 0.0003695487976074219, "__label__education_jobs": 0.0105133056640625, "__label__entertainment": 0.00011032819747924803, "__label__fashion_beauty": 0.0002219676971435547, "__label__finance_business": 0.0009984970092773438, "__label__food_dining": 0.00036525726318359375, "__label__games": 0.0008764266967773438, "__label__hardware": 0.000568389892578125, "__label__health": 0.0004377365112304687, "__label__history": 0.0003712177276611328, "__label__home_hobbies": 0.00011360645294189452, "__label__industrial": 0.0003924369812011719, "__label__literature": 0.0005769729614257812, "__label__politics": 0.0002548694610595703, "__label__religion": 0.0004343986511230469, "__label__science_tech": 0.0219879150390625, "__label__social_life": 0.00014019012451171875, "__label__software": 0.0149078369140625, "__label__software_dev": 0.9443359375, "__label__sports_fitness": 0.0002435445785522461, "__label__transportation": 0.0004317760467529297, "__label__travel": 0.00021517276763916016}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 70784, 0.02889]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 70784, 0.44482]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 70784, 0.91123]], "google_gemma-3-12b-it_contains_pii": [[0, 2502, false], [2502, 6192, null], [6192, 8476, null], [8476, 12138, null], [12138, 13920, null], [13920, 16612, null], [16612, 20131, null], [20131, 23210, null], [23210, 24269, null], [24269, 27133, null], [27133, 29650, null], [29650, 32958, null], [32958, 36093, null], [36093, 38857, null], [38857, 41597, null], [41597, 44536, null], [44536, 45911, null], [45911, 47465, null], [47465, 50579, null], [50579, 53464, null], [53464, 55459, null], [55459, 57952, null], [57952, 61340, null], [61340, 65071, null], [65071, 68481, null], [68481, 70784, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2502, true], [2502, 6192, null], [6192, 8476, null], [8476, 12138, null], [12138, 13920, null], [13920, 16612, null], [16612, 20131, null], [20131, 23210, null], [23210, 24269, null], [24269, 27133, null], [27133, 29650, null], [29650, 32958, null], [32958, 36093, null], [36093, 38857, null], [38857, 41597, null], [41597, 44536, null], [44536, 45911, null], [45911, 47465, null], [47465, 50579, null], [50579, 53464, null], [53464, 55459, null], [55459, 57952, null], [57952, 61340, null], [61340, 65071, null], [65071, 68481, null], [68481, 70784, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 70784, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 70784, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 70784, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 70784, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 70784, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 70784, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 70784, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 70784, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 70784, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 70784, null]], "pdf_page_numbers": [[0, 2502, 1], [2502, 6192, 2], [6192, 8476, 3], [8476, 12138, 4], [12138, 13920, 5], [13920, 16612, 6], [16612, 20131, 7], [20131, 23210, 8], [23210, 24269, 9], [24269, 27133, 10], [27133, 29650, 11], [29650, 32958, 12], [32958, 36093, 13], [36093, 38857, 14], [38857, 41597, 15], [41597, 44536, 16], [44536, 45911, 17], [45911, 47465, 18], [47465, 50579, 19], [50579, 53464, 20], [53464, 55459, 21], [55459, 57952, 22], [57952, 61340, 23], [61340, 65071, 24], [65071, 68481, 25], [68481, 70784, 26]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 70784, 0.2659]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
14adb4d66648b3afb530e20d14b0cbdc0fc693e7
An Improved $O(R \log \log n + n)$ Time Algorithm for Computing the Longest Common Subsequence Daxin Zhu, Lei Wang, and Xiaodong Wang* Abstract—In this paper, we revisit the much studied LCS problem for two given sequences. Based on the algorithm of Iliopoulos and Rahman for solving the LCS problem, we have suggested 3 new improved algorithms. We first reformulate the problem in a very succinct form. The problem LCS is abstracted to an abstract data type $DS$ on an ordered positive integer set with a special operation $Update(S, x)$. For the two input sequences $X$ and $Y$ of equal length $n$, the first improved algorithm uses a van Emde Boas tree for $DS$ and its time and space complexities are $O(R \log \log n + n)$ and $O(R)$, where $R$ is the number of matched pairs of the two input sequences. The second algorithm uses a balanced binary search tree for $DS$ and its time and space complexities are $O(R \log L + n)$ and $O(R)$, where $L$ is the length of the longest common subsequence of $X$ and $Y$. The third algorithm uses an ordered vector for $DS$ and its time and space complexities are $O(nL)$ and $O(R)$. Index Terms—longest common subsequence, NP-hard problems, dynamic programming, time complexity. I. INTRODUCTION The longest common subsequence (LCS) problem is a classic problem in computer science. The problem has several applications in many apparently unrelated fields ranging from file compression, pattern matching and computational biology [11], [2], [4], [5], [14]–[16]. Given two sequences $X$ and $Y$, the longest common subsequence (LCS) problem is to find a subsequence of $X$ and $Y$ whose length is the longest among all common subsequences of the two given sequences. The classic algorithm to LCS problem is the dynamic programming solution of Wagner and Fischer [13], with $O(n^2)$ worst case running time. Masek and Paterson [7] improved this algorithm by using the "Four-Russians" technique to reduce its running time to $O(n^2/\log n)$ in the worst case. Since then, there has been not much improvement on the time complexity in terms of $n$ found in the literature. However, there were several algorithms with time complexities depending on other parameters. For example, Myers in [8] and Nakatsu et al. in [9] presented an $O(nD)$ algorithm, where the parameter $D$ is the Levenshtein distance of the two given sequences. The number of matched pairs of the two input sequences $R$, is perhaps another interesting and more relevant parameter for LCS problem. Hunt and Szymanski [5] presented an $O((R + n) \log n)$ time algorithm to solve LCS problem. Their paper also cited applications, where $R \sim n$ and thus the algorithm would run in $O(n \log n)$ time for these applications. To the authors’ knowledge, the most efficient algorithm sofar for solving the LCS problem is the $O(R \log \log n + n)$ time algorithm presented by Iliopoulos and Rahman [6], [11]. The key point of their algorithm is to solve a restricted dynamic version of the Range Maxima Query problem by using some interesting techniques of [10], and combining them with van Emde Boas structure [12]. Readers are referred to [1] for a more comprehensive comparison of the well-known algorithms for LCS problem and their behavior in various application. In this paper, we will revisit the classic LCS problem for two given sequences and present new algorithms with some interesting new observations and some novel ideas. We first reformulate the problem in a very succinct form. The problem LCS is abstracted to an abstract data type $DS$ on an ordered positive integer set with a special operation $Update(S, x)$. Three new improved algorithms have been suggested. The first improved algorithm uses a van Emde Boas tree for $DS$ and its time and space complexities are $O(R \log \log n + n)$ and $O(R)$, where $R$ is the number of matched pairs of the two input sequences. The second algorithm uses a balanced binary search tree for $DS$ and its time and space complexities are $O(R \log L + n)$ and $O(R)$, where $L$ is the length of the longest common subsequence of $X$ and $Y$. The third algorithm uses an ordered vector for $DS$ and its time and space complexities are $O(nL)$ and $O(R)$. The organization of the paper is as follows. In the following 4 sections, we describe our improved $O(R \log \log n + n)$ time algorithm of Iliopoulos and Rahman for solving LCS problem. In Section 2, the preliminary knowledge for presenting our algorithm for LCS problem is discussed, and the $O(R \log \log n + n)$ time algorithm of Iliopoulos and Rahman is reviewed briefly. In Section 3, we present our improvements on the algorithm of Iliopoulos and Rahman with time complexity $O(R \log \log n + n)$, where $n$ and $R$ are the lengths of the two given input strings, and the number of matched pairs of the two input sequences, respectively. Some concluding remarks are located in Section 4. II. AN $O(R \log \log n + n)$ TIME ALGORITHM In this section, we briefly review the $O(R \log \log n + n)$ time algorithm of Iliopoulos and Rahman for the sake of completeness. A sequence is a string of characters over an alphabet \( \sum \). A subsequence of a sequence \( X \) is obtained by deleting zero or more characters from \( X \) (not necessarily contiguous). A substring of a sequence \( X \) is a subsequence of successive characters within \( X \). For a given sequence \( X = x_1x_2 \cdots x_n \) of length \( n \), the \( i \)th character of \( X \) is denoted as \( x_i \in \sum \) for any \( i = 1, \ldots, n \). A subsequence of \( X \) from position \( i \) to \( j \) can be denoted as \( X[i : j] = x_ix_{i+1} \cdots x_j \). If \( i \neq 1 \) or \( j \neq n \), then the substring \( X[i : j] = x_{i+1} \cdots x_j \) is called a proper substring of \( X \). A substring \( X[i : j] = x_ix_{i+1} \cdots x_j \) is called a prefix or a suffix of \( X \) if \( i = 1 \) or \( j = n \), respectively. **Definition 1:** An appearance of sequence \( X = x_1x_2 \cdots x_n \) in sequence \( Y = y_1y_2 \cdots y_n \), for any \( X \) and \( Y \), starting at position \( j \) is a sequence of strictly increasing indexes \( i_1, i_2, \ldots, i_n \) such that \( i_1 = j \), and \( X = y_{i_1}y_{i_2} \cdots y_{i_n} \). A match for sequences \( X \) and \( Y \) is a pair \((i, j)\) such that \( x_i = y_j \). The set of all matches, \( M \), is defined as follows: \[ M = \{(i, j)|x_i = y_j, 1 \leq i, j \leq n\} \] The total number of matches for \( X \) and \( Y \) is denoted by \( R = |M| \). It is obvious that \( R \leq n^2 \). **Definition 2:** A common subsequence of the two input sequences \( X = x_1x_2 \cdots x_n \) and \( Y = y_1y_2 \cdots y_n \), denoted \( cs(X, Y) \), is a subsequence common to both \( X \) and \( Y \). The longest common subsequence of \( X \) and \( Y \), denoted \( LCS(X, Y) \), is a common subsequence whose length is the longest among all common subsequences of the two given sequences. The length of \( LCS(X, Y) \) is denoted as \( r(X, Y) \). In this paper, the two given sequences \( X \) and \( Y \) are assumed to be of equal length. But all the results can be easily extended to the case of two sequences of different length. **Definition 3:** Let \( T(i, j) \) denote \( r(X[1 : i], Y[1 : j]) \), when \((i, j) \in M \). \( T(i, j) \) can be formulated as follows: In the algorithm of Iliopoulos and Rahman [3], a vector \( H \) of length \( n \) is used to denote the maximum value so far of column \( l \) of \( T \). For the current value of \( i \in [1..n] \), \( H_i(l) = \max_{x \leq l < k \leq \min(l+1, |T|)} T(k, l) \), \( 1 \leq l \leq n \). The footnot index is used to indicate that the current row number is \( i \), and the values of \( H_i(l) \), \( 1 \leq l \leq n \) are not changed for row \( i \) in the algorithm. We can omit the footnot index if the current row is clear. The most important function \( RMQ_i(\text{left}, \text{right}) = \max_{x}\{H_i(l) \} \) used in the algorithm is a range maxima query on \( H \) for the range \( [\text{left}..\text{right}] \), \( 1 \leq \text{left} \leq \text{right} \leq n \). It is clear that \[ T(i, j) = 1 + RMQ_i(1, j - 1), \quad \text{if} \quad (i, j) \in M \quad (2) \] For the efficient computation of \( T(i, j) \), the following facts [10] are utilized in the algorithm of Iliopoulos and Rahman. **Fact 1:** Suppose \((i, j) \in M \). Then for all \((i', j') \in M, i' > i \), \((\text{resp.}(i', j') \in M, j' > j)\), we must have \( T(i', j) \geq T(i, j) \) (resp. \( T(i, j) \geq T(i', j) \)). **Fact 2:** The calculation of the entry \( T(i, j) \), \((i, j) \in M, 1 \leq i, j \leq n \), is independent of any \( T(l, q), (l, q) \in M, l = i, 1 \leq q \leq n \). The algorithm is proceed in a row by row manner as follows. **Algorithm 1** Iliopoulos-Rahman-LCS 1: for \( i = 1 \) to \( n \) do 2: \( H \leftarrow S \) \{Update \( H \) for the next row\} 3: for all \((i, j) \in M \) do 4: \( T(i, j) \leftarrow 1 + RMQ(1, j - 1) \) 5: \( S(j) \leftarrow T(i, j) \) 6: end for 7: end for In the algorithm, another vector \( S \), of length \( n \), is invoked as a temporary vector. After calculating \( T(i, j) \), the vector \( S \) is restored from \( T, S(j) = T(i, j) \), if \((i, j) \in M \). Therefore, at the end of processing of row \( i \), \( S \) is actually \( H_{i+1} \). The algorithm continues in this way as long as it is in the same row. As soon as it comes a new row, the vector \( H \) is updated with new values from \( S \). In the algorithm above, \( RMQ(1, j - 1) \) is actually \( RMQ(1, j - 1) \). We can omit the footnot index since the processing is in the same row \( i \). The correctness of the above procedure follows from Facts 1 and 2. The problem \( RMQ \) can be solved in \( O(n) \) preprocessing time and \( O(1) \) time per query [2]. Therefore, for the constant time range maxima query, an \( O(n) \) preprocessing time has to be paid as soon as \( H \) is updated. Due to Fact 2, it is sufficient to perform this preprocessing once per row. So, the computational effort added for this preprocessing is \( O(n^2) \) in total. The most complicated part of the algorithm of Iliopoulos and Rahman is in the computation of \( RMQ(1, j - 1) \). To eliminate the \( n^2 \) term from the running time of the algorithm, a van Emde Boas tree is used to store the information in \( H \). This data structure can support the operations Search, Insert, Delete, Min, Max, Succ, and Pred in \( O(\log \log n) \) time. By using these operations the query \( RMQ(1, j - 1) \) can then be answered in \( O(\log \log n) \) time. The \( O(n) \) preprocessing step of the algorithm can then be avoided and hence the \( n^2 \) term can be eliminated from the running time. However, as a price to pay, the query time of \( RMQ(1, j - 1) \) increases to \( O(\log \log n) \). Finally, the time complexity is improved to \( O(R\log \log n + n) \), using \( O(n^2) \) space. The vEB structure described in the algorithm of Iliopoulos and Rahman is somewhat involved. For more details of the data structure, the readers are referred to [10]. ### III. IMPROVEMENTS OF THE ALGORITHM In this section, we will present several improvements on the algorithm of Iliopoulos and Rahman. **A. A first improvement** In the algorithm of Iliopoulos and Rahman, the set \( M = \{(i, j)|x_i = y_j, 1 \leq i, j \leq n\} \) is constructed explicitly in the lexicographic order of the matches such that all the matches can be processed in the correct order. To this purpose, two separate lists, \( L_X \) and \( L_Y \) are built in \( O(n) \) time. For each symbol \( c \in \sum \), \( L_X(c) \) (resp. \( L_Y(c) \)) stores, in sorted order, the positions of \( c \) in \( X \) (resp. \( Y \)), if any. Then, a van Emde Boas structure is used to build the set \( M \) in \( O(R\log \log n) \) time. This preprocessing step can be removed completely from our improved algorithm, since we do not need to access \[ T(i, j) = \begin{cases} \text{Undefined} & \text{if } (i, j) \not\in M \\ 1 & \text{if } (i, j) \in M \text{ and } (i', j') \not\in M, i' < i, j' < j \\ \max_{1 \leq l_1 < i, 1 \leq l_2 < j} \{T(l_1, l_2)\} & \text{otherwise} \end{cases} \] (1) Each match \((i, j)\) directly. It will be clear in the description of the algorithm in latter section. Secondly, to avoid overlap, the information in \(H\) are stored separately in row \(i\) and \(i + 1\). We have noticed that, the only query on \(H\) used in the algorithm is of the form \(RMQ(1, j - 1) = \max_{1 \leq l \leq n} \{T(k, l)\}, 1 \leq l \leq n\) for the current value of \(i \in [1..n]\), it is not difficult to observe the following fact. **Fact 3:** For all \(1 \leq i' < i \leq n\), and \(1 \leq j \leq n\), \(H_{i'}(j) \leq H_i(j)\). The information in \(H\) we maintained is used for computing \(RMQ(1, j - 1)\) in the algorithm. If we use a vector \(Q\) of length \(n\) to store the values of \(Q(j) = \max_{1 \leq k < i} \{T(k, j)\}\) for all \(1 \leq j \leq n\), then \(RMQ(1, j - 1)\) will be computed more directly by \(Q(j - 1)\) in \(O(1)\) time. For example, if \(H = (0, 1, 2, 1, 2, 0, 1)\), then \(Q = (0, 1, 2, 2, 2, 2, 2)\). An important albeit easily observable fact about \(Q\) is that, its components \(Q(j), 1 \leq j \leq n\) are nondecreasing. **Fact 4:** Suppose \(Q(j) = \max_{1 \leq l \leq n} \{T(k, l)\}\). Then the values of \(Q(j), 1 \leq j \leq n\) form a nondecreasing sequence. This sequence is under a very special form. If \(Q(j) < Q(j+1), 1 \leq j < n\), then \(Q(j+1) = Q(j) + 1\). Therefore, the values of this sequence are taken from a consecutive integer set \(0, 1, \ldots, L\), where \(L = r(X, Y)\) is the length of the longest common subsequence of \(X\) and \(Y\). **Proof.** For any \(1 \leq j' < j \leq n\), \(Q(j') = \max_{1 \leq l \leq j'} \{H(l)\}\) and \(Q(j) = \max_{1 \leq l \leq j} \{H(l)\}\). It follows from \(j' < j\) that \([l \mid 1 \leq l \leq j'] \subset [l \mid 1 \leq l \leq j]\). It follows then \(Q(j') \leq Q(j)\). This proves that the values of \(Q(j), 1 \leq j \leq n\) form a nondecreasing sequence. In the case of \(Q(j) < Q(j+1), 1 \leq j < n\), since \(Q(j+1)\) and \(Q(j)\) are both nonnegative integers, we have: \[ Q(j + 1) \geq Q(j) + 1 \] (3) On the other hand, by the definition of \(Q\), if current row number is \(i\), we have: \[ Q(j + 1) = \max_{1 \leq l \leq j} \{H_{i}(l)\} \] (4) \[ Q(j + 1) = \max_{1 \leq l \leq j} \{H_{i}(l)\} \] (5) \[ Q(j + 1) = \max_{1 \leq l \leq j} \{H_{i}(l)\} \] (6) Combining (3) and (6) we then have, \(Q(j+1) = Q(j)+1\). The proof is completed. **Example.** By the definition of \(Q\) we know, if current row number is \(i\), then for \(1 \leq j \leq n\), \[ Q(j) = \max_{1 \leq l \leq n} \{T(k, l)\} \] (7) At the end of the algorithm, all the \(n\) rows are treated. At this time, we have, for \(1 \leq j \leq n\), \[ Q(j) = \max_{1 \leq k \leq n} \{T(k, l)\} \] (8) In other words, \(Q(j) = r(X, Y[1 \ldots j])\), \(1 \leq j \leq n\). Especially, \(Q(n) = L = r(X, Y)\). If we want compute \(L = r(X, Y)\), but not \(LCS(X, Y)\), then we do not need to store the 2 dimensional array \(T\). At the end of the algorithm, \(Q(n)\) will return the answer. Because of its unusual form, \(Q\) can be viewed as a piece-wise linear function. As we know, it is sufficient to record the break points of such functions to calculate their values. Therefore, we can use another vector \(P\) of length at most \(L\) to record the break points of \(Q\). Let \(m = \max_{1 \leq i \leq n} \{Q(i)\}\). For \(1 \leq j \leq n\), the value of \(P(j)\) can be defined as follows: \[ P(j) = \begin{cases} \min_{1 \leq i \leq n} \{i \mid Q(i) = j\} & \text{if } j \leq m \\ \min_{1 \leq i \leq n} \{i \mid Q(i) = j\} + 1 & \text{otherwise} \end{cases} \] (9) \[ S(j) = P(j), \quad 1 \leq j \leq n \quad (10) \] It is clear that \( S \) forms an increasing sequence of length at most \( L \). For instance, if \( Q = (0, 1, 2, 2, 2, 2, 2) \), then \( P = (2, 3, 8, 8, 8, 8, 8, 8) \), and \( S = [2, 3] \). Let \( \alpha = |S| \), then \( S(\alpha) \) is the maximal element of \( S \). By the definition of \( S \), if \( k < \alpha \), then for any \( S(k) \leq j < S(k+1) \), we have \( Q(j) = k \). In the case of \( k = \alpha \), for any \( S(\alpha) \leq j \leq n \), we have \( Q(j) = \alpha \). Therefore, \( Q(j) \) can be easily computed by \( S \) as follows. \[ Q(j) = \begin{cases} k & \text{if } (0, S(\alpha) \leq j \leq S(k+1) \leq n) \\ \alpha & \text{if } j \geq S(\alpha) \end{cases} \quad (11) \] Furthermore, we can wind up the following fact. Fact 5: Suppose \( P(j), 1 \leq j \leq n \) be defined by formula (9). Then \( S = \{P(j)|1 \leq j \leq n, 1 \leq P(j) \leq n\} \) forms an increasing sequence of length at most \( L \). This sequence has a very unique property. For each \( P(t) \in S \), and any \( P(t) \leq j < P(t+1) \), \( t = \max_{1 \leq k \leq n} \{T(k, l)\} \), if current row number is \( i \). At the end of the algorithm, for each \( P(t) \in S \), \( t = r(X,Y[1 : j]) \) for any \( P(t) \leq j < P(t+1) \). Especially, the maximal element of \( S \) is \( P(L) \), and \( L = r(X,Y) \). Proof. By the definition of \( P \), we have, for each \( P(t) \in S \), if \( P(t) \leq j < P(t+1) \), then \( Q(j) = t \). Therefore, it follows from formula (7) that if current row number is \( i \), then \( t = \max_{1 \leq k \leq n} \{T(k, l)\} \). At the end of the algorithm, all the \( n \) rows are treated. At this time, for each \( P(t) \in S \), \( t = \max_{1 \leq k \leq n} \{T(k, l)\} \). Especially, if \( P(t') \) is the maximal element of \( S \), then \( P(t') \leq n < P(t' + 1) = n + 1 \), and thus, \( t' = r(X,Y[1 : n]) = r(X,Y) = L \), i.e., the maximal element of \( S \) is \( P(L) \), and \( L = r(X,Y) \). The proof is completed. \( \square \) In the algorithm, if current match \( i, j \) is processed, then the value of \( T(i,j) \) is changed to \( 1 + Q(j - 1) \). Let \( Q(j') \) be the successor of \( Q(j) - 1 \) in \( Q \), i.e., \[ j' = \min \left\{ j \mid Q(j) > Q(j - 1) \right\} \quad (12) \] Then \( Q(j : j' - 1) \) must be changed to \( 1 + Q(j - 1) \), according to the definition of \( Q \). Similarly, Let \( S(k) \) be the successor of \( j - 1 \) in \( S \), i.e., \[ k = \min \left\{ j \mid S(j) > j - 1 \right\} \quad (13) \] Then \( S(k) \) must be changed to \( j \), according to the definition of \( S \). In the case of \( j - 1 \) has no successor in \( S \), i.e., \( j - 1 \geq S(\alpha) \), then \( j \) must be added into \( S \). For example, if \( Q = (0, 1, 2, 2, 2, 2, 2, 2) \), \( S = (2, 3) \), and current match \( (4, 6) \) is processed, then \( T(4, 6) \) is changed to \( 1 + Q(j - 1) = 3 \). In this case, \( j = 6 \) and \( j' = 8 \), and thus \( Q(6 : 7) \) must be replaced by \( 3 \). The current values of \( Q \) becomes \( Q = (0, 1, 2, 2, 2, 3, 3) \). At this point, \( j - 1 = 5 \geq S(\alpha) = 3 \), and thus \( j \) must be added to \( S \). The current values of \( S \) becomes \( S = (2, 3, 6) \). C. The improved algorithm It is readily seen from the discussions above that if we can use the ordered set \( S \) defined by formula (11) to calculate the function \( RMQ(1, j - 1) \), then the algorithm will be simplified substantially. The key point is the way to maintain the ordered set \( S \) efficiently. Let \( U = \{ j | 1 \leq j \leq n \} \). Suppose \( DS \) be an abstract data type on an ordered positive integer set \( S \). The abstract data type \( DS \) can support the following operations on \( S \): 1) \( Size(S) \) A query on an ordered positive integer set \( S \) that returns the number of integers in \( S \). 2) \( Succ(S,x) \) A query that, given a positive integer \( x \) whose key is from \( U \), returns the next larger integer in \( S \), or \( 0 \) if \( x \) is the maximum integer in \( S \). 3) \( Pred(S,x) \) A query that, given a positive integer \( x \) whose key is from \( U \), returns the next smaller integer in \( S \), or \( 0 \) if \( x \) is the minimum integer in \( S \). 4) \( Update(S,x) \) A modifying operation that, given a positive integer \( x \), if \( Succ(S,x - 1) > 0 \), then replace \( Succ(S,x - 1) \) with the integer \( x \), otherwise augments the set \( S \) with a new integer \( x \). With this abstract data type, we can maintain the ordered positive integer set \( S \subseteq U \) defined by formula (10) in our new algorithm \( LCS \) as follows. Algorithm 2 LCS 1: \( S \leftarrow \emptyset \) 2: for \( i = 1 \) to \( n \) do 3: \( \text{for all } j \in L_Y(x_i) \) do 4: \( \text{Update}(S,j) \) 5: end for 6: end for 7: return \( Size(S) \) In above algorithm \( LCS \), the list \( L_Y(c), c \in \Sigma \), in a decreasing order, the positions of \( c \) in \( Y \). The \( |\Sigma| \) lists can be constructed in \( O(n) \) time, by simply scanning \( Y \) in turn. At the end of the algorithm, \( L = r(X,Y) = Size(S) \), the length of \( LCS(X,Y) \), is returned. The efficiency of the new algorithm is depended heavily on the efficiency of the abstract data type \( DS \), especially on the efficiency of its operation \( \text{Update}(S,x) \). We have found that the van Emde Boas tree is an elegant data structure for our purpose. Specifically, van Emde Boas trees support each of the following dynamic set operations, \( \text{Search}, \text{Insert}, \text{Delete}, \text{Min}, \text{Max}, \text{Succ}, \) and \( \text{Pred} \) in \( O(\log \log n) \) time. The operation \( \text{Update}(S,x) \) can be easily implemented by combining at most two successive operations \( \text{delete} \) and \( \text{insert} \). If we chose van Emde Boas tree as our data structure for \( S \), the new algorithm can be described as follows. The structure of algorithm \( vEB - LCS \) is very simple. Although the algorithm can correctly return the length of \( LCS(X,Y) \), it does not directly give \( LCS(X,Y) \). If we want to compute \( LCS(X,Y) \), but not just its length, we have to record more information. A commonly used method is to Algorithm 3 \texttt{vEB\_LCS} 1: \texttt{S} $\leftarrow \emptyset$ 2: \texttt{for} $i = 1$ to $n$ 3: \hspace{1em} \texttt{for all} $j \in L_Y(x_i)$ \texttt{do} 4: \hspace{2em} $k$ $\leftarrow$ Succ($S, j - 1$) 5: \hspace{2em} \texttt{if} $k < \text{Max}(S)$ \texttt{then} 6: \hspace{3em} Delete($S, k$) 7: \hspace{1em} \texttt{end if} 8: \hspace{1em} Insert($S, j$) 9: \texttt{end for} 10: \texttt{return} Size($S$) Algorithm 4 \texttt{vEB\_LCS} 1: \texttt{m} $\leftarrow 0$, \texttt{S} $\leftarrow \emptyset$ 2: \texttt{for} $i = 1$ to $n$ 3: \hspace{1em} \texttt{for all} $j \in L_Y(x_i)$ \texttt{do} 4: \hspace{2em} $k$ $\leftarrow$ Succ($S, j - 1$) 5: \hspace{2em} \texttt{if} $k < \text{Max}(S)$ \texttt{then} 6: \hspace{3em} Delete($S, k$) 7: \hspace{1em} \texttt{end if} 8: \hspace{1em} Insert($S, j$) 9: \hspace{1em} $p$ $\leftarrow$ Pred($S, j$) 10: \hspace{1em} $m$ $\leftarrow$ $m + 1$ 11: \hspace{1em} $B(m) \leftarrow D(p)$, $C(m) \leftarrow j$, $D(j) \leftarrow m$ 12: \hspace{1em} \texttt{end for} 13: \texttt{end for} 14: \texttt{return} Size($S$) In the above algorithm, the vector \texttt{D} is a temporary vector of length at most \texttt{L} used to store the match numbers for current set \texttt{S}. With the two vectors \texttt{B} and \texttt{C} computed in the above algorithm, the following recursive algorithm prints out LCS($X, Y$). The initial call is Print – LCS($\text{Size}(S)$). Algorithm 5 \texttt{Print\_LCS}(k) 1: \texttt{if} $k \leq 0$ \texttt{then} 2: \hspace{1em} \texttt{return} 3: \texttt{else} 4: \hspace{1em} \texttt{Print} – LCS($B(k)$) 5: \hspace{1em} \texttt{print} $Y(C(k))$ 6: \hspace{1em} \texttt{end if} It is obvious that \texttt{Print} – LCS($\text{Size}(S)$) takes time $O(\texttt{L})$, since it prints one character of LCS($X, Y$) in each recursive call. Finally, we can find that the following theorem holds. Theorem 1: The algorithm \texttt{vEB\_LCS} correctly computes LCS($X, Y$) in $O(R\log \log n + n)$ time and $O(R)$ space in the worst case, where $R$ is the total number of matches for $X$ and $Y$. Proof. It follows from formulas (11) and (13) that the values of RMQ($1, j - 1$) for each row $i$ can be correctly computed by the set \texttt{S} maintained in the algorithm. Therefore, the algorithm can compute LCS($X, Y$) correctly as the original algorithm of Iliopoulos and Rahman. It is obvious that the computation of list $L_Y(c), c \in \Sigma$, costs $O(n)$ time and space. For each match $(i, j) \in M$, the algorithm executes each of the 4 operations Succ, Succ, Succ, and Succ at most once, and each of the 4 operations costs $O(\log \log n)$. Therefore, the total time spent for these operations is $O(R\log \log n)$. The worst case time complexity of the algorithm is therefore $O(R\log \log n + n)$. To maintain the van Emde Boas tree, $O(n)$ space is sufficient. To reconstruct the LCS($X, Y$), the algorithm uses two vectors $B$ and $C$, both of size $R$. The space required by the algorithm is thus $O(R)$. The worst case space complexity of the algorithm is therefore $O(R)$. The proof is completed. □ If we chose a balanced binary search tree such as red-black tree as our data structure for the ordered positive integer set $S$, the following dynamic set operations, Search, Insert, Delete, Min, Max, Succ, and Pred can be implemented in $O(\log |S|)$ time. In this case, the time complexity of our algorithm becomes $O(R\log L)$, since $|S| \leq L$. We then can find that the following theorem holds. Theorem 2: The longest common subsequence problem can be solved in $O(R\log L + n)$ time and $O(R)$ space in the worst case, where $n, L$ and $R$ are the length of input sequences $X$ and $Y$, the length of LCS($X, Y$), and the total number of matches for $X$ and $Y$, respectively. The ordered positive integer set $S$ in our algorithm can also be efficiently supported by an ordered vector $s$ of length at most $L$ as follows. Algorithm 6 \texttt{V\_LCS} 1: \texttt{a} $\leftarrow 0$, \texttt{k} $\leftarrow -1$ 2: \texttt{for} $i = 1$ to $n$ 3: \hspace{1em} \texttt{for all} $j \in L_Y(x_i)$ \texttt{do} 4: \hspace{2em} \texttt{while} $k \geq 0$ \texttt{and} $s(k) \geq j$ \texttt{do} 5: \hspace{3em} $k$ $\leftarrow$ $k - 1$ 6: \hspace{2em} \texttt{end while} 7: \hspace{2em} $s(k + 1) \leftarrow j$ 8: \hspace{2em} \texttt{if} $k = \alpha$ \texttt{then} 9: \hspace{3em} $\alpha$ $\leftarrow$ $1 + \alpha$ 10: \hspace{2em} \texttt{end if} 11: \hspace{1em} $k$ $\leftarrow$ \texttt{a} 12: \hspace{1em} \texttt{end for} 13: \texttt{end for} 14: \texttt{return} \texttt{a} In the above algorithm, for each row $i$, all columns $j \in L_Y(x_i)$ are processed in a decreasing order. The successors of all $j - 1$ in $s$ are searched and updated also in a decreasing order from the largest element $s(\alpha)$. It is obvious that the time spent for each row $i$ is $O(\alpha)$. Therefore, we can conclude that the time complexity of the above algorithm is $O(nL)$, since $\alpha \leq L$. Theorem 3: The longest common subsequence problem can be solved in $O(nL)$ time and $O(R)$ space in the worst. case, where \( n \) and \( L \) are the length of input sequences \( X \) and \( Y \), and the length of \( LCS(X,Y) \), respectively. **REFERENCES**
{"Source-Url": "http://www.iaeng.org/IJCS/issues_v44/issue_2/IJCS_44_2_05.pdf", "len_cl100k_base": 9129, "olmocr-version": "0.1.50", "pdf-total-pages": 6, "total-fallback-pages": 0, "total-input-tokens": 28749, "total-output-tokens": 10899, "length": "2e13", "weborganizer": {"__label__adult": 0.0005297660827636719, "__label__art_design": 0.0003809928894042969, "__label__crime_law": 0.0007395744323730469, "__label__education_jobs": 0.0012521743774414062, "__label__entertainment": 0.0001575946807861328, "__label__fashion_beauty": 0.00027060508728027344, "__label__finance_business": 0.0004436969757080078, "__label__food_dining": 0.000720977783203125, "__label__games": 0.0014104843139648438, "__label__hardware": 0.0020198822021484375, "__label__health": 0.001995086669921875, "__label__history": 0.0005135536193847656, "__label__home_hobbies": 0.00021755695343017575, "__label__industrial": 0.0007920265197753906, "__label__literature": 0.0005016326904296875, "__label__politics": 0.0004551410675048828, "__label__religion": 0.0009455680847167968, "__label__science_tech": 0.27685546875, "__label__social_life": 0.00015592575073242188, "__label__software": 0.00875091552734375, "__label__software_dev": 0.69921875, "__label__sports_fitness": 0.000591278076171875, "__label__transportation": 0.00086212158203125, "__label__travel": 0.0003056526184082031}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 29860, 0.04191]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 29860, 0.5742]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 29860, 0.81314]], "google_gemma-3-12b-it_contains_pii": [[0, 5102, false], [5102, 11991, null], [11991, 15838, null], [15838, 22163, null], [22163, 27262, null], [27262, 29860, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5102, true], [5102, 11991, null], [11991, 15838, null], [15838, 22163, null], [22163, 27262, null], [27262, 29860, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 29860, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 29860, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 29860, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 29860, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 29860, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 29860, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 29860, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 29860, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 29860, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 29860, null]], "pdf_page_numbers": [[0, 5102, 1], [5102, 11991, 2], [11991, 15838, 3], [15838, 22163, 4], [22163, 27262, 5], [27262, 29860, 6]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 29860, 0.0]]}
olmocr_science_pdfs
2024-11-30
2024-11-30
ad6525069537d9bbd481d8c64384728005a07c51
Chapter 13: Handling Floating Point Data This chapter presents a brief discussion of floating point data and arithmetic. There are a few reasons to cover this topic, but none relate to the expectation that a programmer will actually use this data format in an assembly language program. The two primary reasons to cover floating point data and arithmetic are simple: 1) So that we can make a plausible claim of a complete coverage of assembler language. 2) So that the student will more fully appreciate some of the complexities (handled by the run–time system of a HLL) of processing floating point data. There is another reason for the study; this is one that is found in early texts on assembler language. It used to be the case that an understanding of floating point format would allow the programmer to write a High–Level–Language program that was considerably more efficient. With modern compilers, this is rarely the case. The first thing to note in this chapter is the difference between floating point data and fixed point data. It is simple: in the first format the decimal point may be said to float in that it can assume any position in the data. In the fixed point data, the decimal point is fixed at a predefined position. The packed decimal format is a good example of a fixed–point format. Consider the two packed decimal numbers defined as follows: \[ \begin{align*} N1 & \quad DC \ P'1234' \quad \text{Stored as X'01234C'} \\ N2 & \quad DC \ P'567' \quad \text{Stored as X'567C'} \end{align*} \] From the viewpoint of assembler language, each of these labels is simply a reference to data in packed decimal format. There is more to the definition than what is stated above. One must view each declaration in terms of a data type, which is a concept taken from a HLL. In particular, the data are defined completely only if the number of decimal places is specified. So, we must ask if the numbers represented by the labels \( N1 \) and \( N2 \) are of compatible data type. Again, this cannot be determined from the simple definition. If both values are to be interpreted with the same number of decimal points, the types are compatible. Suppose that \( N1 \) represents the number 12.34. Suppose that \( N2 \) represents the number 5.67. The two definitions can be viewed as belonging to a single data type. Suppose, however that \( N1 \) represents the number 1.234, while \( N2 \) represents 5.67. Then the definitions belong to what might be called similar, but incompatible, data types. One of the two must be modified by a \texttt{SRP} instruction before they are added, or the results will be silly. One possible redefinition would be as follows: \[ \begin{align*} N1A & \quad DC \ P'1234' \quad \text{Stored as X'01234C'} \text{ for 1.234} \\ N2A & \quad DC \ P'5670' \quad \text{Stored as X'05670C'} \text{ for 5.670} \end{align*} \] In the above definition, each constant is defined with three implicit decimal places, and the two can be said to be of a common data type. We must emphasize that the idea of a data type is derived from the theory of high–level compiled languages and is somewhat foreign to assembler language. However, it is very helpful in understanding fixed point arithmetic. The basic idea of floating point arithmetic is the explicit storage of a representation of the position of the decimal point in each data item. That way, the CPU can automatically adjust the two to the same basic representation, if that is necessary. As we shall see, this adjustment is required for addition and subtraction, but not multiplication and division. Consider the above two numbers at labels **N1** and **N2**. Suppose that these are to be interpreted as 1.234 and 56.7 respectively. In floating-point notation, these would be represented as $1.234 \times 10^0$ and $5.67 \times 10^1$, respectively. Addition might proceed by converting these to $1.234 \times 10^0$ and $56.7 \times 10^0$, then adding to get $57.934 \times 10^0$, which might be converted to either $5.7934 \times 10^1$ or $5.793 \times 10^1$. Multiplication will proceed without adjusting either value: $1.234 \times 10^0 \times 5.67 \times 10^1 = 6.99678 \times 10^1$, which might be rounded to $7.00 \times 10^1$, $6.997 \times 10^1$, or some other value. As noted before, the floating point format has an advantage, which is simultaneously its disadvantage. The advantage is that the format handles the position of the decimal point explicitly. The disadvantage is that it might round and thereby lose precision. At this point, the reader should review the material on floating point formats that is found in Chapter 4 (Data Representation) of this textbook. The topics for review should be: 1. Conversion between decimal format and hexadecimal representations, 2. Excess–64 representation of integers, 3. normalized and denormalized floating point numbers, and 4. the IBM Mainframe floating point formats. For the reader’s convenience, the last topic will be summarized below. **The IBM Mainframe Floating-Point Formats** In this discussion, we shall adopt the bit numbering scheme used in the IBM documentation, with the leftmost (sign) bit being number 0. The IBM Mainframe supports three formats; those representations with more bits can be seen to afford more precision. - **Single precision** 32 bits numbered 0 through 31, - **Double precision** 64 bits numbered 0 through 63, and - **Extended precision** 128 bits numbered 0 through 127. As in the IEEE–754 standard, each floating point number in this standard is specified by three fields: the sign bit, the exponent, and the fraction. Unlike the IEEE–754 standard, the IBM standard allocates the same number of bits for the exponent of each of its formats. The bit numbers for each of the fields are shown below. <table> <thead> <tr> <th>Format</th> <th>Sign bit</th> <th>Bits for exponent</th> <th>Bits for fraction</th> </tr> </thead> <tbody> <tr> <td>Single precision</td> <td>0</td> <td>1–7</td> <td>8–31</td> </tr> <tr> <td>Double precision</td> <td>0</td> <td>1–7</td> <td>8–63</td> </tr> <tr> <td>Extended precision</td> <td>0</td> <td>1–7</td> <td>8–127</td> </tr> </tbody> </table> Note that each of the three formats uses eight bits to represent the exponent, in what is called the **characteristic field**, and the sign bit. These two fields together will be represented by two hexadecimal digits in a one–byte field. The size of the fraction field does depend on the format. - Single precision 24 bits 6 hexadecimal digits, - Double precision 56 bits 14 hexadecimal digits, and - Extended precision 120 bits 30 hexadecimal digits. The Characteristic Field In IBM terminology, the field used to store the representation of the exponent is called the “characteristic”. This is a 7–bit field, used to store the exponent in excess–64 format; if the exponent is E, then the value (E + 64) is stored as an unsigned 7–bit number. Recalling that the range for integers stored in 7–bit unsigned format is 0 ≤ N ≤ 127, we have 0 ≤ (E + 64) ≤ 127, or −64 ≤ E ≤ 63. Range for the Standard We now consider the range and precision associated with the IBM floating point formats. The reader should remember that the range is identical for all of the three formats; only the precision differs. The range is usually specified as that for positive numbers, from a very small positive number to a large positive number. There is an equivalent range for negative numbers. Recall that 0 is not a positive number, so that it is not included in either range. Given that the base of the exponent is 16, the range for these IBM formats is impressive. It is from somewhat less than 16−64 to a bit less than 1663. Note that 1663 = (24)63 = 2252, and 16−64 = (24)−64 = 2−256 = 1.0 / (2256) and recall that log10(2) = 0.30103. Using this, we compute the maximum number storable at about (100.30103)252 = 1075.86 ≈ 9·1075. We may approximate the smallest positive number at 1.0 / (36·1077) or about 3.0·10−77. In summary, the following real numbers can be represented in this standard: X = 0.0 and 3.0·10−77 < X < 9·1075. One would not expect numbers outside of this range to appear in any realistic calculation. Precision for the Standard Unlike the range, which depends weakly on the format, the precision is very dependent on the format used. More specifically, the precision is a direct function of the number of bits used for the fraction. If the fraction uses F bits, the precision is 1 part in 2F. We can summarize the precision for each format as follows. <table> <thead> <tr> <th>Format</th> <th>Type</th> <th>Positive Range</th> <th>Precision</th> </tr> </thead> <tbody> <tr> <td>Single Precision</td> <td>E</td> <td>3.0·10−77 &lt; X &lt; 9·1075</td> <td>7 digits</td> </tr> <tr> <td>Double Precision</td> <td>D</td> <td>3.0·10−77 &lt; X &lt; 9·1075</td> <td>16 digits</td> </tr> <tr> <td>Extended Precision</td> <td>L</td> <td>3.0·10−77 &lt; X &lt; 9·1075</td> <td>36 digits</td> </tr> </tbody> </table> The argument for precision is quite simple. Consider the single precision format, which is more precise than 1 part in 10,000,000 and less precise than 1 part in 100,000,000. In other words it is better than 1 part in 107, but not as good as 1 in 108; hence we say 7 digits. Range and Precision We now summarize the range and precision for the three IBM Mainframe formats. Representation of Floating Point Numbers As with the case of integers, we shall most commonly use hexadecimal notation to represent the values of floating-point numbers stored in the memory. From this point, we shall focus on the two more commonly used formats: Single Precision and Double Precision. The single precision format uses a 32–bit number, represented by 8 hexadecimal digits. The double precision format uses a 64–bit number, represented by 16 hexadecimal digits. Due to the fact that the two formats use the same field length for the characteristic, conversion between the two is quite simple. To convert a single precision value to a double precision value, just add eight hexadecimal zeroes. Consider the positive number 128.0. As a single precision number, the value is stored as 4280 0000. As a double precision number, the value is stored as 4280 0000 0000 0000. Conversions from double precision to single precision format will involve some rounding. For example, consider the representation of the positive decimal number 123.45. In a few pages, we shall show that it is represented as follows. As a double precision number, the value is stored as 427B 7333 3333 3333. As a single precision number, the value is stored as 427B 7333. The Sign Bit and Characteristic Field We now discuss the first two hexadecimal digits in the representation of a floating–point number in these two IBM formats. In IBM nomenclature, the bits are allocated as follows. <table> <thead> <tr> <th>Bit Number</th> <th>0</th> <th>1</th> <th>2</th> <th>3</th> <th>4</th> <th>5</th> <th>6</th> <th>7</th> </tr> </thead> <tbody> <tr> <td>Hex digit</td> <td>0</td> <td></td> <td></td> <td>1</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Use</td> <td>Sign bit</td> <td>Characteristic (Exponent + 64)</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> Consider the four bits that comprise hexadecimal digit 0. The sign bit in the floating–point representation is the “8 bit” in that hexadecimal digit. This leads to a simple rule. If the number is not negative, bit 0 is 0, and hex digit 0 is one of 0, 1, 2, 3, 4, 5, 6, or 7. If the number is negative, bit 0 is 1, and hex digit 0 is one of 8, 9, A, B, C, D, E, or F. Some Single Precision Examples We now examine a number of examples, using the IBM single–precision floating–point format. The reader will note that the methods for conversion from decimal to hexadecimal formats are somewhat informal, and should check previous notes for a more formal method. Note that the first step in each conversion is to represent the magnitude of the number in the required form X●10^E, after which we determine the sign and build the first two hex digits. Example 1: True 0 The number 0.0, called “true 0” by IBM, is stored as all zeroes [R_15, page 41]. In single precision it would be 0000 0000. In double precision it would be 0000 0000 0000 0000. Example 2: Positive exponent and positive fraction. The decimal number is 128.50. The format demands a representation in the form X\(\cdot\)16^E, with 0.625 \(\leq\) X \(<\) 1.0. As 128 \(\leq\) X \(<\) 256, the number is converted to the form X\(\cdot\)16^2. Note that 128 = (1/2)\(\cdot\)16^2 = (8/16)\(\cdot\)16^2, and 0.5 = (1/512)\(\cdot\)16^2 = (8/4096)\(\cdot\)16^2. Hence, the value is 128.50 = (8/16 + 0/256 + 8/4096)\(\cdot\)16^2; it is 16^2\(\cdot\)0x0.808. The exponent value is 2, so the characteristic value is either 66 or 0x42 = 100 0010. The first two hexadecimal digits in the eight digit representation are formed as follows. <table> <thead> <tr> <th>Field</th> <th>Sign</th> <th>Characteristic</th> </tr> </thead> <tbody> <tr> <td>Value</td> <td>0</td> <td>0 0 0 1 0 0 0 0</td> </tr> <tr> <td>Hex value</td> <td>4</td> <td>2</td> </tr> </tbody> </table> The fractional part comprises six hexadecimal digits, the first three of which are 808. The number 128.50 is represented as 4280 8000. Example 3: Positive exponent and negative fraction. The decimal number is the negative number –128.50. At this point, we would normally convert the magnitude of the number to hexadecimal representation. This number has the same magnitude as the previous example, so we just copy the answer; it is 16^2\(\cdot\)0x0.808. We now build the first two hexadecimal digits, noting that the sign bit is 1. <table> <thead> <tr> <th>Field</th> <th>Sign</th> <th>Characteristic</th> </tr> </thead> <tbody> <tr> <td>Value</td> <td>1</td> <td>0 0 0 1 0 0 0 0</td> </tr> <tr> <td>Hex value</td> <td>C</td> <td>2</td> </tr> </tbody> </table> The number 128.50 is represented as c280 8000. Note that we could have obtained this value just by adding 8 to the first hex digit. Example 4: Negative exponent and positive fraction. The decimal number is 0.375. As a fraction, this is 3/8 = 6/16. Put another way, it is 16^0\(\cdot\)0.375 = 16^0\(\cdot\)(6/16). This is in the required format X\(\cdot\)16^E, with 0.625 \(\leq\) X \(<\) 1.0. The exponent value is 0, so the characteristic value is either 64 or 0x40 = 100 0000. The first two hexadecimal digits in the eight digit representation are formed as follows. <table> <thead> <tr> <th>Field</th> <th>Sign</th> <th>Characteristic</th> </tr> </thead> <tbody> <tr> <td>Value</td> <td>0</td> <td>0 0 0 0 0 0 0 0</td> </tr> <tr> <td>Hex value</td> <td>4</td> <td>0</td> </tr> </tbody> </table> The fractional part comprises six hexadecimal digits, the first of which is a 6. The number 0.375 is represented in single precision as 4060 0000. The number 0.375 is represented in double precision as 4060 0000 0000 0000. **Example 5: A Full Conversion** The number to be converted is 123.45. As we have hinted, this is a non-terminator. Convert the integer part. \[ \begin{align*} 123 \div 16 &= 7 \text{ with remainder } 11 \text{ this is hexadecimal digit B.} \\ 7 \div 16 &= 0 \text{ with remainder } 7 \text{ this is hexadecimal digit 7.} \end{align*} \] Reading bottom to top, the integer part converts as 0x7B. Convert the fractional part. \[ \begin{align*} 0.45 \cdot 16 &= 7.20 \text{ Extract the 7,} \\ 0.20 \cdot 16 &= 3.20 \text{ Extract the 3,} \\ 0.20 \cdot 16 &= 3.20 \text{ Extract the 3,} \\ 0.20 \cdot 16 &= 3.20 \text{ Extract the 3, and so on.} \end{align*} \] In the standard format, this number is \(16^2\cdot0x0.7B33333333\ldots\). The exponent value is 2, so the characteristic value is either 66 or 0x42 = 100 0010. The first two hexadecimal digits in the eight digit representation are formed as follows. <table> <thead> <tr> <th>Field</th> <th>Sign</th> <th>Characteristic</th> </tr> </thead> <tbody> <tr> <td>Value</td> <td>0 0 0 0</td> <td>1 0 0 1 0</td> </tr> <tr> <td>Hex value</td> <td>4</td> <td>2</td> </tr> </tbody> </table> The number 123.45 is represented in single precision as \(427B\; 3333\). The number 0.375 is represented in double precision as \(427B\; 3333\; 3333\; 3333\). **Example 5: One in “Reverse”** We are given the single precision representation of the number. It is 4110 0000. What is the value of the number stored? We begin by examination of the first two hex digits. <table> <thead> <tr> <th>Field</th> <th>Sign</th> <th>Characteristic</th> </tr> </thead> <tbody> <tr> <td>Value</td> <td>0 0 0 0</td> <td>1 0 0 0 0 1</td> </tr> <tr> <td>Hex value</td> <td>4</td> <td>1</td> </tr> </tbody> </table> The sign bit is 0, so the number is positive. The characteristic is 0x41, so the exponent is 1 and the value may be represented by \(X\cdot16^1\). The fraction field is 100 000, so the value is \(16^{-2}\cdot(1/16) = 1.0\). **Example 6: Another in “Reverse”** We are given the single precision representation of the number. It is BEC8 0000. What is the value of the number stored? We begin by examination of the first two hex digits. <table> <thead> <tr> <th>Field</th> <th>Sign</th> <th>Characteristic</th> </tr> </thead> <tbody> <tr> <td>Value</td> <td>1 0 1 1 1 1 1 0</td> <td></td> </tr> <tr> <td>Hex value</td> <td>B</td> <td>E</td> </tr> </tbody> </table> The characteristic has value 0x3E or decimal 3\cdot16 + 14 = 62. The exponent has value 62 – 64 = –2. The number is then \(16^{-2}\cdot0x0.C8 = 16^{-2}\cdot(12/16 + 8/256)\), which can be converted to decimal in any number of ways. I prefer the following conversion. \[ 16^{-2}\cdot(12/16 + 8/256) = 16^{-2}\cdot(3/4 + 1/32) = 16^{-2}\cdot(24/32 + 1/32) = 16^{-2}\cdot(25/32) = 25 / (32\cdot256) = 25 / 8192 \approx 3.0517578\cdot10^{-3}. \] The answer is approximately the negative number \(-3.0517578\cdot10^{-3}\). Why Excess–64 Notation for the Exponent? We have introduced two methods to be used for storing signed integers: two’s–complement notation and excess–64 notation. One might well ask why two’s-complement notation is not used to store the exponent in the characteristic field. The answer for integer notation is simple. Consider some of examples. - 128.50 is represented as 4280 8000. Viewed as a 32–bit integer, this is positive. - -128.50 is represented as C280 8000. Viewed as a 32–bit integer, this is negative. - 1.00 is represented as 4110 0000. Viewed as a 32–bit integer, this is positive. - -3.05×10^{-3} is represented as BEC8 0000. Viewed as a 32–bit integer, this is negative. It turns out that the excess–64 notation allows the use of the integer compare unit to compare floating point numbers. Consider two floating point numbers X and Y. Pretend that they are integers and compare their bit patterns as integer bit patterns. It viewed as an integer, X is less than Y, then the floating point number X is less than the floating point Y. Note that we are not converting the numbers to integer form, just looking at the bit patterns and pretending that they are integers. For example, the above examples would yield the following order. - 4280 8000 for 128.50. This is the largest. - 4110 0000 for 1.00. - BEC8 0000 for -3.05×10^{-3}. - C280 8000 for -128.50. This is the most small (most negative). Examples of Floating–Point Declaratives Floating point storage and constants are defined with the standard DS and DC declaratives. There are three possible formats: E (Single Precision), D (Double Precision) and L (Extended Precision). Standard programs use the E (Single Precision) format, with occasional use of the D (Double Precision) format. The L format is probably unusual. Here are some examples of floating–point declaratives. | FL1 | DS E | This defines a 4–byte storage area, aligned on a fullword boundary. Presumably, it will store Single Precision Data. | | DL1 | DS D | An 8–byte storage area, aligned on a double word boundary. It could store data in Double Precision format. | | FL2 | DS E ‘12.34’ | Define a single precision value. | | FL3 | DS E ‘–12.34’ | The negative of the above value. | | DL2 | DS D ‘0.0’ | The constant 0.0, in double precision. | The reader may recall that we have used statements, such as the DL1 declarative, to reserve an 8–byte storage area aligned on a double–word boundary, for use in the CVB and CVD instructions associated with packed decimal arithmetic. This emphasizes the fact that the declaratives do not really determine a data type, but just set aside storage. In assembler language, it is the instructions that determine the data type. Before proceeding, we must give a disclaimer. There are a few features of floating-point arithmetic, such as the exponent modifier and scale modifier, that will not be covered in this discussion. This discussion will also be limited to normalized floating-point numbers and totally ignore the unnormalized instructions which handle data not in normalized format. The Floating-Point Registers In addition to the sixteen general-purpose registers (used for binary integer arithmetic), the S/360 architecture provides four registers dedicated for floating-point arithmetic. These registers are numbered 0, 2, 4, and 6(*). Each is a 64–bit register. It is possible that the use of even numbers to denote these registers is to emphasize that they are not 32–bit registers. The use of the registers by the floating-point operations depends on the precision. - Single precision formats use the leftmost 32 bits of a floating-point register. - Double precision formats use all 64 bits of the register. - Extended precision formats use two adjacent registers for a 128 bit number. In order to understand why it is the leftmost 32 bits of the register that are used for the 32–bit single precision floating-point format, we must consider what is involved in extending the single precision format to a double precision format. Consider the single–precision constant 123.45, which would be represented by the 32–bit (8 hexadecimal digit) constant $427B \ 3333$. Were this to be extended to double precision, it would be stored as the 64–bit constant $427B \ 3333 \ 0000 \ 0000$. In other words, each floating point register stores a value as if it were a double–precision value; the single–precision values being stored as values with limited precision. As we saw above, a conversion of 123.45 directly to the double–precision floating–point format would yield the value $427B \ 3333 \ 3333 \ 3333$, rather than the truncated value $427B \ 3333 \ 0000 \ 0000$ seen above. Put another way, single–precision values stored as double precision are not as precise as true double–precision constants. To make this point completely obvious, suppose that a 64–bit floating–point register contains the following value, expressed as 16 hexadecimal digits. <table> <thead> <tr> <th>Byte</th> <th>0</th> <th>1</th> <th>2</th> <th>3</th> <th>4</th> <th>5</th> <th>6</th> <th>7</th> </tr> </thead> <tbody> <tr> <td>Value</td> <td>42</td> <td>7B</td> <td>33</td> <td>33</td> <td>33</td> <td>33</td> <td>33</td> <td>33</td> </tr> </tbody> </table> An E format (Single Precision) floating-point reference to this register would access only the leftmost four bytes and use the value $427B \ 3333$. A D format (Double Precision) floating-point reference would access all eight bytes and use the value $427B \ 3333 \ 3333 \ 3333$. Each reference should correspond to the decimal value 123.45, just with different precision. As a side note, some early versions of FORTRAN might print the above number at something like 123.449999, due to the fact that 123.45 cannot be represented exactly as a floating–point number. The FORMAT statement provided by the FORTRAN run–time system was modified to round this value to 123.45. * Modern System/z architecture supports 16 floating–point registers, numbered 0 – 15. The additional registers (1, 3, 5, and 7 – 15) are useable if the AFPR option has been selected in the ACONTROL instruction for the code. [R-17, page 100] The Floating–Point Instructions The floating–point instruction set is less extensive than the binary integer instruction set, but bears some similarities. The instructions are in two formats: RR (Register to Register) and RX (Register and Indexed Storage). Obviously the register reference in these instructions are the floating–point registers. The mnemonics for the instructions are structured into three parts: a one or two character code for the operation, followed by a character indicating the precision, then either a blank for type RX or an ‘R’ for type RR. The Load Instructions The load instructions load a 64–bit floating point register from either storage or another floating–point register. The valid register numbers are 0, 2, 4, or 6. **LE R1,D2(X2,B2)** Load R1 single precision from memory Operand 2 is an aligned fullword; it's address is a multiple of 4. **LD R1,D2(X2,B2)** Load R1 double precision from memory Operand 2 is an aligned double word; it's address is a multiple of 8. **LER R1,R2** Load the leftmost 32 bits of R1 from the leftmost 32 bits of R2. **LDR R1,R2** Load the 64–bit register R1 from the 64–bit register R2. Neither LE or LER change the rightmost 32 bits of the target floating–point register. The opcodes for the two type RR instructions are as follows: LE R1,D2(X2,B2) X '38' LD R1,D2(X2,B2) X '28' The object code format for these type RR instructions follows the standard. Each is a two–byte instruction of the form OP R1,R2. <table> <thead> <tr> <th>Type</th> <th>Bytes</th> <th>Operands</th> </tr> </thead> <tbody> <tr> <td>RR</td> <td>2</td> <td>R1,R2</td> </tr> <tr> <td>OP</td> <td>R1,R2</td> <td></td> </tr> </tbody> </table> The first byte contains the 8–bit instruction code. The second byte contains two 4–bit fields, each of which encodes a register number. This instruction format is used to process data between registers. The opcodes for the two type RX instructions are as follows: LE R1,D2(X2,B2) X '78' LD R1,D2(X2,B2) X '68' Each is a four–byte instruction of the form OP R1,D2(X2,B2). <table> <thead> <tr> <th>Type</th> <th>Bytes</th> <th>Operands</th> </tr> </thead> <tbody> <tr> <td>RX</td> <td>4</td> <td>R1,D2(X2,B2)</td> </tr> <tr> <td>OP</td> <td>R1,X2</td> <td>B2,D2</td> </tr> </tbody> </table> The first byte contains the 8–bit instruction code. The second byte contains two 4–bit fields, each of which encodes a register number. The third and fourth bytes contain an address in the standard base/displacement with index register format. The load instructions do not set any condition code. The Store Instructions There are two store instructions for storing either the leftmost 32 bits or all 64 bits of the 64 bit floating–point registers. Again, the valid register numbers are 0, 2, 4, or 6. STE R1,D2(X2,B2) Store the 32 leftmost bits of register R1 as a single precision result into the aligned fullword address. STD R1,D2(X2,B2) Store the 64 bits of register R1 as a double precision result into the aligned double word address. The opcodes for these two instructions are as follows: STE X'70' STD X'60'. Each is a four–byte instruction of the form OP R1,D2(X2,B2). <table> <thead> <tr> <th>Type</th> <th>Bytes</th> <th>Operands</th> <th>1</th> <th>2</th> <th>3</th> <th>4</th> </tr> </thead> <tbody> <tr> <td>RX</td> <td>4</td> <td>R1,D2(X2,B2)</td> <td>OP</td> <td>R1</td> <td>X2</td> <td>B2 D2</td> </tr> </tbody> </table> The first byte contains the 8–bit instruction code. The second byte contains two 4–bit fields, each of which encodes a register number. The third and fourth bytes contain an address in the standard base/displacement with index register format. The rules for forming the address of operand 2 in each of the above instructions follow the standard for type RX instructions. Again, the only new feature is that the address of the operand must be properly aligned. In practice that means using the proper declarative for specifying the storage. Single precision Use DS E or DC E, to insure that the address is a multiple of 4. Double precision Use DS D or DC D, to insure that the address is a multiple of 8. Sample Code LOAD1 LE 0,FL1 LOAD FP REG 0 FROM ADDRESS FL1 LOAD2 LD 2,FL2 LOAD DOUBLE PRECISION LOAD3 LER 4,0 COPY SINGLE PRECISION INTO FP REG 4 LOAD4 LDR 6,2 COPY DOUBLE PRECISION INTO FP REG 6 STORE1 STE 6,FL3 STORE THE SINGLE PRECISION INTO FL3 STORE2 STD 6,FL4 STORE DOUBLE PRECISION INTO FL4 FL1 DC E'123.45' A SINGLE PRECISION FLOATING POINT CONSTANT. ADDRESS IS A MULTIPLE OF 4. FL2 DC D'45678.90' A DOUBLE PRECISION FLOATING POINT CONSTANT. ADDRESS IS A MULTIPLE OF 8. FL3 DS E JUST RESERVE AN ALIGNED FULLWORD FL4 DS D RESERVE AN ALIGNED DOUBLE WORD. Note that the contents of register 6 are first stored as a single precision result, then as a double precision result. Addition and Subtraction There are four distinct addition instructions and four distinct subtraction instructions for normalized floating-point numbers. These instructions are as follows: <table> <thead> <tr> <th>Mnemonic</th> <th>Operation</th> <th>Opcode</th> <th>Operand Format</th> </tr> </thead> <tbody> <tr> <td>AE</td> <td>Add single precision</td> <td>7A</td> <td>R1,D2(X2,B2)</td> </tr> <tr> <td>AD</td> <td>Add double precision</td> <td>6A</td> <td>R1,D2(X2,B2)</td> </tr> <tr> <td>AER</td> <td>Add register single precision</td> <td>3A</td> <td>R1,R2</td> </tr> <tr> <td>ADR</td> <td>Add register double precision</td> <td>2A</td> <td>R1,R2</td> </tr> <tr> <td>SE</td> <td>Subtract single precision</td> <td>7B</td> <td>R1,D2(X2,B2)</td> </tr> <tr> <td>SD</td> <td>Subtract double precision</td> <td>6B</td> <td>R1,D2(X2,B2)</td> </tr> <tr> <td>SER</td> <td>Subtract register single precision</td> <td>3B</td> <td>R1,R2</td> </tr> <tr> <td>SDR</td> <td>Subtract register double precision</td> <td>2B</td> <td>R1,R2</td> </tr> </tbody> </table> Subtraction functions by changing the sign of the second operand and then performing an addition. The first step in each is ensuring that the characteristics of both operands are equal. If unequal, the field with the smaller characteristic is adjusted by shifting the fraction to the right and incrementing the characteristic by 1 until the characteristics are equal. Each of these operations sets the proper condition code for conditional branching. Recall that the standard floating point format is as follows: <table> <thead> <tr> <th>Leftmost 8 bits</th> <th>Other bits</th> </tr> </thead> <tbody> <tr> <td>Sign bit</td> <td>7-bit characteristic</td> </tr> </tbody> </table> Here is an example of adjusting the characteristic. Characteristic | Fraction ---|--- 41 | 290000 = 41 290000 40 | 12000 = 41 01200 | 41 2A200 Suppose that the fraction overflows. If that happens, the fraction is shifted right by one hexadecimal digit and the characteristic is incremented by 1. This last operation is called normalization, in that it returns the result to the expected normal form. Characteristic | Fraction ---|--- 41 | 940000 41 | 760000 41 | 10A0000 which becomes 42 010A000. Normalized addition and subtraction perform post-normalization; that is, they normalize the result after the operation. This is seen in the example above. Precision is maintained by use of a guard digit, which saves the last digit shifted during normalization prior to addition or subtraction. This digit may be restored during post-normalization. Here is an example. Characteristic | Fraction ---|--- 42 | 0B2584 = 42 0B2584 40 | 114256 = 42 001142(5) 5 is the guard digit. | 42 0B36C6(5) **Normalize the result** 41 B36C65. Here are some examples of the operation, which appear exactly as expected. * SINGLE PRECISION FLOATING POINT ADDITION * ADDSNG LE 2,FL1 LOAD THE REGISTER AE 2,FL2 ADD SINGLE PRECISION LE 4,FL3 LOAD ANOTHER REGISTER AER 4,2 REGISTER 4 IS CHANGED * SINGLE PRECISION FLOATING POINT SUBTRACTION * SUBSNG LE 2,FL1 LOAD THE REGISTER SE 2,FL2 SUBTRACT FROM THE VALUE IN REG 2 LE 4,FL3 LOAD ANOTHER REGISTER SER 4,2 SUBTRACT REG 2 FROM REG 4, CHANGING THE VALUE IN REGISTER 4 * DOUBLE PRECISION FLOATING POINT ADDITION * ADDDBL LD 2,FL1 LOAD THE REGISTER AD 2,FL2 ADD DOUBLE PRECISION LD 4,FL3 LOAD ANOTHER REGISTER ADR 4,2 REGISTER 4 IS CHANGED * DOUBLE PRECISION FLOATING POINT SUBTRACTION * SUBBDL LD 2,FL1 LOAD THE REGISTER SD 2,FL2 SUBTRACT FROM THE VALUE LD 4,FL3 LOAD ANOTHER REGISTER SDR 4,2 REGISTER 4 IS CHANGED * A FEW MIXED OPERATIONS * MIXED LD 2,FL1 DOUBLE PRECISION LOAD AE 2,FL2 SINGLE PRECISION ADDITION SE 2,FL3 SINGLE PRECISION SUBTRACTION STD 2,FL1 STORE AS DOUBLE PRECISION, THOUGH THE RESULT IS NOT QUITE THAT PRECISE * FL1 DC D '123.4' FL2 DC D '10.0' FL3 DC D '150000.0' Consider the “mixed precision” operations in which both single precision and double precision floating point numbers are used. The result is certainly less precise than a true double precision result, though possibly a bit more precise than a single precision one. This last claim of precision greater than single would be difficult to justify. Multiplication There are four distinct floating-point multiplication operations. <table> <thead> <tr> <th>Mnemonic</th> <th>Action</th> <th>Opcode</th> <th>Operands</th> </tr> </thead> <tbody> <tr> <td>ME</td> <td>Multiply single precision</td> <td>7C</td> <td>R1,D2(X2,B2)</td> </tr> <tr> <td>MD</td> <td>Multiply double precision</td> <td>6C</td> <td>R1,D2(X2,B2)</td> </tr> <tr> <td>MER</td> <td>Multiply single (register)</td> <td>3C</td> <td>R1,R2</td> </tr> <tr> <td>MDR</td> <td>Multiply double (register)</td> <td>2C</td> <td>R1,R2</td> </tr> </tbody> </table> In each, the first operand specifies a register that stores the multiplicand and, after the multiplication, stores the product. The operation normalizes the product, which in all cases is a double-precision result. Division There are four distinct floating-point division operations. <table> <thead> <tr> <th>Mnemonic</th> <th>Action</th> <th>Opcode</th> <th>Operands</th> </tr> </thead> <tbody> <tr> <td>DE</td> <td>Divide single precision</td> <td>7D</td> <td>R1,D2(X2,B2)</td> </tr> <tr> <td>DD</td> <td>Divide double precision</td> <td>6D</td> <td>R1,D2(X2,B2)</td> </tr> <tr> <td>DER</td> <td>Divide single (register)</td> <td>3D</td> <td>R1,R2</td> </tr> <tr> <td>DDR</td> <td>Divide double (register)</td> <td>2D</td> <td>R1,R2</td> </tr> </tbody> </table> In each, the first operand specifies a register that stores the dividend and, after the division, stores the quotient. There is no remainder. The operation normalizes the quotient, which in all cases is a double-precision result. A divisor containing a zero fraction causes a program interrupt. Recall that the two parts of any number in IBM floating point format are the characteristic and the fraction. The characteristic is held in the leftmost byte of the format and represents the sign and exponent. The fraction is held in the rest of the format: for single precision this is the 24 rightmost bits, and for double precision this is the 56 rightmost bits. Comparison There are four distinct floating-point division comparison operations. <table> <thead> <tr> <th>Mnemonic</th> <th>Action</th> <th>Opcode</th> <th>Operands</th> </tr> </thead> <tbody> <tr> <td>CE</td> <td>Compare single precision</td> <td>79</td> <td>R1,D2(X2,B2)</td> </tr> <tr> <td>CD</td> <td>Compare double precision</td> <td>69</td> <td>R1,D2(X2,B2)</td> </tr> <tr> <td>CER</td> <td>Compare single (register)</td> <td>39</td> <td>R1,R2</td> </tr> <tr> <td>CDR</td> <td>Compare double (register)</td> <td>29</td> <td>R1,R2</td> </tr> </tbody> </table> In each, the comparison sets the condition codes as would be expected for comparisons in the other formats. Each operation proceeds as a modified subtraction. The characteristic fields of the two operands are checked, and the smaller exponent is incremented while right shifting its fraction (denormalizing the number, but preserving its value) before the comparison. If both operands have fractions that are zero (all bits in the field are 0), the result is declared to be equal without consideration of either the exponent or the sign. The single precision operations compare only the leftmost 32 bits in each value. Conversions To and From Floating Point We now briefly discuss conversion of data between the three main forms that we have discussed at this time: two’s–complement integer, packed decimal, and floating point. We begin by considerations related to conversion to and from integer data. Recall that all floating point formats store data in the form $16^E \cdot F$, where $F$ is a fraction not less than $1/16 = 0.625$ and less than $1.0$. Of particular interest here are the values $16^1 = 16$, and $16^8 = (2^4)^8 = 2^{32} = 4,294,967,296$. Recall that a 32–bit two’s–complement format can represent integers in a specific range with the most negative value being $-2,147,483,648$ and the most positive being $2,147,483,647$. In terms of powers of 2, this range is from $-(2^{31})$ to $(2^{31} - 1)$. We see that $2^{31} = 16^8 \cdot 1/2$. Consider non–zero integers. The range consistent with the fullword format is as follows. The smallest magnitude is $1 = 16^1 \cdot (1/16)$; the exponent is 1, stored as $65 = \text{x'41'}$. The largest magnitude is $2^{31} = 16^8 \cdot 1/2$; the exponent is 8, stored as $72 = \text{x'48'}$. Immediately, we see that positive floating point numbers with characteristic fields at least $\text{x'41'}$ but not greater than $\text{x'48'}$ can be converted to integer form. If the characteristic field is less than $\text{x'41'}$, the floating–point value will be come an integer 0. If the characteristic field is greater than $\text{x'48'}$, the value is too large to be represented. The primary difficulty with conversions between packed decimal format and floating–point format is the fact that the position of the decimal point in packed format is not specified. This difficulty presents itself in different forms, depending on the exact operation. In translation from packed decimal to floating–point, the position of the decimal point must be explicitly specified in order to correctly set the exponent. In translation from floating–point to packed decimal, the computations can be done almost exactly, but there is no place to store a value representing the position of the decimal point. We shall explore these conversions again after we have developed a few more tools that can be used in scanning an array of digits or an array of bytes. Input and Output of Floating Point Values At this point in the chapter, the reader should be aware of a glaring omission. There has been no discussion of conversion from EBCDIC format to any of the floating–point formats or conversions from those formats back to EBCDIC. In other words, there has been no mention of methods to write assembly language programs either to read floating point data or to print those data in some readable format. The plain fact is that floating–point I/O is not mentioned in any standard source, either the textbooks [R_02, R_05, R_07, or R_18] or in any of the IBM manuals for the S/370 and successor systems [R_15, R_16, R_17, R_19, R_20, R_21, R_22, or R_23]. A request to IBM for any information yielded only a copy of the zSeries Principles of Operation [R_16]. It is likely the case that nobody writes complete floating–point oriented programs in IBM Assembler Language and has not for quite a few years. If your author finds any additional information, it will be shared in the next revision of this textbook.
{"Source-Url": "http://www.edwardbosworth.com/My3121Textbook_PDF/MyText3121_Ch13_V02.pdf", "len_cl100k_base": 11105, "olmocr-version": "0.1.53", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 40642, "total-output-tokens": 11567, "length": "2e13", "weborganizer": {"__label__adult": 0.0003399848937988281, "__label__art_design": 0.0003733634948730469, "__label__crime_law": 0.00030231475830078125, "__label__education_jobs": 0.0012712478637695312, "__label__entertainment": 6.687641143798828e-05, "__label__fashion_beauty": 0.0001671314239501953, "__label__finance_business": 0.0002841949462890625, "__label__food_dining": 0.00041413307189941406, "__label__games": 0.0007405281066894531, "__label__hardware": 0.00659942626953125, "__label__health": 0.0004291534423828125, "__label__history": 0.0002906322479248047, "__label__home_hobbies": 0.0001590251922607422, "__label__industrial": 0.0014848709106445312, "__label__literature": 0.00022602081298828125, "__label__politics": 0.0002446174621582031, "__label__religion": 0.0006318092346191406, "__label__science_tech": 0.1317138671875, "__label__social_life": 7.385015487670898e-05, "__label__software": 0.01386260986328125, "__label__software_dev": 0.83935546875, "__label__sports_fitness": 0.00028133392333984375, "__label__transportation": 0.0006537437438964844, "__label__travel": 0.00014650821685791016}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 37879, 0.07132]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 37879, 0.77853]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 37879, 0.85058]], "google_gemma-3-12b-it_contains_pii": [[0, 3237, false], [3237, 6616, null], [6616, 9197, null], [9197, 11917, null], [11917, 14272, null], [14272, 16887, null], [16887, 19605, null], [19605, 22883, null], [22883, 25320, null], [25320, 27463, null], [27463, 30137, null], [30137, 31581, null], [31581, 34539, null], [34539, 37879, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3237, true], [3237, 6616, null], [6616, 9197, null], [9197, 11917, null], [11917, 14272, null], [14272, 16887, null], [16887, 19605, null], [19605, 22883, null], [22883, 25320, null], [25320, 27463, null], [27463, 30137, null], [30137, 31581, null], [31581, 34539, null], [34539, 37879, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 37879, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 37879, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 37879, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 37879, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 37879, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 37879, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 37879, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 37879, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 37879, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, true], [5000, 37879, null]], "pdf_page_numbers": [[0, 3237, 1], [3237, 6616, 2], [6616, 9197, 3], [9197, 11917, 4], [11917, 14272, 5], [14272, 16887, 6], [16887, 19605, 7], [19605, 22883, 8], [22883, 25320, 9], [25320, 27463, 10], [27463, 30137, 11], [30137, 31581, 12], [31581, 34539, 13], [34539, 37879, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 37879, 0.21728]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
66dde1d303d65b9fd9911861b0ff0ca36785d792
Document History: <table> <thead> <tr> <th>Released</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>April 2017</td> <td>Initial Version</td> </tr> </tbody> </table> Table of Contents Overview ............................................................................................................................................. 4 Compatibility .................................................................................................................................. 4 Support .......................................................................................................................................... 4 Download ...................................................................................................................................... 5 Summary of Changes .......................................................................................................................... 5 Important Notes ............................................................................................................................... 5 Release Summary ............................................................................................................................ 6 Fixes ................................................................................................................................................ 6 Enhancements ................................................................................................................................ 6 Added Firmware/Software ................................................................................................................. 6 Driver Update Disks (DUD) for Linux ............................................................................................... 6 Known Limitations .............................................................................................................................. 7 General ........................................................................................................................................... 7 Components ................................................................................................................................... 9 Supported Operating Systems ........................................................................................................... 10 SPP Support for Client Operating System on HPE ProLiant WS460c Graphics Server and Synergy SY480 Compute Module ...................................................................................................... 11 Prerequisites .................................................................................................................................. 11 Component Prerequisites ................................................................................................................ 11 HP SUM Prerequisites .................................................................................................................... 11 Deployment Instructions ..................................................................................................................... 11 Installation ..................................................................................................................................... 11 Installation Instructions ................................................................................................................... 12 Additional Information for using the SPP on Linux Operating Systems ........................................ 13 Additional Information for using the SPP on VMware Operating Systems ....................................... 13 Additional Resources ........................................................................................................................ 13 Hot Fixes ........................................................................................................................................ 13 SPP Supplements ............................................................................................................................ 14 Using a PXE Server to Deploy Components from the full SPP ISO over a network ...................... 14 Setup ............................................................................................................................................. 14 Configuring GRUB2 .......................................................................................................................... 15 Configuring ELILO ........................................................................................................................... 15 Configuring PXELINUX ..................................................................................................................... 15 Supported network file system protocols ......................................................................................... 17 Common Abbreviations ................................................................................................................... 17 © Copyright 2017 Hewlett Packard Enterprise Development LP Overview The Service Pack for ProLiant (SPP) is a systems software and firmware solution delivered as a bootable ISO. This solution uses HP Smart Update Manager (HP SUM) as the deployment tool and is tested on supported HPE servers, including ProLiant, Apollo, and Synergy. Compatibility HP SUM and the components delivered in this SPP are all tested together. Hewlett Packard Enterprise (HPE) supports each SPP version for 12 months from the release date. Customers may choose to update to the current SPP from a previous SPP version. This is acceptable as long as the earlier version is within current version’s 12 month support period. This means that customers may directly update their SPP by skipping intermediate releases within the 12 month support period. See the table in the Compatibility section for details on the components contained in earlier SPPs that can migrate to this SPP. <table> <thead> <tr> <th>Product</th> <th>Version</th> </tr> </thead> <tbody> <tr> <td>Service Pack for ProLiant</td> <td>2016.10.0</td> </tr> <tr> <td></td> <td>2016.04.0</td> </tr> </tbody> </table> ⚠️ When migrating directly from an older version of the SPP to the latest, please review the release notes for the versions being skipped to be aware of changes that have occurred during those releases. Support The end of a 12 month support period can be determined by the version number of the release. For example, if SPP 2016.10.0 is currently installed, support for it would end the last day of October, 2017. This is based on version 2016=year, 10= month, 0=full release id number. Applying a Maintenance Supplement Bundle (MSB) will extend the support period of the SPP: <table> <thead> <tr> <th>SPP Version</th> <th>End of Support Period</th> </tr> </thead> <tbody> <tr> <td>2017.04.0</td> <td>April 30, 2018</td> </tr> <tr> <td>2016.10.0</td> <td>October 31, 2017</td> </tr> <tr> <td>2016.04.0</td> <td>April 30, 2017</td> </tr> </tbody> </table> For more details on the support period, please refer to Support Policy. Download There are several ways to download the SPP: **SPP Custom Download** [https://www.hpe.com/servers/spp/custom](https://www.hpe.com/servers/spp/custom): The SPP Custom Download is a free service for creating custom SPPs in 2 simple steps. Use the SPP Custom Download to: - Reduce the size of the SPP by including only what’s needed for your environment (e.g. SPP for ProLiant DL servers running Windows) - Add the latest hot fixes and OS supplements to the SPP Each SPP release in the SPP Custom Download also includes 1 or 2 HPE published SPPs that can be downloaded as is or customized. - Base SPP – SPP bootable ISO containing the version of the Smart Components the day the SPP was released. The “Base SPP” is always published for each SPP release. - Full SPP – SPP bootable ISO containing the Base SPP plus all Hot Fixes, OS Supplement Bundles, and Maintenance Supplement Bundles (MSBs) released to date. The “Full SPP” is published when the first hot fix, OS supplement, or MSB (for the SPP release in question) is release and is regenerated every time a new hot fix, OS supplement, or MSB is released. HPE recommends you download the “Full SPP” (if one is published) to ensure the SPP you’re downloading or customizing has the latest updates. **SPP Download Page** [https://www.hpe.com/servers/spp/download]: - Offers version information, release notes, Hot Fixes, Advisories, key documents, and an FAQ for SPP versions within the one year support window. - Enables individual selection of the SPP, OS Supplements, and Maintenance Supplement Bundle for download. - Displays a link to the SPP Custom Download service **HPESC Download Page** [https://www.hpe.com/global/swpublishing/MTX3c2bfc8c3b446a7a9451c4ab9]: - Enables download of all published versions of the SPP. - Provides description, list of supported operating systems, release notes, installation instructions and revision history. ⚠️ *Access to the SPP requires validation via the HPE Support Center. An active warranty or HPE support agreement is required to download the SPP.* ### Summary of Changes #### Important Notes In order to reduce the frequency at which servers need to be updated, HPE is changing the packaging and delivery of the SPP. Going forward, two types of SPPs will be released: - A single **“Production SPP”** that contains the firmware and drivers for the all of the production server generations Service Pack for ProLiant 2017.04.0 • Multiple server generation specific “Post-Production SPPs” that contain the firmware and drivers for a specific post-production server generation (e.g. Gen8 only Post-Production SPP that contains the firmware and drivers for all of Gen8 server models). When a server generation transitions to “Post-Production,” the firmware and drivers for that server generation are frozen, packaged together on a “Post-Production SPP,” and released. The “Post-Production SPP” is supported through the EOS (end of support) for that server generation, and all future firmware and driver updates are released as hot fixes. This eliminates the need for yearly updates. The 2017.04.0 SPP is the last production SPP to contain components for the G6, G7 and Gen8 server platforms. For additional information please https://downloads.hpe.com/pub/softlib2/software1/doc/p35024129/v128214/SPP_Reducing_Server_Updates.pdf Release Summary This Service Pack for ProLiant (SPP) release supersedes the 2016.10.0 SPP. Fixes • Online ROM Flash Component - Smart Array H240ar, H240nr, H240, H241, H244br, P240nr, P244br, P246br, P440ar, P440, P441, P542D, P741m, P840, P840ar, and P841 version 5.04 (Smart Array Firmware) Enhancements This release adds support for: • Red Hat Enterprise Linux 6.9 • Red Hat Enterprise Linux 7.3 • SUSE LINUX Enterprise Server 12 SP2 Added Firmware/Software • Added Firmware o Online ROM Flash Component - HPE ProLiant EC200a (U26) Server/HPE ProLiant Thin Micro TM200 (U26) Server • Added Linux Software o NIC support is provided with drivers in the Operating System distribution. HPE value added drivers for these operating systems will be in the next SPP. For a complete list of components on the ISO, see the SPP Contents Report on the ISO or the SPP documentation page. Driver Update Disks (DUD) for Linux DUDs for the following controllers for all Red Hat and SUSE supported operating systems can be found in the ‘DUD’ directory at the root of the ISO. • HP Dynamic Smart Array SATA RAID Controller • HP Smart Array B110i SATA RAID Controller • HP ProLiant Smart Array Controller • HP Dynamic Smart Array B140i SATA RAID Controller Driver Known Limitations The following is a select list of known issues and limitations relating to the smart components and HP SUM version delivered with this SPP. For a full list, please visit the SPP Download page, select the “Hot Fixes & Advisories” tab, and the “Known Limitations” heading. This procedure can be followed for any currently listed SPP by selecting the preferred SPP version listed next to ‘Currently Supported Versions’ to open its version specific page. General Rewrite of FCoE/FC Driver Kit for HPE QLogic CNAs fails with “update returned an error” due to product name change. Initial install will work successfully. Offline update of HPE B140i in legacy BIOS mode is not supported. Configure the Boot Mode to UEFI Mode if using HPE SW RAID. HP H2xx SAS/SATA Host Bus Adapter Driver for SUSE LINUX Enterprise Server 12 SP2 is not included in this SPP. Due to a conflict with an in-distro driver and Smart Update Manager, the HP H2xx SAS/SATA Host Bus Adapter Driver for SUSE LINUX Enterprise Server 12 SP2 is not included in this SPP. It is available on HPE Support Center at https://www.hpe.com/global/swpublishing/MTXc502d2922c2c47f584880ba61e. When using SUSE LINUX Enterprise Server 12 SP2, firmware must be flashed in offline mode. When verbose logging is enabled, HP SUM fails to deploy several components and will display the error message Return code – 1073741819 HP SUM fails to deploy several components and will display the error message Return code – 1073741819. This is caused when verbose logging is enabled and these components do not support verbose logging. Verbose logging is not enabled by default. Affected components include but are not limited to: - Online ROM Flash Component for Windows - HP Host Bus Adapters H220, H221, H222, H210i and H220i - Online ROM Flash Component for Windows - HPE Smart Array B320i RAID controller - Online ROM Flash Component for Windows (x64) - HP Gen8 Server Backplane Expander Firmware for HP Smart Array Controllers and HP HBA Controllers - Online HP 6Gb SAS BL Switch Firmware Smart Component for Windows (x86/x64) - Online HP 3Gb SAS BL Switch Firmware Smart Component for Windows - Online ROM Flash Component for Windows - Smart Array P700m Drivers and/or enablement kits must be installed prior to detecting and updating some hardware and firmware - HP SUM may need to be run twice for all firmware components to be presented for installation Drivers and/or enablement kits must be installed prior to detecting and updating some hardware and firmware. There are several scenarios when HP SUM may need to be run twice for all firmware components to be presented for installation. This is due to a requirement that drivers are needed in order for HP SUM to discover some hardware and thus the needed firmware. After the drivers are installed for the first time and the system rebooted, HP SUM needs to be run again for all of the firmware components to be presented for installation. The scenarios are: Network Adapters (NIC's), Host Bus Adapters (HBA's), and iLO require a driver or enablement kit to be installed in order to be recognized by HP SUM. When running HP SUM on Windows, if the iLO Channel Interface Driver is not installed, the iLO firmware will show a version of 'None' as the installed version and 'Ready for Installation' as the status on the Select Bundle or Select Component page. This applies to firmware for iLO 2, 3, and 4. When attempting to update the firmware, it may fail to update if it is already up to date. When using HP SUM on Linux, the ILO Channel Interface Driver needs to be loaded from the operating system for the iLO firmware to display for installation. The Power Management Controller, the Advanced Power Capping Microcontroller Firmware for HP ProLiant BL/DL/MLGen9 Servers, and the Smart Array H240ar, H240, H241, H244br, P244br, P246br, P440ar, P440, P441, P741m, P840, and P841 firmware also require the iLO Channel Interface Driver for firmware installation. Broadcom NICs are not discovered by HP SUM unless the appropriate driver is installed and all Ethernet ports are up. The Ethernet port can be brought up by using the following command: ``` # ifup ethx ``` or ``` # ifconfig ethx up ``` To update the firmware for Broadcom NIC, use the following steps: 1. Install the appropriate Windows or Linux driver found in the SPP. If updating a Linux server, the driver can also be retrieved from the SDR or the Linux distro. 2. Enable all the Ethernet ports 3. Run the Broadcom FW upgrade component Emulex, QLogic, and Qlogic BR-Series (Brocade) HBA Firmware is flashed in online mode **Service Pack for using ProLiant using the following steps.** This section includes optional installation of the Smart SAN Enablement Kit. 1) Prep the operating system: - If flashing Emulex CNAs or Fibre Channel HBAs on Linux, install the following RPMs from the operating system installation media, if not present on the system: - `libsysfs` or `sysfsutils` (depending on Linux OS) if Emulex CNAs are flashed, see CA c04366000 for additional information - `libhbaapi` or `libhbaapi2` (depending on Linux OS, required for the Emulex Enablement Kit) - For VMware use the HP Custom Image released at or shortly after the release of the SPP. To obtain the VMware Custom Image from HPE, visit the HPE web site to download drivers and other software to enable features such as SPP discovery and HBA firmware flashing. Custom HPE ESXi images. 2) Use the SPP to install necessary drivers for the HBAs, including any NIC drivers where applicable. At this time do not install the Enablement Kit or flash the HBA firmware, even if the selections are enabled by default in the SPP; deselect them. Until the system is rebooted with the drivers you have installed, do not attempt to enable Smart SAN, do not install the Fibre Channel Enablement Kit, and do not flash the HBA firmware. If on-site processes do not permit the installation of out of box drivers, review HPE SPOCK for inbox driver support information for the configuration. 3) If the drivers were updated, reboot the target system. 4) Use SPP to install the Fibre Channel Enablement Kits on Linux targets if using Fiber Channel (FC) cards (also recommended if using CNA cards in FCoE mode). No reboot is required after installing the Fibre Channel Enablement Kits. ⚠️ Important! Do not install the QLogic BR-series (Brocade) Enablement Kit on the same system with another vendor’s Enablement Kit. QLogic BR-series FC HBAs are not supported with other vendor HBAs unless the other vendor HBAs are used only as NICs. 5) If you have installed a Smart SAN enabled driver and wish to enable the Smart SAN feature, configure the Smart SAN Enablement Kit component in HP SPP. See the SPP documentation regarding configurable components. In the configuration of the component choose to enable Smart SAN. For Linux systems also elect to rebuild the ramdisk (initrd). - **Note**: HPE recommends that you back up your Linux system’s ramdisk before rebuilding it for any purpose (driver installation, Smart SAN Enablement, and so forth). The QLogic Smart SAN Enablement Kit does not create a copy of the ramdisk for you, so HPE recommends making a backup copy manually. The Emulex Smart SAN Enablement Kit creates a copy, the name of which can be seen if you click “View Log” in the SPP after deployment. 6) Perform an SPP inventory of the target system and optionally deploy the configured Smart SAN Enablement Kit and the firmware flash components. - **Note**: For legacy QLogic 8Gbps FC HBAs, see the release note “Legacy QLogic 8Gb Fibre Channel Adapters show an Active/Available Multi-boot Version of ’00.00.00’”. 7) After the flash operation and the optional Smart SAN update complete, click “View Log” in the SPP to review the results of the operations and check for errors. Reboot the target system to enable the new HBA Firmware and Smart SAN. ### Components **Required libraries for Linux Virtual Connect firmware:** The following libraries are required for HPE BladeSystem c-Class Virtual Connect Firmware, Ethernet plus FC Edition Component to install on Linux 64-bit systems: - `/lib/tls/libpthread.so.0` - `/lib/libdl.so.2` - `/usr/lib/libstdc++.so.6` - `/lib/tls/libm.so.6` - `/lib/libgcc_s.so.1` - `/lib/tls/libc.so.6` - `/lib/ld-linux.so.2` **Updated Firmware, Drivers, and Enablement Kits for QLogic BR-series (Brocade) adapters are not available on certain OS’s** Updated firmware, drivers, and Enablement Kits for QLogic BR-series (Brocade) adapters are not available for Windows 2008 32-bit, Windows 2008 64-bit, and 32-bit Linux systems. Components for BR-series adapters are available on the SPP for Windows 2008 R2 (and later) and 64-bit Linux systems. The BR-series Fibre Channel HBA Enablement Kit is not available for RHEL6.8. If you need to use the firmware flash component to flash your Brocade Fibre Channel HBAs on RHEL6.8, use Service Pack for ProLiant in offline mode. (CINDY S) RHEL 7 user has to wait 5-7 minutes to view the system management details due to the required init services not being in a running state **Root Cause:** In RHEL7 boot process, only the OS required init services are started before the user login screen/console is displayed. Then the remaining init services will be started. User will wait 5-7 minutes to view the system management details if logged into the system immediately before the init services are up and in a running state. With older RHEL (RHEL5, 6) boot processes, all the init services are started first before the login screen/console is displayed, so user would not face this issue. ## Supported Operating Systems The following operating systems are supported for system software and firmware support: - Microsoft Windows Server 2016 - Microsoft Windows Server 2012 R2 - All Editions - Microsoft Windows Server 2012 - All Editions - Microsoft Windows Server 2012 Essentials - Microsoft Windows Server 2008 R2 - Microsoft Windows Server 2008 R2 Foundation Edition - Microsoft Windows HPC Server 2008 R2 - Microsoft Windows Server 2008 x64 - All Editions - Microsoft Windows Server 2008 x64 - Server Edition - Microsoft Windows Server 2008 x64 - Server Core Edition - Microsoft Windows Server 2008 W32 - All Editions - Microsoft Windows Server 2008 W32 - Server Core Edition - Microsoft Windows Server 2008 Foundation Edition - Red Hat Enterprise Linux 7.3, 7.2, and 7.1 - Red Hat Enterprise Linux 6.9, 6.8, and 6.7 (x86-64) - Red Hat Enterprise Linux 6.9, 6.8, and 6.7 (x86) - SUSE Linux Enterprise Server 12 SP2, 12 SP1, and 12 - SUSE Linux Enterprise Server 11 SP4 and SP3 (AMD64/EM64T) - SUSE Linux Enterprise Server 11 SP4 and SP3 (x86) - VMware vSphere 6.0 Update 2, 6.0 Update 1, and 6.0 - VMware vSphere 5.5 Update 3, 5.5 Update 2, and 5.5 Update 1 Firmware-only Support: - VMware ESXi 5.1, 5.0 & 4.1 (offline only) - Novell Open Enterprise Server (Linux) (offline only) - Novell SUSE Open Linux (offline only) - Oracle Enterprise Linux (offline only) - Debian Linux (all releases) (offline only) For more information on HPE Operating Systems and Virtualization Software Support for ProLiant Servers, please visit our OS Support Site at: [https://www.hpe.com/info/ossupport](https://www.hpe.com/info/ossupport) SPP Support for Client Operating System on HPE ProLiant WS460c Graphics Server and Synergy SY480 Compute Module SPP software is an HPE ProLiant technology designed for server platforms but is supported on certain client operating systems supported only on HPE WS460c Graphics Server Blade and Synergy SY480 compute module. Support for the SPP when used with Microsoft Windows 7/8.1/10 on HPE ProLiant WS460c Graphics Server Blade and Synergy SY480 compute module is listed below. - SPP Offline Mode (Firmware Update) is fully supported by HPE ProLiant WS460c Graphics Server Blade Gen6/8/9, and Synergy SY480 compute blade Gen9. - SPP Online Mode (Drivers, Software and Firmware) is supported on HPE ProLiant WS460c Graphics Server Blade Gen8/9 and Synergy SY480 compute module Gen9. Note: The following components will be detected for install/update by SPP online mode. These utilities, which will function on Windows 7/8.1/10, are administration tools intended for Server operating systems and may not be appropriate for Client OS base images. - HPE ProLiant Integrated Management Log Viewer - HPE Lights-Out Online Configuration Utility - HPE ProLiant Array Configuration Utility - HPE Network Configuration Utility - HPE ProLiant Smart Array SAS/SATA Event Notification Service The following components may be detected by SPP online mode for installation/update. These utilities have not been tested on Windows 7/8.1 on HPE ProLiant WS460c Graphics Server Blade and are not recommended. The stability of the system will not be affected if these utilities are inadvertently installed, however, de-selecting these components during the SPP component install process is recommended. - HPE Insight Diagnostics Online Edition for Windows - HPE Insight Management WBEM Providers Prerequisites Component Prerequisites Some components have prerequisites. Check the individual components for their prerequisites. HP SUM Prerequisites The most current prerequisites for HP SUM can be found at the HP SUM documentation page https://www.hpe.com/servers/hpsum/documentation. Deployment Instructions Installation There are two methods for using the Service Pack for ProLiant to update your ProLiant servers: Service Pack for ProLiant 2017.04.0 - Online mode - Runs on a Windows or Linux hosted operating system - Offline mode - Server is booted to the ISO - Automatic mode - Firmware components will be updated without interaction - Interactive mode - Follow the onscreen steps to update firmware components To initiate deployment in Interactive mode: Run the launch_hpsum.bat (windows) or launch_hpsum.sh (linux) script which is found in the root of the ISO Automatic mode will by default run firmware update without any user interaction after sitting 30 seconds at the menu screen when an SPP .iso image is used to boot the server. Booting the SPP from iLO virtual media is only supported in Automatic Firmware Update mode. Users attempting this in any other mode may experience hangs from connection timeouts, difficulties updating iLO firmware, and mouse syncing issues. Note: If you install a software from the SPP and then install a Microsoft Windows operating system Service Pack or other operating system updates, HPE recommends reinstalling the software from the SPP. Installation Instructions Follow these steps to install the components found on this SPP: 1. Download the SPP 2017.04.0.iso file from the SPP download page https://www.hpe.com/servers/spp/download 2. Determine how to access the data on the ISO – bootable USB key, mounted ISO, etc. Use the appropriate tool to obtain the ISO in the desired format. 3. Determine how to initiate deployment to the targets using the SPP – Offline mode or Online mode: a. Online mode - Runs on a Windows® or Linux hosted operating system b. Offline mode - Server boots to the SPP ISO (Bootable ISO only) i. Automatic mode - Firmware components update without interaction ii. Interactive mode - Onscreen instructions guide the user to update firmware components 4. Initiate deployment. To initiate deployment in **online mode**: - From the SPP folder: o Windows: launch_hpsum.bat o Linux: ./launch_hpsum - For VMware hosts, select the host to update as a remote target. Online firmware update on a VMware host requires the HP Insight Management WBEM providers to be installed on the VMware host. - To review the EULA, locate README.html which is found in the root of the ISO. For more information, see the HP SUM User Guide and HP ProLiant Best Practices Implementation Guide. https://www.hpe.com/servers/spp/documentation To initiate deployment in **Offline mode**: - Boot the server to the SPP using one of the supported methods including mounting the ISO or DVD or using a bootable USB key. - Select either Automatic mode or Interactive mode. Additional Information for using the SPP on Linux Operating Systems Please refer to the following links for Technical Exception matrices for minimum OS support: - Red Hat Enterprise Linux - [Red Hat Enterprise Linux](#) - SUSE Linux Enterprise Server - [SUSE Linux Enterprise Server](#) The SPP contains Linux drivers, agent software and firmware in a single ISO image. Alternatively, downloads.linux.hpe.com contains software repositories that may be used with software configuration managers (Yum, Zyper or Apt). For drivers and agent software, subscribe your system to the "spp" repository: [http://downloads.linux.hpe.com/SDR/project/spp/](#) For firmware, subscribe your system to the "fwpp" repository: [http://downloads.linux.hpe.com/SDR/project/fwpp/](#) Additional Information for using the SPP on VMware Operating Systems The SPP can deploy drivers and firmware to a system running a supported VMware operating system in an online mode. Drivers are also available at Software Delivery Repository - vibsdepot. For a consolidated recipe of firmware and driver support, please review the VMware FW and Software Recipe document. To determine support for these operating systems, see the HPE ProLiant Server VMware Support Matrix at: [HPE Servers Support and Certification Matrices](#) **Additional Resources** **Hot Fixes** Hot Fixes and their associated Customer Advisories are released between SPP releases. Hot Fix components are tested against applicable SPPs. The Hot Fixes and the Customer Advisories for the latest SPP can be found by selecting the “Hot Fixes & Advisories” tab on the SPP Download page, [https://www.hpe.com/servers/spp/download](#). The Customer Advisory can be reviewed to determine if the Hot Fix applies and determine which component(s) need to be downloaded. To update the current configuration with a Hot Fix: 1. Click the grey + expander to the left of the Hot Fix Advisory to expand the list of associated downloadable component(s). 2. Click the title of the desired component to download to a designated repository. 3. Deploy it using HP SUM. SPP Supplements A supplement is an add-on bundle that may contain firmware, drivers, and/or applications which is released between SPPs. If the Supplement’s contents include Linux components, the components will also be available on the SDR. The components in the supplement are rolled into the next release of the SPP. - SPP Supplements can be downloaded from the SPP Download page (https://www.hpe.com/servers/spp/download). - The Release Notes can be found on the SPP Download page Documentation Tab. OS Supplements: An OS Supplement is a bundle containing software and/or firmware components. It includes support for a new operating system update, but works with the components in the SPP. Supplements allow HPE to deliver support when it is needed so customers do not have to wait on a full SPP’s availability. Support for OS Supplements are included as part of the associated SPP’s support period. Using a PXE Server to Deploy Components from the full SPP ISO over a network Follow these steps to use a PXE server to deploy components from the full SPP ISO over a network. ⚠️ The files needed to configure the menu system for use with a PXE server can be found in the PXE directory on the full SPP ISO. Prerequisites The following is required before proceeding with the configuration: - The user must have a good working knowledge of PXE and TFTP. - A network with a DHCP server on it. - A TFTP server configured on the same network as the DHCP server. - A network file server hosting the ISO images and can be accessed by a PXE booted system. The use of a Linux TFTP server and the TFTP package https://www.kernel.org/pub/software/network/tftp/ is assumed. Other TFTP servers should work similarly. Setup Before proceeding with the configuration, ensure that the TFTP server as well as the PXELINUX or GRUB2 configuration are setup and configured properly. ELILO (https://sourceforge.net/projects/eliilo/files) may be used also. GRUB2 is recommended for UEFI boot mode, legacy boot mode, or mixed environments where both legacy and UEFI boot mode support are required. To set up PXE boot for the SPP: 1. Copy the SPP ISO image to the network file system, and note its location. NFS and Windows® file shares as well as HTTP connections are supported. 2. For this example, the NFS and path to the ISO image used is 192.168.0.99/path/to/spp/image/(SPPfilename).iso. Test the network file system to ensure that it is accessible before proceeding. 3. The /pxe directory of the ISO image will need to be accessed, either by burning the ISO image, mounting the ISO image, or extracting it using a third-party tool. 4. Copy all the files from the /pxe directory of the ISO image to the TFTP server so that they are accessible by the TFTP software. See important instructions and information in the /pxe/README.txt file (for legacy boot mode PXELINUX configuration). Configuring GRUB2 Follow these steps to configure GRUB2: 1. Run the command grub2-mknetdir --net-directory=DIR where DIR is the root of the TFTP server. 2. Configure DHCP using the helpful output of the grub2-mknetdir command above (arch = 00:07 for UEFI boot mode and arch = 00:00 for legacy boot mode). 3. Edit the grub.cfg files on the TFTP server to set the appropriate paths to the kernel vmlinuz image file and the initial ramdisk initrd.img image file which were copied to the TFTP server from the SPP ISO /pxe directory. Configuring ELILO Follow these steps to configure ELILO: 1. Add an EFI folder on the TFTP server which contains bootx64.efi, elilomenu.msg, and elilo.conf. 2. Add details in elilo.conf as it is given for configuring pxelinux.cfg (see below). 3. Change the DHCP configuration as given below: ```plaintext if option arch = 00:07 { filename "pxelinux/bootx64.efi"; } else { filename "pxelinux.0"; } ``` Configuring PXELINUX Follow these steps to configure PXELINUX: 1. Using the isolinux.cfg file from the /system/ directory of the ISO as a guide, copy the labeled targets to the PXELINUX configuration file. The entire file does not need to be included: ```plaintext label sos MENU LABEL Automatic Firmware Update Version 2017.04.0 kernel vmlinuz append initrd=initrd.img media=cdrom root=/dev/ram0 splash quiet hp_fibre cdcache showopts TYPE=AUTOMATIC AUTOPWEROFFONSUCCESS=no AUTOREBOOTONSUCCESS=yes label vsos ``` MENU LABEL Interactive Firmware Update Version 2017.04.0 kernel vmlinuz append initrd=initrd.img media=cdrom root=/dev/ram0 splash quiet hp_fibre cdcache showopts TYPE=MANUAL AUTOPOWEROFFONSUCCESS=no label sos_poweroff MENU HIDE Automatic & POWEROFF Firmware Update Version 2017.04.0 kernel vmlinuz append initrd=initrd.img media=cdrom root=/dev/ram0 splash quiet hp_fibre cdcache showopts TYPE=AUTOMATIC hp_poweroff The paths to files on the TFTP server are vmlinuz and initrd.img. They must be modified to include any directories or naming conventions that are on the TFTP server. 2. Replace “media=cdrom” with “media=net” on the append line 3. Specify the ISO image path. For the PXE booted server to find the ISO Image, add the ISO Image path to the append line in the PXELINUX configuration file. Add the following arguments: iso1=nfs://192.168.0.99/path/to/spp/image/(SPPfilename).iso iso1mnt=/mnt/bootdevice The iso1 parameter helps the PXE booted SPP locate the ISO image. The iso1mnt parameter tells the PXE booted SPP where the iso1 image must be mounted. The final configuration file must be similar to the following example: label sos MENU LABEL Automatic Firmware Update Version 2017.04.0 kernel vmlinuz append initrd=initrd.img media=net root=/dev/ram0 splash quiet hp_fibre showopts TYPE=AUTOMATIC AUTOPOWEROFFONSUCCESS=no AUTOREBOOTONSUCCESS=yes iso1=nfs://192.168.0.99/path/to/spp/image/(SPPfilename).iso iso1mnt=/mnt/bootdevice label vsos MENU LABEL Interactive Firmware Update Version 2017.04.0 kernel vmlinuz append initrd=initrd.img media=net root=/dev/ram0 splash quiet hp_fibre showopts TYPE=MANUAL AUTOPOWEROFFONSUCCESS=no iso1=nfs://192.168.0.99/path/to/spp/image/(SPPfilename).iso iso1mnt=/mnt/bootdevice label sos_poweroff MENU HIDE Automatic & POWEROFF Firmware Update Version 2017.04.0 kernel vmlinuz Service Pack for ProLiant 2017.04.0 append initrd=initrd.img media=net root=/dev/ram0 splash quiet hp_fibre showopts TYPE=AUTOMATIC hp_poweroff iso1=nfs://192.168.0.99/path/to/spp/image/(SPPfilename).iso iso1mnt=/mnt/bootdevice Additional ISO images can be added by specifying the additional iso# and iso#mnt arguments, for example, iso2=/path/to/iso2.iso iso2mnt=/mnt/iso2. **Supported network file system protocols** The following network file system protocols are supported for use with PXE booting: **NFS:** iso1=nfs://192.168.0.99/path/to/spp/image/(SPPfilename).iso iso1mnt=/mnt/bootdevice **NFS volumes are mounted with the following options:** - `-o ro` - `nolock` *The mount options can be explicitly set with the iso#opts parameter* iso1opts="rsize=32768,ro,nolock" **Windows® operating systems:** iso1=cifs://192.168.0.99/share/path/to/spp/image/(SPPfilename).iso iso1mnt=/mnt/bootdevice **Windows® operating systems with login credentials:** iso1=cifs://user:password@192.168.0.99/share/path/to/spp/image/(SPPfilename).iso iso1mnt=/mnt/bootdevice **HTTP:** iso1=http://192.168.0.99/path/to/spp/image/(SPPfilename).iso iso1mnt=/mnt/bootdevice Once these steps have been completed, the SPP components are ready to be deployed using the PXE boot functionality. **Common Abbreviations** <table> <thead> <tr> <th>Abbreviations</th> <th>Name</th> </tr> </thead> <tbody> <tr> <td>AMS</td> <td>Agentless Management Service</td> </tr> <tr> <td>CNU</td> <td>Converged Network Utility</td> </tr> <tr> <td>HBA</td> <td>Host Bus Adapter</td> </tr> <tr> <td>iLO</td> <td>Integrated Lights-Out</td> </tr> <tr> <td>MSB</td> <td>Maintenance Supplement Bundle</td> </tr> </tbody> </table> © Copyright 2017 Hewlett Packard Enterprise Development LP <table> <thead> <tr> <th>Acronym</th> <th>Full Form</th> </tr> </thead> <tbody> <tr> <td>OA</td> <td>Onboard Administrator</td> </tr> <tr> <td>RHEL</td> <td>Red Hat Enterprise Linux</td> </tr> <tr> <td>SIM</td> <td>Systems Insight Manager</td> </tr> <tr> <td>SLES</td> <td>SUSE Linux Enterprise Server</td> </tr> <tr> <td>SPP</td> <td>Service Pack for ProLiant</td> </tr> <tr> <td>SUM</td> <td>Smart Update Manager</td> </tr> </tbody> </table>
{"Source-Url": "https://downloads.hpe.com/pub/softlib2/software1/doc/p1205445419/v130016/2017.04.0-SPPReleaseNotes.pdf", "len_cl100k_base": 8661, "olmocr-version": "0.1.53", "pdf-total-pages": 18, "total-fallback-pages": 0, "total-input-tokens": 41227, "total-output-tokens": 9678, "length": "2e13", "weborganizer": {"__label__adult": 0.0007338523864746094, "__label__art_design": 0.0007233619689941406, "__label__crime_law": 0.0004100799560546875, "__label__education_jobs": 0.0009794235229492188, "__label__entertainment": 0.00026035308837890625, "__label__fashion_beauty": 0.00037217140197753906, "__label__finance_business": 0.0047454833984375, "__label__food_dining": 0.0004825592041015625, "__label__games": 0.0019550323486328125, "__label__hardware": 0.164306640625, "__label__health": 0.0008263587951660156, "__label__history": 0.0006098747253417969, "__label__home_hobbies": 0.0006418228149414062, "__label__industrial": 0.00472259521484375, "__label__literature": 0.0003995895385742187, "__label__politics": 0.0005769729614257812, "__label__religion": 0.0007963180541992188, "__label__science_tech": 0.22802734375, "__label__social_life": 0.00010478496551513672, "__label__software": 0.2176513671875, "__label__software_dev": 0.36865234375, "__label__sports_fitness": 0.0003001689910888672, "__label__transportation": 0.001247406005859375, "__label__travel": 0.00042176246643066406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 38423, 0.0291]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 38423, 0.06732]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 38423, 0.74073]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 112, false], [112, 5141, null], [5141, 7061, null], [7061, 9469, null], [9469, 11673, null], [11673, 14657, null], [14657, 17785, null], [17785, 20663, null], [20663, 23012, null], [23012, 25221, null], [25221, 27852, null], [27852, 29926, null], [29926, 32456, null], [32456, 34497, null], [34497, 36345, null], [36345, 38145, null], [38145, 38423, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 112, true], [112, 5141, null], [5141, 7061, null], [7061, 9469, null], [9469, 11673, null], [11673, 14657, null], [14657, 17785, null], [17785, 20663, null], [20663, 23012, null], [23012, 25221, null], [25221, 27852, null], [27852, 29926, null], [29926, 32456, null], [32456, 34497, null], [34497, 36345, null], [36345, 38145, null], [38145, 38423, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 38423, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 38423, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 38423, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 38423, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 38423, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 38423, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 38423, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 38423, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 38423, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 38423, null]], "pdf_page_numbers": [[0, 0, 1], [0, 112, 2], [112, 5141, 3], [5141, 7061, 4], [7061, 9469, 5], [9469, 11673, 6], [11673, 14657, 7], [14657, 17785, 8], [17785, 20663, 9], [20663, 23012, 10], [23012, 25221, 11], [25221, 27852, 12], [27852, 29926, 13], [29926, 32456, 14], [32456, 34497, 15], [34497, 36345, 16], [36345, 38145, 17], [38145, 38423, 18]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 38423, 0.06905]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
bda12dd21ed570b63806f01105010df495f09d64
[REMOVED]
{"Source-Url": "https://backend.orbit.dtu.dk/ws/portalfiles/portal/6377948/The+Logic.pdf", "len_cl100k_base": 14307, "olmocr-version": "0.1.50", "pdf-total-pages": 19, "total-fallback-pages": 0, "total-input-tokens": 73303, "total-output-tokens": 16021, "length": "2e13", "weborganizer": {"__label__adult": 0.0004062652587890625, "__label__art_design": 0.0006036758422851562, "__label__crime_law": 0.0012235641479492188, "__label__education_jobs": 0.001102447509765625, "__label__entertainment": 8.7738037109375e-05, "__label__fashion_beauty": 0.00022661685943603516, "__label__finance_business": 0.0010881423950195312, "__label__food_dining": 0.0003905296325683594, "__label__games": 0.0005941390991210938, "__label__hardware": 0.001331329345703125, "__label__health": 0.001556396484375, "__label__history": 0.0002925395965576172, "__label__home_hobbies": 0.00015425682067871094, "__label__industrial": 0.0008831024169921875, "__label__literature": 0.0003056526184082031, "__label__politics": 0.00045871734619140625, "__label__religion": 0.0004606246948242187, "__label__science_tech": 0.1734619140625, "__label__social_life": 0.00011396408081054688, "__label__software": 0.027557373046875, "__label__software_dev": 0.78662109375, "__label__sports_fitness": 0.0002453327178955078, "__label__transportation": 0.0004367828369140625, "__label__travel": 0.00019109249114990232}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 48037, 0.04102]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 48037, 0.34709]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 48037, 0.76531]], "google_gemma-3-12b-it_contains_pii": [[0, 311, false], [311, 3045, null], [3045, 6154, null], [6154, 8805, null], [8805, 10921, null], [10921, 13571, null], [13571, 16347, null], [16347, 18582, null], [18582, 21415, null], [21415, 23512, null], [23512, 25558, null], [25558, 28294, null], [28294, 30905, null], [30905, 33975, null], [33975, 37240, null], [37240, 40163, null], [40163, 43037, null], [43037, 46347, null], [46347, 48037, null]], "google_gemma-3-12b-it_is_public_document": [[0, 311, true], [311, 3045, null], [3045, 6154, null], [6154, 8805, null], [8805, 10921, null], [10921, 13571, null], [13571, 16347, null], [16347, 18582, null], [18582, 21415, null], [21415, 23512, null], [23512, 25558, null], [25558, 28294, null], [28294, 30905, null], [30905, 33975, null], [33975, 37240, null], [37240, 40163, null], [40163, 43037, null], [43037, 46347, null], [46347, 48037, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 48037, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 48037, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 48037, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 48037, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 48037, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 48037, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 48037, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 48037, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 48037, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 48037, null]], "pdf_page_numbers": [[0, 311, 1], [311, 3045, 2], [3045, 6154, 3], [6154, 8805, 4], [8805, 10921, 5], [10921, 13571, 6], [13571, 16347, 7], [16347, 18582, 8], [18582, 21415, 9], [21415, 23512, 10], [23512, 25558, 11], [25558, 28294, 12], [28294, 30905, 13], [30905, 33975, 14], [33975, 37240, 15], [37240, 40163, 16], [40163, 43037, 17], [43037, 46347, 18], [46347, 48037, 19]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 48037, 0.08654]]}
olmocr_science_pdfs
2024-12-01
2024-12-01
1dbb79283a3f1b9d3798bd4792739b384b4b7898
ABOUT THE TOOLBOX The Pharamcoepi Toolbox contains a number of elements useful for modern pharmacoepidemiology. Included in this version of the toolbox are: - High-Dimensional Variable Selection - High-Dimensional Propensity Scores - High-Dimensional Disease Risk Scores (experimental) - 1:1, n:1, and r:1 Greedy Matching - 1:1, n:1, and r:1 Nearest-Neighbor Matching - 1:1:1 Nearest-Neighbor Matching - Epidemiology Table Creation All elements in the toolbox are implemented as Java programs, which can be linked into SAS, R, or custom code. For convenience, we have created SAS macros that encapsulate the Java programs. This guide details how to use the elements of the Toolbox from within SAS. Included in the distribution is example code for using the Toolbox in R. The Java classes are self-documented with Javadocs. HOW TO CITE When using the Toolbox, please cite it as follows: SYSTEM REQUIREMENTS The Toolbox requires SAS Version 9.2 or later. It will not run on earlier versions of SAS. The macro makes use of SAS’s Java subsystem. Giving sufficient memory to the Java subsystem will substantially increase performance; adding a line such as ``` -jreoptions (-Xmx1024m) ``` to the SASV9_LOCAL.CFG file or similar should suffice. For more information on how to allocate Java memory in SAS, please see **Note to SAS Batch Mode users.** The Toolbox macros use PROC EXPORT for transferring data; PROC EXPORT will hang batch SAS unless the `-noterminal` option is specified: ``` sas -noterminal program.sas ``` HIGH DIMENSIONAL VARIABLE SELECTION HIGH DIMENSIONAL PROPENSITY SCORES HIGH DIMENSIONAL DISEASE RISK SCORES MACROS DEFINED %InitHDMacros %DoHDVariableSelection %EstimateHDPs %EstimateHDDRSE [experimental] %RunOutcomeModels DESCRIPTION This macro implements a multi-step algorithm to implement high-dimensional proxy adjustment in claims data. The algorithm is described in detail in High-dimensional proxy adjustment in claims data studies of treatment effects by Schneeweiss et al. The additions to the second version of the algorithm are described in Observed performance of high-dimensional propensity score analyses of treatment effects in small samples by Rassen et al. (in press). Briefly, the macro’s steps include 1) identify data dimensions, e.g. diagnoses, procedures, and medications, 2) empirically identify candidate covariates, 3) assess recurrence, i.e. multiplicity of same code, 4) prioritize covariates, 5) select covariates for adjustment, 6) estimate exposure propensity score, and 7) estimate outcome model. FILES REQUIRED Main SAS file: hdmacros.sas Core program file: pharmacoepi.jar MACROS INCLUDED The hd-PS macro is divided into several key steps: variable creation and selection, score model building, and outcome models. Each step has a distinct associated macro, plus a single initialization macro that sets parameters for all subsequent steps. In more detail, the macros are: %InitHDMacros(...) Initialize the macro and sets parameters used in all subsequent steps. Takes the parameters described below. %DoHDVariableSelection Performs variable creation and selection. Takes no parameters. %EstimateHDPs(name_of_dataset) Estimates propensity scores and places the scores as variables called ps2, ps3, ps4, ps5 in the specified dataset. There is no ps1 since the first model run is a crude (unadjusted) model. The variables contained in ps2 to ps5 are described under “score_type_X”, below. %RunOutcomeModels(name_of_dataset, score_var [ps or drs]) Runs the specified matched or decile-based outcome models. With the specified dataset, searches for any score variables with the specified score variable base name, and runs outcome models for each score variable. For hd-PS the score_var should be ps, while for hd-DRS (experimental) the score_var should be drs. MACRO PARAMETERS THAT CONTROL PRE-DEFINED VARIABLES var_patient_id Required Name of unique patient identifier variable. var_exposure Optional; default=exposure Name of binary exposure variable. A value of 1 for this variable will be considered exposed; 0 will be considered unexposed/referent. var_outcome Optional; default=outcome Name of binary outcome variable. A value of 1 for this variable will be considered outcome positive; 0 will be considered outcome negative. vars_demographic Optional; default=none A list of variables to be considered as demographic information, such as age, sex, and race. vars_predefined Optional A list of variables to be considered as pre-defined, such as co-morbidities or past drug usage. If this option is not specified, all variables in the dataset other than the patient ID, exposure, outcome, and demographic variables will be considered pre-defined. vars_force_categorical Optional; default=none An optional list of numeric variables that should be treated as categorical. Year of service is a common example. (See note below.) vars_ignore Optional; default=none A list of variables to be ignored in the propensity score estimation and simply passed through to output data sets. Examples include follow-up time and other variables important to an analysis but which do not figure into confounder adjustment. This option will only take effect when vars_predefined is not specified. MACRO PARAMETERS THAT CONTROL INPUT AND OUTPUT DATA input_cohort Required Name of the input SAS dataset containing the patients, exposure, outcome, and any predefined covariates. Datasets will not be modified. See note below on format of the data. input_dimX *one or more dimensions required* This parameter is specified one or more times to indicate the names of the datasets containing the dimension data. Datasets will not be modified. See note below for dataset format. Each time this parameter is specified, two data items are needed: the name of the dimension dataset and the name of the field containing the code of interest. These two items should be supplied on one line with only spaces in between. (See example.) The parameters should be numbered sequentially and with no gaps in the numbering (input_dim1, input_dim2, etc.). output_cohort *optional; default*= output_scored_cohort Name of a SAS dataset that will be created or replaced. This dataset will contain the input cohort (including their exposure, outcome, and fixed covariates), as well as the series of empirical covariates calculated from each dimension of data. It is intended for diagnostic use or further exploration of the generated variables and may be quite large. result_diagnostic *optional; default*= result_diagnostic Base name of a series of SAS datasets that will be created or replaced. Two datasets will be created. (1) A dataset with all codes considered; the default name is result_diagnostic_dim_codes. (2) A dataset with details on all variables constructed from those codes and subsequently considered for selection; the default name is result_diagnostic_all_vars. result_estimates *optional; default*= result_estimates Name of a SAS dataset that will be created or replaced. This dataset will contain the point estimates and confidence intervals for each of the outcome models that were requested (if any). path_temp_dir *required* The path to a directory where the hd-PS macro can store temporary files. There should be enough space in the directory to hold a second copy of the input cohort and each of the dimensions. path_jar_file *required* The path to the pharmacoepi.jar file. NOTE: This path cannot contain spaces. This is a SAS limitation. **MACRO PARAMETERS THAT CONTROL VARIABLE CREATION & SELECTION** top_n *optional; default*=200 The n most prevalent empirical covariates to consider from each dimension of data. **k** *optional; default=500* The number of empirical covariates to include in the resulting propensity score. **frequency_min** *optional; default=0* The minimum number of occurrences an empirical variable must have before being considered for selection. **For compatibility with older versions of the software, set the value to 100.** **ranking_method** *optional; default=BIA S* A text variable that indicates one of three modes for selecting variables. Specifying **BIAS** will yield a variable list in which the top k variables are selected as ranked by the Bross bias formula. Specifying **EXP_ASSOC** will yield a variable list in which the top k variables are selected as ranked by the confounder/exposure “risk ratio” (ratio of prevalence of the confounder in the exposed versus the unexposed). This is most suitable for cases where there are fewer than 150 exposed outcomes. Specifying **OUTCOME_ASSOC** will yield a variable list in which the top k variables are selected as ranked by the confounder/outcome risk ratio. This is most suitable for disease risk scores. **outcome_zero_cell_corr** *optional; default=0* An indicator for whether to screen variables with a zero correction added to each cell in the confounder/outcome 2x2 table. Recommended when the number of exposed outcomes is fewer than 150. **infer_service_intensity_vars** *optional; default=0* An indicator for whether to infer the intensity of health service utilization by computing quartile of (a) number of codes per patient, and (b) number of unique codes per patient within each dimension. These quartile indicators are then screened like all other hd-PS variables and allowed to enter the final propensity score. This option may be used in place of investigator-defined variables such as “number of unique medications used” or “number of office visits”. **MACRO PARAMETERS THAT CONTROL SCORE TYPES AND OUTCOME MODELS** **outcome_model_deciles** *optional; default=1* An indicator for whether to run outcome models using deciles. **outcome_model_matched** *optional; default=0* An indicator for whether to run outcome models using greedy matching. **score_type_X** *optional (X=1 to 5); default is that all =1* An indicator for whether to create propensity (or disease risk) score types 1 through 5, and, if analysis is selected, whether to execute an outcome model adjusted by (or matched on) each of those propensity (or disease risk) scores. The score types are as follows: 1. No confounders (unadjusted) 2. Demographics variables only 3. Demographics and predefined variables 4. Demographics, predefined, and empirical (macro-selected) variables 5. Demographics and empirical (macro-selected) variables MACRO PARAMETERS THAT CONTROL NETEZZA DATABASE PROCESSING MODE **selection_mode** *optional; default=LOCAL* A text variable that indicates whether variable selection will be done locally using traditional hd-PS processing, or whether it should be done in-database with Netezza information appliances. The default, LOCAL, will run within SAS using the Java subsystem. Specifying DB will cause variable selection to run within a Netezza appliance. The mode requires several additional parameters to be specified. **input_cohort_table** *required for DB mode* A table on the database server that mirrors the cohort specified in input_cohort. This table is used to speed processing. **db_driver_classpath** *required for DB mode* The full filesystem path to the database driver class. The driver is often packaged in nzjdbc3.jar. **db_url** *required for DB mode* The JDBC URL to the Netezza database. This should take the form of jdbc:netezza://server.domain/database. **db_username** *required for DB mode* The username for the Netezza database. **db_password** *required for DB mode* The password for the Netezza database. OTHER MACRO PARAMETERS **upload_results** *optional; default = 0* An indicator for whether to upload results to the hdpharmacoepi.org web site. analysis_num required if upload_results = 1 If results upload is selected, the analysis number assigned by the hdpharmacoepi.org web site; specifying this number will associate the results uploaded with the proper analysis. outcome_type optional; default = DICHOTOMOUS Experimental. NOTES Input cohort data format. The input_cohort dataset must contain only the patient ID, exposure, outcome, and any covariates that should be adjusted for in the outcome model. If the vars_predefined option is not specified, covariates in the input data that are not to be included in the outcome model should be dropped before running the macro or specified in vars_ignore. Input dimension data format. Each dimension of data (drugs, inpatient procedures, etc.) should be supplied in a unique dataset. This dataset should have at least two fields: the patient identifier and the dimension code. Patients receiving multiple codes, and/or a single code more than one time, should be listed over multiple rows. (For example, in an outpatient procedure dimension, the dimension code would likely be a CPT code.) Additional fields will be ignored. Covariates. All character covariates in the input cohort will be treated as categorical. Any numeric covariates that should be treated as categorical (such as year of service) should be either converted to character before running the macro or included in the vars_force_categorical list. EXAMPLE CODE In the following example code, the required input is printed in bold. Other options are printed as an example but are not required for running the macro. %include "/path/to/macro/directory/hdmacros.sas"; Title1 'High-dimensional propensity score adjustment'; Title2 '(study description)'; %InitHDMacros { var_patient_id = id, var_exposure = exposed, var_outcome = outcome, vars_demographic = age sex race, vars_force_categorical = year, vars_ignore = followup_time, top_n = 200, k = 400, path_temp_dir = %QUOTE(/path/to/temp/dir), /* remember, no spaces in path_jar_file! */ path_jar_file = %QUOTE(/path/to/jar/file/pharmacoepi.jar), outcome_model_deciles = 0, outcome_model_matched = 1, score_type_4 = 0, input_cohort = master_file, input_dim1 = drug_claims generic_name, input_dim2 = outpatient_diagnoses icd9_dx, input_dim3 = inpatient_diagnoses icd9_dx, input_dim4 = inpatient_procedures icd9_proc, input_dim5 = outpatient_procedures cpt, output_cohort = scored_cohort, result_estimates = estimates, result_diagnostic = variable_info ); DESCRIPTION These macros implement greedy and nearest-neighbor matching in SAS. FILES REQUIRED Main SAS file: matching.sas Core program file: pharmacoepi.jar ➔ Due to SAS limitations, the pharmacoepi.jar file must be stored on a path without spaces! GENERAL INFORMATION The greedy and nearest-neighbor matching methods each implement 1:1, n:1 (variable-ratio), and r:1 (fixed-ratio) matching. In each case, it is assumed that 1 or more referent patients will be matched to a single treated patient; if the opposite is desired, simply reverse the group designations. The resulting matched cohort will contain a variable called set_num; this variable indicates the matched set. Lower values of set_num will tend to be better matches. MATCHING MACROS %match_GreedyMatch(...) Performs a 1:1, n:1, or r:1 digit-based greedy match using a modified version of the Parsons greedy matching technique. in_dataset required Name of a SAS library in which the source data (cohort to be matched) resides. out_dataset required Name of a SAS library that will contain the matched cohort. If this dataset exists, it will be overwritten. working_directory required The path to a directory where the macro can store temporary files. There should be enough space in the directory to hold a second copy of the input cohort. var_patient_id required Name of unique patient identifier variable. var_exposure *optional; default=exp* Name of binary exposure variable. var_ps *optional; default=ps* Name of variable containing the propensity score (or other continuous value) to match on. exp_groups *optional; default=0 1* A list of values that define the two exposure groups. The first group listed will be assumed to be the referent group. start_digit *optional; default=5* The first digit at which the matching algorithm will attempt to match. For example, with the default of 5, it will first match propensity scores that are equal to the first 5 digits. end_digit *optional; default=1* The digit at which the matching will stop. For example, with the default of 1, the matching algorithm will last match patients whose propensity scores are equal to the first digit. ratio *optional; default=1* The desired match ratio, e.g., the value of n or r in n:1 or r:1 matching. fixed_ratio *optional; default=0* An indicator (values 1 or 0) for whether fixed ratio (r:1) or variable ratio (n:1) matching is desired. %match_NearestNeighborMatch(...) Performs a 1:1, n:1, or r:1 nearest neighbor match. in_dataset *required* Name of a SAS library in which the source data (cohort to be matched) resides. out_dataset *required* Name of a SAS library that will contain the matched cohort. If this dataset exists, it will be overwritten. working_directory *required* The path to a directory where the macro can store temporary files. There should be enough space in the directory to hold a second copy of the input cohort. var_patient_id *required* Name of unique patient identifier variable. var_exposure *optional; default=exp* Name of binary exposure variable. var_ps optional; default=ps Name of variable(s) containing the propensity score(s) (or other continuous value) to match on. exp_groups optional; default=0 1 A list of values that define the two or three exposure groups. In two-way matching, the first group listed will be assumed to be the treatment group. caliper optional; default=0.05 The maximum distance between two patients allowable for a match. In two-way matching, recommendations for this value can be found in papers by Peter Austin. In three-way matching, this value sum of the Euclidean distance among the three patients (the perimeter of the triangle defined by the three patients). No specific value is yet recommended, but 3x the value used in two-way matching may be a good starting point. Caliper must be specified as a constant (e.g., 0.05) or a macro variable (e.g. &caliper). ratio optional; default=1 The desired match ratio, e.g., the value of n or r in n:1 or r:1 matching. fixed_ratio optional; default=0 An indicator (value 1 or 0) for whether fixed ratio (r:1) or variable ratio (n:1) matching should be performed. balanced optional; default=0 An indicator (value 1 or 0) for whether nearest-neighbor matching should be balanced (requiring that referent matches alternate between being to the right and left of the treated patient). EXAMPLE CODE %INCLUDE "\path/to/toolbox/sas/java_utils.sas"; %INCLUDE "\path/to/toolbox/sas/matching.sas"; /* remember, no spaces in the path! */ %toolbox_Start(%QUOTE(/path/to/toolbox/java/pharmacoepi.jar)); /* Estimate 2-group propensity score */ PROC LOGISTIC DATA=input_cohort DESCENDING; MODEL exposure = covariate1 covariate2 ... ; OUTPUT OUT=match_input_cohort PRED=prob; RUN; /* Run 1:1 nearest neighbor match */ %match_NearestNeighborMatch (match_input_cohort, match_output_cohort, %QUOTE(c:\temp\), var_patient_id = id, var_exposure = exp, var_ps = prob, exp_groups = 0 1, caliper=0.05, ratio=3, fixed_ratio = 1 ); /* Estimate 3-group propensity score with polytomous */ /* logistic regression */ PROC LOGISTIC DATA=input_cohort_3way ORDER=data DESCENDING; CLASS expcat; MODEL expcat(ref="1") = covariate1 covariate2 ... / LINK=glogit; OUTPUT OUT=input_3way_cohort_long(KEEP=id expcat _level_ prob) PRED=prob; RUN; /* The output from above will contain one row per patient per */ /* level. Transform to one row per patient with one variable per level */ PROC TRANSPOSE DATA=input_3way_cohort_long OUT=input_3way_cohort PREFIX=prob; BY id expcat; RUN; /* Run 1:1:1 nearest neighbor match */ %match_NearestNeighborMatch ( input_3way_cohort, output_3way_cohort, %QUOTE(c:\temp\), var_patient_id = id, var_exposure = expcat, var_ps = prob1 prob2, exp_groups = 1 2 3, caliper=0.05, ratio=3, ); /* Perform analysis: crude, adjusted, conditioned on match set (set_num) ... */ ... EPIDEMIOLOGY TABLE CREATION DESCRIPTION This macro implements epidemiology tables in SAS. Note. There are two ways to define tables: through a series of macro calls, or via Excel spreadsheet(s). They are functionally equivalent, though the latter may be more convenient. While the methods should be able to be mixed-and-matched, it is probably best to use one or the other. SYSTEM REQUIREMENTS The macro requires SAS Version 9.2 or later. It will not run on earlier versions of SAS. FILES REQUIRED Main SAS file: table_creator.sas Required include file: java_utils.sas Core program file: pharmacoepi.jar Due to SAS limitations, the pharmacoepi.jar file must be stored on a path without spaces! EXCEL SPREADSHEET FORMAT The Excel spreadsheet must be formatted in a specific way in order to allow the Table Creator to extract table definitions. For convenience, a sample spreadsheet is provided. Excel files can be in either the older XLS or the newer XLSX format. The sections of the spreadsheet are each color-coded; the choice of colors is very specific and must not be altered. The color refers to the Fill Color of the cell. Opening the Fill Color dialog box and hovering over the color swatches will reveal color names. <table> <thead> <tr> <th>Section</th> <th>Color</th> <th>Notes</th> </tr> </thead> <tbody> <tr> <td>Table ID</td> <td>N/A</td> <td>The Table ID will be the worksheet name. Each worksheet in the Excel file will define a new table.</td> </tr> <tr> <td>Table Name</td> <td>Yellow</td> <td>The name and description of the table, to be printed as the table’s header.</td> </tr> <tr> <td>Row Header</td> <td>Orange</td> <td>The text to display above the rows. Example: Characteristics Measured.</td> </tr> <tr> <td>Columns</td> <td>Blue</td> <td>The table’s columns. If there are multiple rows of column definitions, then columns and sub-columns will be created. The column definition should consist of the column text, and, if you want to refer to a column (such as when filling cells), also a column ID. The ID should be set off from the text by two slashes (//). Example: Treatment // TX. “Treatment” will display, while TX will be assigned as the column ID. You can</td> </tr> </tbody> </table> also specify a footnote reference, set off by two carats (^). Example: Treatment // TX ^^ A. This will create a reference to footnote A, as described below. <table> <thead> <tr> <th>Rows</th> <th>Red</th> <th>The table’s rows. If there are multiple columns of row definitions, then rows and sub-rows will be created. The row definition should consist of the row text, and, if you want to refer to a row (such as when filling cells), also a row ID. The ID should be set off from the text by two slashes (/). Example: Age // AGE. “Age” will display, while AGE will be assigned as the row ID. You can also specify a footnote reference, set off by two carats (^). Example: Age // AGE ^^ A. This will create a reference to footnote A, as described below.</th> </tr> </thead> <tbody> <tr> <td>Footnotes</td> <td>Green</td> <td>The footnote definitions. Each definition starts with a footnote reference, as used above, followed by two carats (^), followed by the footnote text. Example: A ^^ As measured in the 180 days prior to the index date.</td> </tr> </tbody> </table> **TABLE CREATION MACROS** ```sas %table_Init(table_library) ``` Initializes the table creation functions. Call this macro before beginning any other table operations. **table_library** *required* Name of a SAS library in which the table data files can be stored. ```sas %table_AddTablesFromExcel(workbook_path); ``` Adds all the tables defined in the Excel spreadsheet. See the section on “Excel Spreadsheet Format” for more information. **workbook_path** *required* A file path to the Excel workbook with the table(s) defined. ```sas %table_AddTable(table_id, description); ``` Adds a table. **table_id** *required* Name of the new table; internal name only. Should be one word with no special characters. **description** *required* Description of the table. Will be included in the output. ```sas %table_Copy(source, dest); ``` After creating a table, copies the structure (rows, columns) of a source table to a destination table. source **required** Name of a the table to copy from. dest **required** Name of a the table to copy to. %table_AddRow(table_id, row_id, description, parent_id=.); %table_AddCol(table_id, col_id, description, parent_id=.); Adds a row (column) to the table. table_id **required** ID of an existing table. row_id (col_id) **required** Unique ID of the new row in this table. description **required** Description (text) of the row (column). Will be included in the output. parent_id *optional; default=.* Used to create sub-rows (columns). ID of an existing row (column) in this table, or “.” to indicate no parent. %table_AddHeaderRow(table_id, row_id, description, parent_id=.); %table_AddHeaderCol(table_id, col_id, description, parent_id=.); Adds a header (bolded) row to the table. See above for syntax. %table_AddEmptyRow(table_id, parent_id=.); Adds an empty (blank) row to the table. See above for syntax. %table_AddToRowDescription(table_id, row_id, description); %table_AddToColDescription(table_id, col_id, description); Adds text to the row description. Used to add information to a row’s output text after the row has been created. table_id **required** ID of an existing table. row_id **required** ID of an existing row in this table. description **required** Description (text) to be added to the row’s existing description. Will be included in the output. %table_SetRowsTitle(table_id, description); Adds text above the first table row. - **table_id**: *required* - ID of an existing table. - **description**: *required* - Description (text) to be printed above the first row of the table. %table_FillCell(table_id, row_id, col_id, contents); Sets the specified cell to output the specified contents. - **table_id**: *required* - ID of an existing table. - **row_id**: *required* - ID of an existing row. Note that in tables with sub-rows, this must indicate a row in the lowest level of nesting. - **col_id**: *required* - ID of an existing column. Note that in tables with sub-columns, this must indicate a column in the lowest level of nesting. - **contents**: *required* - Contents to output. Contents will be output as-is and can contain HTML. %table_FillCellNum(table_id, row_id, col_id, num, num_decimals = 0); Fill a cell with formatted numeric information. Syntax as above, plus: - **num**: *required* - The number to insert into the cell. - **num_decimals**: *optional; default = 0* - The number of decimal places to print. %table_FillCellCommaNum(table_id, row_id, col_id, num, num_decimals = 0); Fill a cell with formatted numeric information, adding commas. Syntax as above. %table_FillCellPct(table_id, row_id, col_id, pct, num_decimals = 1, multiply=0); Fill a cell with formatted percentage information. Syntax as above, plus: - **pct**: *required* - The percentage to insert into the cell. - **num_decimals**: *optional; default = 1* - The number of decimal places to print. multiply *optional; default = 0* An indicator (1 or 0) specifying whether to multiply pct by 100 before printing. ```latex %table_FillCellMeanSD(table_id, row_id, col_id, mean, sd, num_decimals = 1, percentage = 0); ``` Fill a cell with a formatted mean and standard deviation. Syntax as above, plus: <table> <thead> <tr> <th>Parameter</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>mean</td> <td>The mean to insert into the cell.</td> </tr> <tr> <td>sd</td> <td>The standard deviation to insert into the cell.</td> </tr> <tr> <td>num_decimals</td> <td>The number of decimal places to print.</td> </tr> <tr> <td>percentage</td> <td>An indicator (1 or 0) specifying whether the mean and SD should be formatted as a percentage.</td> </tr> </tbody> </table> ```latex %table_FillCellMedianIQR(table_id, row_id, col_id, median, q1, q3, num_decimals = 1, percentage = 0); ``` Fill a cell with a formatted median and interquartile range. Syntax as above, plus: <table> <thead> <tr> <th>Parameter</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>median</td> <td>The median to insert into the cell.</td> </tr> <tr> <td>q1</td> <td>The lower quartile to insert into the cell.</td> </tr> <tr> <td>q3</td> <td>The upper quartile to insert into the cell.</td> </tr> <tr> <td>num_decimals</td> <td>The number of decimal places to print.</td> </tr> </tbody> </table> ```latex %table_FillCellEstCI(table_id, row_id, col_id, est, ci_low, ci_high, num_decimals = 2); ``` Fill a cell with a formatted estimate and a confidence interval. Syntax as above, plus: <table> <thead> <tr> <th>Parameter</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>est</td> <td>The point estimate to insert into the cell.</td> </tr> <tr> <td>ci_low</td> <td>The lower confidence interval of the point estimate to insert into the cell.</td> </tr> <tr> <td>ci_high</td> <td>The upper confidence interval of the point estimate to insert into the cell.</td> </tr> </tbody> </table> num_decimals optional; default = 2 The number of decimal places to print. %table_FillCellOR(table_id, row_id, col_id, est, ci_low, ci_high, num_decimals = 2); Fill a cell with a formatted odds (hazard, rate) ratio and a confidence interval. Syntax as above. %table_FillCellRD(table_id, row_id, col_id, est, ci_low, ci_high, num_decimals = 2); Fills a cell with a formatted risk (rate) difference and a confidence interval. Syntax as above. %table_FillCellFromPHREG(table_id, row_id, col_id, phreg_out_ds, variable, num_decimals = 2); Fills a cell with a formatted hazard ratio using output from PROC PHREG. Syntax as above, plus: phreg_out_ds required The dataset produced by PHREG using ODS OUTPUT XXX=phreg_out_ds. variable required The name of the variable of interest in the dataset (usually the exposure). %table_FillCellFromLOGISTIC(table_id, row_id, col_id, logistic_out_ds, variable, num_decimals = 2); Fills a cell with formatted odds ratio using output from PROC LOGISTIC. Syntax as above, plus: logistic_out_ds required The dataset produced by LOGISTIC using ODS OUTPUT OddsRatios = logistic_out_ds. %table_FillCellFromGENMOD(table_id, row_id, col_id, genmod_out_ds, variable, exponentiate = 0, num_decimals = 2); Fill a cell with a formatted estimate and CI using output from PROC GENMOD. Syntax as above, plus: genmod_out_ds required The dataset produced by GENMOD using ODS OUTPUT XXX=genmod_out_ds. exponentiate optional; default = 0 An indicator (1 or 0) specifying whether to exponentiate the figures in the GENMOD output before filling the cell. %table_FillCellMedianFromUNIVAR(table_id, row_id, col_id, univariate_out_ds, variable, num_decimals = 2, percentage = 0); Fills a cell with formatted a median and interquartile range using ODS output from UNIVARIATE. Syntax as above, plus: univariate_out_ds required The dataset produced by UNIVARIATE using ODS OUTPUT Quartiles = univariate_out_ds. %table_FillCellMeanFromUNIVAR(table_id, row_id, col_id, univariate_out_ds, variable, num_decimals = 2, percentage = 0); Fills a cell with a mean and SD using ODS output from UNIVARIATE. Syntax as above, plus: univariate_out_ds required The dataset produced by UNIVARIATE using ODS OUTPUT Moments = univariate_out_ds. %table_FillCellMedianFromMEANS(table_id, row_id, col_id, means_out_ds, variable, num_decimals = 2, percentage = 0); Fills a cell with formatted a median and interquartile range using ODS output from MEANS. MEANS should be run with the options including MEDIAN, Q1, and Q3. Syntax as above, plus: means_out_ds required The dataset produced by MEANS using ODS OUTPUT Summary = means_out_ds. %table_FillCellMeanFromMEANS(table_id, row_id, col_id, means_out_ds, variable, num_decimals = 2, percentage = 0); Fill a cell with a mean and SD using ODS output from MEANS. MEANS should be run no options, or options including MEAN and STDDEV. Syntax as above, plus: means_out_ds required The dataset produced by MEANS using ODS OUTPUT Summary = means_out_ds. %table_FillCellNumFromFREQ(table_id, row_id, col_id, freq_out_ds, where=); Fill a cell with a frequency (number) using ODS output from FREQ. Syntax as above, plus: freq_out_ds required The dataset produced by FREQ using ODS OUTPUT CrossTabFreqs = freq_out_ds. where optional; default = (1=1) [all rows] The WHERE clause used to identify the single value desired from the PROC FREQ. If FREQ is run with TABLE exposure*covariate, then one WHERE clause would be WHERE=(exposure=1 AND covariate=1). %table_FillCellRowPctFromFREQ(table_id, row_id, col_id, freq_out_ds, where=, num_decimals = 2); %table_FillCellColPctFromFREQ(table_id, row_id, col_id, freq_out_ds, where=, num_decimals = 2); Fill a cell with a percentage of the row (column) using ODS output from FREQ. Syntax as above. %table_GetCell(table_id, row_id, col_id); Get the value of a cell that has been filled with one of the %table_FillCell macros. Syntax as above. %table_Output(table_id, filepath); %table_OutputAll(filepath); Outputs all defined tables to files in filepath. Files will be named using the tables’ IDs. filepath required The path at which to output the tables. EXAMPLE CODE In the following example code, the required input is printed in bold. Other options are printed as an example but are not required for running the macro. /* include necessary files */ %include "/path/to/macro/directory/table_creator.sas"; %include "/path/to/macro/directory/java_utils.sas"; /* initialize the Java code */ %javautils_InitClasspathUpdate; /* remember, no spaces in the path! */ %javautils_AddToClasspath(/path/to/java/files/pharmacoepi.jar); /* create a library where the table data files will be stored */ LIBNAME tables "/path/to/table/output/library"; /* initialize the table code */ %table_Init(tables); /* ------------------------------- */ /* OPTION 1: Define tables from Excel */ /* ------------------------------- */ %table_AddTablesFromExcel(%NRBQUOTE(c:\files\workbook.xls)); /* ------------------------------- */ /* OPTION 2: Define tables manually */ /* ------------------------------- */ /* add a new Table 1 */ %table_AddTable(TABLE1, %NRBQUOTE(Table 1)); /* create columns for exposed patients */ %table_AddHeaderCol(TABLE1, EXPOSED, %NRBQUOTE(Exposed)); /* two sub-columns: mean and median */ %table_AddCol(TABLE1, EXPOSED_MEAN, %NRBQUOTE(Mean), parent_id=EXPOSED); %table_AddCol(TABLE1, EXPOSED_MEDIAN, %NRBQUOTE(Median), parent_id=EXPOSED); /* create columns for unexposed patients */ %table_AddHeaderCol(TABLE1, UNEXPOSED, %NRBQUOTE(Unexposed)); %table_AddCol(TABLE1, UNEXPOSED_MEAN, %NRBQUOTE(Mean), parent_id=UNEXPOSED); %table_AddCol(TABLE1, UNEXPOSED_MEDIAN, %NRBQUOTE(Median), parent_id=UNEXPOSED); /* create a row: age */ %table_AddRow(TABLE1, AGE, %NRBQUOTE(Age)); /* ------------------------------- */ /* Fill the table cells with information */ /* ------------------------------- */ /* run UNIVARIATE and generate the data for the cells */ ODS OUTPUT Quantiles = quantiles; ODS OUTPUT Moments = moments; PROC UNIVARIATE; WHERE exposed = 1; VAR age; RUN; /* fill the exposed mean cell with data from UNIVARAIATE */ %table_FillCellMeanFromUNIVAR(TABLE1, AGE, EXPOSED_MEAN, moments, age); /* fill the exposed median cell with data from UNIVARAIATE */ %table_FillCellMedianFromUNIVAR(TABLE1, AGE, EXPOSED_MEDIAN, quantiles, age); /* repeat for unexposed patients */ ODS OUTPUT Quantiles = quantiles; ODS OUTPUT Moments = moments; PROC UNIVARIATE; WHERE exposed = 0; VAR age; RUN; %table_FillCellMeanFromUNIVAR(TABLE1, AGE, UNEXPOSED_MEAN, moments, age); %table_FillCellMedianFromUNIVAR(TABLE1, AGE, UNEXPOSED_MEDIAN, quantiles, age); /* ------------------------------- */ /* Output tables */ /* ------------------------------- */ /* output the table HTML file in the specified directory */ %table_Output(%NRBQUOTE(/path/to/table/output)); Question: The hd-PS model does not converge; instead, SAS warns of quasi-complete separation of data points. What do I do about this? Quasi-complete separation is an issue when the goal is to interpret the point estimates of the PS model, rather than just use the predicted values. Since a PS uses only the predicted values, quasi-complete separation is not ideal but does not pose a problem. Those variables for which there is separation will not contribute to the predicted value, but also should not in any way harm the prediction. Question: I am having memory problems in SAS. SAS requires configuration of the Java subsystem to allocate the system its needed memory. There are SAS support documents that describe this, including: http://support.sas.com/documentation/cdl/en/grstatgraph/63878/HTML/default/viewer.htm#n099d3bkbcllg5n1enitj9b8y1f.htm. Question: I am getting a classpath-related error. Check that you specified the path_jar_file variable correctly. NOTE: For use in SAS, classpaths cannot contain spaces! This is a SAS limitation. Question: Where is the core of hd-PS? Can I see the code? The core components of hd-PS – the variable creation, ranking and selection – are all within the Java code. The Java system allows for much faster and more efficient computation, and allows for parallel computation of each of the dimensions. (Version 1 of hd-PS was implemented entirely in SAS and was rather slow.) The Java source code is contained within the pharmacoepi.jar file and is released under and open-source license.
{"Source-Url": "http://www.drugepi.org/wp-content/uploads/2013/10/Using_the_Pharmacoepi_Toolbox_in_SAS_2.4.15.pdf", "len_cl100k_base": 9351, "olmocr-version": "0.1.53", "pdf-total-pages": 23, "total-fallback-pages": 0, "total-input-tokens": 50522, "total-output-tokens": 10621, "length": "2e13", "weborganizer": {"__label__adult": 0.0007243156433105469, "__label__art_design": 0.00080108642578125, "__label__crime_law": 0.00102996826171875, "__label__education_jobs": 0.006839752197265625, "__label__entertainment": 0.00016307830810546875, "__label__fashion_beauty": 0.00033402442932128906, "__label__finance_business": 0.0015764236450195312, "__label__food_dining": 0.0008831024169921875, "__label__games": 0.0014905929565429688, "__label__hardware": 0.0020465850830078125, "__label__health": 0.0224761962890625, "__label__history": 0.0006432533264160156, "__label__home_hobbies": 0.0003631114959716797, "__label__industrial": 0.0012922286987304688, "__label__literature": 0.0004982948303222656, "__label__politics": 0.0004963874816894531, "__label__religion": 0.0007801055908203125, "__label__science_tech": 0.251220703125, "__label__social_life": 0.0002961158752441406, "__label__software": 0.11773681640625, "__label__software_dev": 0.58642578125, "__label__sports_fitness": 0.0008974075317382812, "__label__transportation": 0.0005645751953125, "__label__travel": 0.0004572868347167969}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 37778, 0.00983]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 37778, 0.66441]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 37778, 0.71962]], "google_gemma-3-12b-it_contains_pii": [[0, 1121, false], [1121, 1765, null], [1765, 3852, null], [3852, 5762, null], [5762, 7965, null], [7965, 10186, null], [10186, 11972, null], [11972, 14087, null], [14087, 14496, null], [14496, 15875, null], [15875, 17560, null], [17560, 19460, null], [19460, 20465, null], [20465, 22529, null], [22529, 24355, null], [24355, 25867, null], [25867, 27437, null], [27437, 29351, null], [29351, 30945, null], [30945, 32872, null], [32872, 34522, null], [34522, 36236, null], [36236, 37778, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1121, true], [1121, 1765, null], [1765, 3852, null], [3852, 5762, null], [5762, 7965, null], [7965, 10186, null], [10186, 11972, null], [11972, 14087, null], [14087, 14496, null], [14496, 15875, null], [15875, 17560, null], [17560, 19460, null], [19460, 20465, null], [20465, 22529, null], [22529, 24355, null], [24355, 25867, null], [25867, 27437, null], [27437, 29351, null], [29351, 30945, null], [30945, 32872, null], [32872, 34522, null], [34522, 36236, null], [36236, 37778, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 37778, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 37778, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 37778, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 37778, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 37778, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 37778, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 37778, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 37778, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 37778, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 37778, null]], "pdf_page_numbers": [[0, 1121, 1], [1121, 1765, 2], [1765, 3852, 3], [3852, 5762, 4], [5762, 7965, 5], [7965, 10186, 6], [10186, 11972, 7], [11972, 14087, 8], [14087, 14496, 9], [14496, 15875, 10], [15875, 17560, 11], [17560, 19460, 12], [19460, 20465, 13], [20465, 22529, 14], [22529, 24355, 15], [24355, 25867, 16], [25867, 27437, 17], [27437, 29351, 18], [29351, 30945, 19], [30945, 32872, 20], [32872, 34522, 21], [34522, 36236, 22], [36236, 37778, 23]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 37778, 0.04312]]}
olmocr_science_pdfs
2024-12-12
2024-12-12
e010ed18bd40f63366db84a0bcf2c26b127e4fb6
Gemini: A Distributed Crash Recovery Protocol for Persistent Caches* Shahram Ghandeharizadeh, Haoyu Huang Database Laboratory Technical Report 2018-06 Computer Science Department, USC Los Angeles, California 90089-0781 {shahram,haoyuhua}@usc.edu Abstract Gemini is a distributed crash recovery protocol for persistent caches. When a cache instance fails, Gemini assigns other cache instances to process its reads and writes. Once the failed instance recovers, Gemini starts to recover its persistent content while using it to process reads and writes immediately. Gemini does so while guaranteeing read-after-write consistency. It also transfers the working set of the application to the recovering instance to maximize its cache hit ratio. Our evaluation shows that Gemini restores hit ratio two orders of magnitude faster than a volatile cache. Working set transfer is particularly effective with workloads that exhibit an evolving access pattern. 1 Introduction Modern web workloads with a high read to write ratio enhance the performance of the underlying data store with a caching layer, e.g., memcached [25] and Redis [6]. These caches process application reads [26] much faster by looking up results of queries instead of processing them. A volatile cache loses its data upon a power failure or a process restarts [12]. Upon recovery, the cache provides sub-optimal performance until it rebuilds the application’s working set (defined as the collection of data items that the application references repeatedly [9]). The time to restore hit ratio depends on the size of the working set, the time to compute a cache entry and write it to an instance. Yiying et al. [34] report hours to days to warm up cold caches for typical data center workloads. Existing work on persistent caches [32, 24, 30, 11] recovers cache entries intact from a failure without recovering their latest state, producing stale data. Stale data are undesirable because they defy a user’s expectation and increase programming complexity to reason and handle all the complex cases [23]. A crash recovery protocol should preserve read-after-write --- *A shorter version of this paper appeared in 19th International Middleware Conference (Middleware ’18), Rennes, France, December, 2018. Figure 1: Number of stale reads observed after 20 cache instances recover from a 10-second and a 100-second failure. consistency [23] even in the event of failure. The caching layer must guarantee that data produced by a confirmed write is observed by all subsequent reads. Figure 1 shows the number of reads per second that violate read-after-write consistency, after 20 cache instances (instances) recover from a 10-second and a 100-second failure, respectively. These results are obtained using a trace derived from Facebook’s workload [5, 21]. This number peaks immediately after the caches recover. It drops as the application processes a write that deletes an entry which happens to be stale. The percentage of stale reads is 6% of total reads at the peak for a 100-second failure. A distributed crash recovery protocol for caches should also recover the latest application’s working set to provide the highest cache hit ratio. If the working set evolves during an instance’s failure, then recovering an entry that is not accessed in the future (or is evicted) is wasted work. We present Gemini, a distributed crash recovery protocol for persistent caches. Gemini preserves read-after-write consistency in the presence of instance failures, reducing the number of stale reads of Figure 1 to zero. Gemini partitions an application’s key space into fragments with one or more fragments assigned to an instance. When an instance fails, Gemini assigns its fragments to other instances. Gemini maintains a dirty list for each fragment of the failed instance. These dirty lists are used to recover a consistent state of the cache entries of the failed instance once it recovers. Moreover, Gemini transfers the latest working set to the recovering instance. Technical challenges addressed by Gemini are as follows: 1. How to detect undesirable race conditions that may cause a cache to generate stale values? See Section 3.2. 2. How to restore the cache hit ratio of a recovering instance as fast as possible? See Section 3.2.2. 3. How does Gemini discard millions and billions of cache entries assigned to a fragment when it detects it cannot recover a consistent state of its keys? See Section 3.2.4. 4. How does Gemini provide read-after-write consistency with an arbitrary combination of its client and instance failures? See Section 3.3. The primary contribution of this study is an efficient design of Gemini that addresses the above challenges. Gemini uses the eviction policy of an instance to discard its potentially invalid cache entries lazily. Its client detects stale cache entries and deletes them using a simple counter mechanism [13]. This mechanism facilitates read-after-write consistency in the presence of instance failures. Gemini uses leases [14] to prevent undesirable race conditions. We evaluate Gemini using the YCSB benchmark [7] and a synthetic trace derived from Facebook’s workload [5]. We measure the overhead of maintaining dirty lists of cache entries during an instance’s failure and show it is insignificant. We compare Gemini’s performance during recovery with a technique that discards the content of the cache. Our experiments show that Gemini restores the cache hit ratio by more than two orders of magnitude faster than a volatile cache. 2 Overview Figure 2 shows Gemini’s architecture, consisting of cache servers, a coordinator, and a client library. Table 1 provides a definition of these components and the terminology used in this paper. A cache server hosts one or more instances that store cache entries persistently. Each instance is assigned a fraction of its hosting cache server’s memory. Cache entries are partitioned into subsets. Each subset is termed a fragment. Several fragments are assigned to an instance. An application uses a Gemini client to issue requests to an instance. This client caches a configuration and uses it to route a request to a fragment for processing. A configuration is an assignment of fragments to instances. A Gemini client uses a deterministic function to map a request to an instance using a configuration. To illustrate, Figure 3 shows the processing of a read referencing a key $K_i$. A Gemini client uses a hash function to map this key to a cell of the configuration. This cell identifies a fragment. Its metadata identifies the fragment’s mode and the instance that holds a lease on it. A read that observes a cache miss queries the data store, computes a cache entry, and inserts this entry in an instance for future references. There are several policies for processing writes. With write-around [26], a write invalidates the relevant cache entry and updates the data store. With either write-through or write-back, the write updates the cache entry and the data store. While write-through applies writes to the data store synchronously, write-back buffers them and applies them to the data store asynchronously. For the rest of this paper and due to lack of space, we make the following assumptions. First, Gemini and its application use the write-around policy. Gemini’s implementation with write-through is different. Second, we present a client side implementation of Gemini. Its server side implementation using its instances would be different. ### 2.1 Coordinator and Configuration Management An instance must have a valid lease on a fragment in order to process a request that references this fragment. The instance obtains the lease from the coordinator. The lease has a fixed lifetime and the instance must renew its lease to continue processing requests that reference this fragment. When the coordinator assigns a lease on a fragment, say Fragment A Configuration with Id=999 <table> <thead> <tr> <th>Fragment 0</th> <th>Fragment k</th> <th>Fragment k+1</th> <th>Fragment F-1</th> </tr> </thead> <tbody> <tr> <td>Primary: Instance-1:3</td> <td>Primary: Instance-0:5</td> <td>Primary: Instance-0:5</td> <td>Primary: Instance-83:2</td> </tr> <tr> <td>Secondary: Instance-0:0</td> <td>Config Id: 100</td> <td>Config Id: 200</td> <td>Config Id: 123</td> </tr> <tr> <td>Mode: Recovery</td> <td>Mode: Normal</td> <td>Mode: Normal</td> <td>Mode: Transient</td> </tr> </tbody> </table> Figure 3: Client’s processing of a request for $K_i$ using a configuration. $j$ where $j$ is a cell in Figure 3, it identifies the instance hosting either the fragment’s primary replica $PR_{j,p}$ or its secondary replica $SR_{j,s}$. The first time Fragment $j$ is assigned to an instance $I_p$, that replica is identified as its primary $PR_{j,p}$. Failure of this instance causes the coordinator to assign another instance $I_s$ to host Fragment $j$, termed its secondary replica $SR_{j,s}$. The coordinator maintains the configuration and grants leases. It identifies each of its published configurations with an increasing id. Each time an instance fails or recovers, the coordinator (a) computes a new configuration and increments the id, (b) notifies impacted instances that are available of the new id, and (c) inserts the new configuration as a cache entry in these instances. Instances memoize the latest configuration id. However, they are not required to maintain the latest configuration permanently because their cache replacement policy may evict the configuration. To tolerate coordinator failures, Gemini’s coordinator consists of one master and one or more shadow coordinators maintained using Zookeeper [16]. When the coordinator fails, one of the shadow coordinators is promoted to manage the configuration, similarly to RAM-Cloud [27]. 2.2 Life of a fragment Gemini manages a fragment in three distinct modes: normal, transient, and recovery, see Figure 4. Gemini assigns a fragment to an available instance in the cluster, constructing its primary replica. In normal mode, clients issue read and write requests to a fragment’s primary replica. The primary replica becomes unavailable when its hosting instance fails. The coordinator assigns another instance to host this fragment which creates a secondary replica for the fragment. Moreover, Gemini transitions mode of the fragment to transient ①. Initially, read requests observe cache misses in the secondary replica since it is empty. These requests populate this replica similar to the normal mode of operation. A write request (a) invalidates the impacted cache entry in the secondary replica, and (b) maintains the impacted key in a dirty list. The dirty list is stored in the secondary replica. The primary replica of a fragment becomes available once its instance recovers. The coordinator sets the fragment’s mode to recovery ② and publishes a new configuration. This causes a Gemini client to fetch the dirty list of the fragment from the instance hosting its secondary replica. With a read or a write that references a key in this list, a client deletes the key from the primary replica. Moreover, a client transfers the latest working set from the fragment’s secondary replica to its primary replica. This restores the cache hit ratio of the recovering instance that host the fragment’s primary replica. Gemini also employs recovery workers to speed up processing dirty lists of fragments in recovery mode. Once the dirty list is processed and optionally transfer of the working set completes, Gemini transitions the fragment to normal mode 3. Should the primary replica become unavailable before the recovery completes, the coordinator transitions the fragment back to transient mode 5. The coordinator may discard cache entries in the primary replica 4 if (a) the overhead of maintaining dirty cache entries outweighs its benefit, or (b) the dirty list is unavailable because the instance hosting the secondary replica either failed or evicted the dirty list. During the interval of time, from when the instance hosting a fragment’s primary replica fails, to when the coordinator publishes its secondary replica, a Gemini client suspends processing of writes that reference the fragment. This preserves read-after-write consistency. Moreover, all reads are processed using the data store. Once a client obtains the latest configuration that identifies a secondary, reads and writes are resumed using the secondary replica of the fragment. 2.3 Leases A Gemini’s client acquires Inhibit (I) and Quarantine (Q) leases [14] on application’s cache entries to ensure read-after-write consistency. Moreover, its recovery worker acquires Redlease [4] on a dirty list to prevent another recovery worker from processing the same dirty list. While I and Q leases may collide on the same cache entry, it is not possible for these leases to collide with a Redlease. Similarly, a Redlease may collide with another Redlease and not either an I or a Q lease. IQ leases and Redlease have a lifetime in the order of milliseconds. Gemini’s coordinator grants leases on fragments to instances. These leases have a lifetime in the order of seconds if not minutes depending on the reliability of an instance. Below, we describe IQ leases and Redlease in turn. Gemini uses the concept of sessions. A session is an atomic operation that reads and writes one cache entry and issues one transaction to the data store. It obtains leases on cache entries from an instance. Table 2 shows the compatibility of I and Q leases. An instance grants an I lease on a key to a request that observes a cache miss for the value of this key. Once the requester computes the missing value and inserts it in the cache, its I lease must be valid in order for its insert to succeed. Otherwise, the instance ignores the inserted value. <table> <thead> <tr> <th>Requested Lease</th> <th>Existing Lease</th> </tr> </thead> <tbody> <tr> <td>I</td> <td>Back off</td> </tr> <tr> <td>Q</td> <td>Void I &amp; grant Q</td> </tr> </tbody> </table> I leases are incompatible with one another. When multiple concurrent reads observe a cache miss for the same key, only one of them is granted the I lease. The others back off and look up the cache again. The read granted the I lease queries the data store and populates the cache with the missing entry. When other concurrent requests try again, they find this entry and consume it. The I lease prevents the thundering herd phenomenon of [26], where the data store is flooded with concurrent queries that are identical. A write request must acquire a Q lease on its referenced cache entry prior to deleting it (write-around). A Q lease voids an existing I lease on the key. This prevents the race condition where a concurrent read would populate an instance with a stale value [14]. With write-around, Q leases are compatible because the impacted cache entry is deleted and the order in which two or more sessions delete this entry does not result in an undesirable race condition. After acquiring a Q lease, the session updates the data store, deletes the key, and releases its Q lease. When a Q lease times out, the instance deletes its associated cache entry. A Redlease protects a dirty list, to provide mutual exclusion between recovery workers that might process this list. Once a Redlease on a dirty list is granted to a recovery worker, a request by another worker must back off and try again. ### 3 Gemini Recovery Protocol Given a large number of instances, multiple instances may fail and recover independently and concurrently. Gemini’s recovery focuses on impacted fragments. It processes each fragment independent of the others, facilitating recovery of two or more fragments at the same time. Gemini uses IQ leases described in Section 2.3 to process a request that references a fragment in normal mode. Below, we describe the processing of a request that references a fragment in either transient or recovery mode. Appendix A provides a formal proof of read-after-write consistency. #### 3.1 Transient Mode Fragment $j$ in transient mode consists of both a primary replica $PR_{j,p}$ on a failed instance $I_p$ and a secondary replica $SR_{j,s}$ on an available instance $I_s$. Once a client obtains a configuration that identifies a fragment in transient mode, it retries its outstanding requests using the secondary replica and directs all future requests to this secondary. A client processes read requests in the same way as in normal mode and populates the secondary. In transient mode, the instance $I_s$ hosting $SR_{j,s}$ maintains a dirty list for the fragment in anticipation of the recovery of the primary $PR_{j,p}$. The dirty list is represented as a cache entry. A write request appends its referenced key to the dirty list. The dirty list may be lost due to the instance $I_s$ failing or its cache replacement technique evicting the dirty list. Either causes the coordinator to terminate transient mode and discard the primary replica $PR_{j,p}$. Next, the coordinator either promotes the existing secondary to be the primary or identifies a new primary for the fragment on a new instance. To detect dirty list evictions, the dirty list is initialized with a marker. The marker enables Gemini to detect the race condition where one client appends to the list while the instance $I_s$ evicts the list. Even though the client succeeds in generating a new dirty list, it is detected as being partial because it lacks the marker. #### 3.2 Recovery Mode Once the coordinator detects a failed instance has recovered, Gemini starts to recover its fragments’ primary replicas while allowing them to take immediate ownership of their valid cache entries to process requests. It employs recovery workers to process dirty keys, expediting recovery of a fragment. Recovery of a fragment is configurable in two ways. First, Gemini’s recovery workers may either invalidate a dirty key from its fragment’s primary replica or overwrite its value with the latest from the secondary replica. Second, one may enable or disable Gemini’s transfer of the working set. This results in the four possible variations of Gemini shown in Figure 5. Below, we provide its details. ![Figure 5: Four Gemini variations.](image) ### 3.2.1 Processing Client Requests When an instance becomes available, it is possible that only a subset of its fragments’ primary replicas is recoverable. Those that lack dirty lists must be discarded as detailed in Section 3.2.4. Gemini uses Algorithm 1 to allow a primary replica to take immediate ownership of its still valid cache entries to process requests. Details of the algorithm are as follows. A client fetches the dirty list of each fragment in recovery mode from the instance hosting its secondary replica. A write request deletes its referenced key from both the primary and the secondary replicas. A read request checks if its referenced key is on the dirty list. If so, it deletes this key from the primary replica and acquires an I lease on this key from the instance hosting the primary replica. It looks up the key’s value in the secondary replica. If found then it proceeds to insert the obtained value in the primary replica. Otherwise, it uses the data store to compute the missing value and inserts it in the primary. ### 3.2.2 Working Set Transfer The application’s working set may have evolved during an instance’s failure. This means some of its cache entries are obsolete. To minimize cache misses, a Gemini client copies popular cache entries from a secondary to a primary. Gemini uses IQ leases to prevent race conditions. This is realized as follows, see lines 11 to 15 in Algorithm 1. When a request observes a cache miss in a primary, the client looks up its secondary. If it finds a value in the secondary, it inserts the entry in the primary. Otherwise, it reports a cache miss. A write request also deletes its referenced key in the secondary replica, see line 3 in Algorithm 2. Gemini terminates the working set transfer once either (a) the cache hit ratio of the primary $PR_{j,p}$ exceeds a threshold $h$ or (b) the cache miss ratio of the secondary $SR_{j,s}$ exceeds a threshold $m$. Benefits and costs of the working set transfer are quantified using $h$. Algorithm 1: Client: processing get on a key $k$ mapped to a fragment $j$ in recovery mode. **Input:** key $k$ **Result:** key $k$’s value Let $PR_{j,p}$ be fragment $j$’s primary replica on instance $I_p$. Let $SR_{j,s}$ be fragment $j$’s secondary replica on instance $I_s$. Let $D_j$ be fragment $j$’s dirty list. 1. if $k \notin D_j$ then 2. $v = PR_{j,p}.iqget(k)$ 3. if $v \neq \text{null}$ then 4. return $v$ 5. end 6. else 7. $PR_{j,p}.iset(k)$ 8. $D_j = D_j - k$ 9. end 10. /* Cache miss in the primary. */ 11. if working set transfer is enabled then 12. $v = SR_{j,s}.get(k)$ 13. if $v \neq \text{null}$ then 14. $PR_{j,p}.iqset(k, v)$ 15. return $v$ 16. end 17. /* Cache miss in both replicas. */ 18. $v = \text{query the data store}$ 19. $PR_{j,p}.iqset(k, v)$ 20. return $v$ Algorithm 2: Client: processing write on a key $k$ mapped to a fragment $j$ in recovery mode. **Input:** key $k$ Let $PR_{j,p}$ be fragment $j$’s primary replica on instance $I_p$. Let $SR_{j,s}$ be fragment $j$’s secondary replica on instance $I_s$. Let $D_j$ be fragment $j$’s dirty list. 1. $PR_{j,p}.qareg(k)$ 2. if working set transfer is enabled then 3. $SR_{j,s}.delete(k)$ 4. end 5. Update the data store 6. $PR_{j,p}.dar(k)$ 7. // Delete $k$ and release the Q lease in the primary. and $m$, respectively. We suggest to set $h$ to be the cache hit ratio of the primary $PR_{j,p}$ prior to its instance failing while considering some degree of variation $\epsilon$. We set $m$ to be $1-h+\epsilon$. Algorithm 3: Recovery worker: recover fragments in recovery mode. \[\textbf{Input:} \text{A list of fragments in recovery mode}\] \begin{enumerate} \item for each fragment $j$ in recovery mode do \item Let $PR_{j,p}$ be fragment $j$’s primary replica on instance $I_p$. \item Let $SR_{j,s}$ be fragment $j$’s secondary replica on instance $I_s$. \item Let $D_j$ be fragment $j$’s dirty list. \item Acquire a Redlease on $D_j$ in $SR_{j,s}$. \item if fail to acquire the lease then \item continue \item end \item if overwrite dirty keys is enabled then \item for each key $k$ in $D_j$ do \item $PR_{j,p}$.iset($k$) \item $v = SR_{j,s}$.get($k$) \item if $v \neq \text{null}$ then \item $PR_{j,p}$.iqset($k$, $v$) \item else \item $PR_{j,p}$.idelete($k$) \hspace{1cm} // Release the I lease. \item end \item end \item else \item Delete keys in $D_j$ in $PR_{j,p}$ \item end \item end \item Delete $D_j$ and release the Redlease \end{enumerate} 3.2.3 Recovery Workers Gemini uses stateless recovery workers to speed up recovery. These workers overwrite a cache entry on the dirty list in the primary with its latest value from the secondary. Algorithm 3 shows the pseudo-code of a recovery worker. A worker obtains a Redlease [4] on the dirty list of a fragment. All other lease requesters must back off and try again. This ensures different workers apply dirty lists on primary replicas of different fragments: one worker per fragment with a dirty list. Next, the worker fetches the dirty list from the secondary. For each key on this list, it deletes it from the primary and obtains an I lease on the key from its instance. Next, it looks up the key in the secondary. If it finds the key then it writes it to the primary. Otherwise, it releases its I lease and proceeds to the next key. Once all dirty keys are processed, the recovery worker deletes the dirty list and releases its Redlease. Algorithm 3 also shows a setting that requires the recovery worker to delete dirty keys from the primary, see line 20. This is appropriate when the working set of an application evolves. In this case, overwriting keys using values from a secondary imposes an additional overhead without providing a benefit. Hence, deleting dirty keys is more appropriate. Once a recovery worker exhausts the dirty list for a fragment, it notifies the coordinator to change the mode of this fragment to normal and publish a new configuration. This causes the clients to stop looking up keys in the dirty list of this fragment and to discard this dirty list. 3.2.4 Discarding Fragments Gemini uses the coordinator’s assigned configuration id to distinguish cache entries that can be reused from those that must be discarded. Each cache entry stores the configuration id that wrote its value. Moreover, each fragment of a configuration identifies the id of the configuration that updated it. For a cache entry to be valid, its local configuration id must be equal to or greater than its fragment’s configuration id. Otherwise, it is obsolete and discarded. To recover a fragment’s primary replica, its configuration id is restored to the value at the time of its instance failure. Interested readers may refer to Rejig [13] for a more detailed description and a proof of the protocol. Example 3.1. Assume the coordinator’s current configuration id is 999. Figure 3 shows Fragment F_k was assigned to Instance-0:5 (hosted on cache server 0) in configuration 100. Fragment F_{k+1} was assigned to the same instance in configuration 200. When Instance-0:5 fails, the coordinator transitions its fragments to transient mode. Assume it assigns Instance-1:1 to host the secondary replicas of F_k and F_{k+1}. This results in a new configuration with id 1000. The id of F_k and F_{k+1} is set to 1000 because their assignment changed in this configuration. It also notifies Instance-1:1 of the new id and inserts the configuration as a cache entry in this instance. Once Instance-0:5 recovers, the coordinator checks for the dirty lists of F_k and F_{k+1} in their secondary replicas on Instance-1:1. Assume the dirty list for F_k exists while that of F_{k+1} was evicted and is lost. Hence, the coordinator transitions F_k to recovery mode, sets F_k’s configuration id to 100, its configuration id to 1001, and F_{k+1}’s configuration id to 1001. The last setting causes the cache entries of F_{k+1}’s primary replica on Instance-0:5 to be discarded. This is because all these entries are labeled with configuration ids no greater than 999 and this is smaller than the id of their fragment. 3.3 Fault Tolerance Gemini’s design tolerates arbitrary failures of its clients, recovery workers, and instances. We describe each in turn. When a client fails during processing read or write requests, its outstanding I and Q leases expire after some time to allow other clients to process requests referencing these keys. When a client recovers from a failure, it fetches the latest configuration from an instance. If the instance does not have the configuration then the client contacts the coordinator for the latest configuration. Once it has the configuration then it proceeds to service requests. When a recovery worker fails during recovering a fragment’s primary replica, other recovery workers will later work on this fragment when its Redlease expires. It guarantees read-after-write consistency since deleting or overwriting a dirty key is idempotent. An instance hosting a fragment’s secondary replica may fail. If it fails while the fragment’s primary replica is unavailable, the coordinator transitions the fragment to normal mode and discards its primary replica by changing its configuration id to be the latest id. If it fails before the recovery completes, clients terminate the working set transfer and recovery workers delete remaining dirty cache entries in the fragment’s primary replica. 4 Implementation We implemented a prototype of Gemini. Its client library is implemented with 3,000 lines of Java code. The coordinator is based on Google RPC [18] and implemented with 1,500 lines of Java code. The coordinator distributes fragments owned by a failed instance uniformly across the remaining instances. When a failed instance recovers, the coordinator assigns these fragments back to the recovering instance. A key is mapped to a fragment by hash(key) % the number of fragments. We implemented an instance on top of IQ-Twemcached, the Twitter extended version of memcached with the IQ framework. We extended IQ-Twemcached with only 40 lines of C code to maintain the configuration id described in Section 2 and Section 3. As Gemini’s recovery protocol is agnostic to the underlying persistent storage media, we emulate a persistent cache using DRAM and an instance failure using Gemini’s coordinator by removing it from the latest configuration. We verified our implementation is free from atomicity, consistency, and serializability violations using Polygraph [3]. 5 Evaluation Our evaluation answers two questions: 1) How fast can Gemini restore the system performance when an instance becomes available after a failure? 2) How effective is the working set transfer in restoring cache hit ratio of a recovering instance? As Gemini focuses on reusing still valid cache entries in a fragment’s primary replica, the remaining number of valid cache entries is crucial to its performance. Many factors impact the number of dirty cache entries in a primary replica when its hosting instance fails. The application workload (read/write ratio) and the access pattern (probability of referencing a key) determine the probability that a key becomes dirty during its unavailability. The number of dirty keys is then dictated by the failure duration (seconds), the frequency of writes, and the system load. These are the parameters of our evaluation. We evaluate Gemini in two modes: transient mode and recovery mode. Transient mode quantifies the overhead of maintaining dirty lists while recovery mode quantifies both the overheads and benefits of recovering a failed instance. Since Gemini recovers each fragment independently, this section quantifies costs and benefits for a single instance failure. We compare Gemini with two baseline systems: 1. VolatileCache: Discard the content of an instance after recovering from a power failure. This approach removes the persistence property, simulating a volatile cache. --- 1This implementation lacks shadow coordinators and Zookeeper [16]. 2. **StaleCache**: Use the content of an instance without recovering the state of stale cache entries or adjusting for an evolving access pattern. This technique produces stale data as in Figure 1. We provide a comprehensive comparison of Gemini by exercising its possible configuration settings, see Figure 5. We present evaluation results using a synthetic trace derived from Facebook’s workload [5] and YCSB [7]. Main lessons are as follows: - Gemini guarantees read-after-write consistency in the presence of instance failures. - Gemini maximizes the cache hit ratio of a recovering instance immediately upon its recovery. With a static access pattern, Gemini realizes this as quick as StaleCache without producing stale data. - Gemini restores the cache hit ratio at least two orders of magnitude faster than Volatile-Cache under various system loads and application workloads. - The rate to restore cache hit ratio of a recovering instance depends on its failure duration, the application workload, the system load, and the access pattern. - The working set transfer maximizes the cache hit ratio of a recovering instance for workloads with access patterns that evolve quickly. ### 5.1 Synthetic Facebook-like Workload This section uses statistical models for key-size, value-size, and inter-arrival time between requests for Facebook’s workload [5] to evaluate Gemini. The mean key-size is 36 bytes, the mean value-size is 329 bytes, and the mean inter-arrival time is 19 µs. We generated a synthetic trace based on these distributions assuming a read-heavy workload (95% reads), a static working set (10 million records), a highly skewed access pattern (Zipfian with $\alpha = 100$), 5000 fragments with 50 fragments per instance, and a cache memory size equal to 50% of the database size [21]. Figure 6 shows cache hit ratio of a configuration consisting of 100 instances as a function of time. At the 50th second (x-axis), we fail 20 instances for 100 seconds. The cache hit ratio drops at the 50th second because the secondary replicas start empty. We observe that Gemini-O+W, StaleCache, and VolatileCache have a comparable cache hit ratio in normal and transient modes. At the 150th second, the 20 failed instances are restarted, causing their fragments to enter recovery mode. Gemini-O+W restores its hit ratio immediately since it continues to consume still valid entries in recovering instances. StaleCache has a slightly higher hit ratio. However, it generates stale data, see Figure 1. VolatileCache has the lowest hit ratio due to the failed 20 instances losing their cache contents. ### 5.2 YCSB Workloads We use YCSB [7] to evaluate Gemini’s performance characteristics using an Emulab [31] cluster of 11 nodes: 1 server hosts a MongoDB (version 3.4.10) document store and a Gemini’s coordinator. 5 servers each hosts one instance of IQ-Twemcached and 5 servers each hosts one YCSB client that generates a system workload. Each server is an off-the-shelf Dell Poweredge R430 with two 2.4 GHz 64-bit 8-Core, 64 GB memory, 200GB SSD and 1 Gbps networking card. These servers are connected using a 1 Gbps networking switch. All experiments use a 10 million record YCSB database with a highly skewed Zipfian distribution with $\alpha = 100$. Each record is 1KB in size and is represented as a MongoDB document. The YCSB read command looks up a record in the caching layer first and, with misses, queries MongoDB to compute a cache entry, and populates the instance. The unique identifier of a YCSB record identifies a MongoDB document and the key of the corresponding cache entry. A YCSB update invalidates the cache entry and updates the corresponding document in MongoDB. We construct 5000 fragments across the 5 instances, 1000 fragments per instance. An instance has sufficient memory to store all cache entries for its assigned fragments. We use Gemini’s coordinator to emulate an instance failure by removing it from the latest configuration (without failing it). This causes each of the 1000 fragments of this instance to create a secondary replica, with 250 fragments’ secondary replicas assigned to each of the remaining 4 instances. Clients are provided with the latest configuration, causing them to stop using the emulated failed instance. The content of the failed instance remains intact because its power is not disrupted. Similarly, we emulate an instance recovery by using the coordinator to inform the clients of the availability of the instance. Gemini recovers all fragments’ primary replicas when the failed instance recovers. The working set transfer terminates when the cache hit ratio of the recovering instance is restored to the same value prior to its failure. We consider both a low and a high system load. With a low system load, each client uses 8 YCSB threads to issue requests for a total of 40 YCSB threads (by 5 clients). With a high system load, the number of threads per client increases five-fold for a total of 200 YCSB threads issuing requests. We consider YCSB workloads consisting of a mix of reads and updates: Workload A consists of 50% reads and 50% updates, Workload B consists of 95% reads and 5% updates. In several experiments, we also vary YCSB workload’s percentage of updates from 1% to 10%, reducing its percentage of reads proportionally. We also evaluate Gemini with workloads that have a static and an evolving access pattern. A static access pattern references data items based on a fixed distribution during the entire experiment. An evolving access pattern changes the access distribution during the instance’s failure. We report the mean of three consecutive runs with error bars showing the standard deviation. All the experiments described in the following sections are based on the YCSB workloads. 5.3 Transient Mode Gemini imposes an overhead on a secondary replica by requiring it to maintain a dirty list. Each of the remaining 4 available instances maintains 250 dirty lists. Figure 7 shows the cache hit ratio of an instance, the overall system throughput, and the 90th percentile response time before, during, and after the instance’s 10-second failure. The x-axis of this figure is the elapsed time. The first 10 seconds show system behaviors in normal mode. At the 10th second, we emulate the instance failure for 10 seconds. Reported results are with 1% writes. We observe similar results with YCSB’s write-heavy workload A consisting of 50% writes. In transient mode, the failed instance does not process requests, providing a 0% cache hit ratio, see Figure 7.a. The overall throughput of the system in transient mode is identical between Gemini-O and its alternatives even though these alternatives generate no dirty lists. This is due to the time to apply the write to the data store is significantly higher, masking the overhead of appending the referenced key to the dirty list. Hence, there is no noticeable difference between Gemini and VolatileCache (or StaleCache) in transient mode. 5.4 Recovery Mode We start with workloads that have a static access pattern (workload-B) and focus on quantifying the impact of overwriting dirty keys with their latest values in secondary replicas (Gemini-O) and compare it with invalidating dirty keys (Gemini-I). Then, we evaluate Gemini with an access pattern that evolves during the instance’s failure. We focus on quantifying the impact of working set transfer (Gemini-I+W) and compare it with Gemini-I. 5.4.1 Static Access Pattern With Gemini-O+W, the recovery time includes the time to (a) overwrite dirty keys in a primary replica with their latest values in its secondary replica, and (b) restore cache hit ratio of the recovering instance. With a static access pattern, the first item dictates the Figure 7: Performance before, during, and after a 10-second failure with a low system load and 1% update ratio. Figure 8: Elapsed time to (a) restore the recovering instance’s cache hit ratio, (b-c) complete recovery. recovery time because the access pattern to the persistent entries of the primary replica is unchanged. Figure 8.a shows the time to restore cache hit ratio of the recovering instance with VolatileCache. Figures 8.b and 8.c show Gemini-O’s recovery time as a function of the frequency of writes with a low and a high system load respectively. In these experiments, the recovery time with StaleCache is zero. However, it produces stale data of Figure 1. Gemini-O’s recovery time is in the order of seconds with both a low and a high system load. With a low system load, the recovery workers overwrite most of the dirty keys. VolatileCache takes the longest because it deletes all cache entries of the recovering instance. The time to materialize these using the data store is in the order of hundreds of seconds. A higher system load materializes these faster by utilizing system resources fully. The error bars in Figure 8.b show Gemini-O observes 1 to 2 seconds variation with a low system load. This is because it monitors cache hit ratio once every second. The recovery time is in the order of a few seconds and, to eliminate this variation, monitoring of cache hit ratio to terminate should become more frequent. Figure 7.c shows the 90th percentile read latency for requests issued to all instances. This metric behaves the same with all techniques before and during the failure. After the failed instance recovers, StaleCache provides the best latency by restoring the cache hit ratio of the failed instance immediately while producing stale data. Gemini-O is slightly worse by guaranteeing consistency with negligible performance overhead compared to StaleCache. VolatileCache provides the worst latency because it must use the data store to populate the recovering instance. The 90th percentile read latency of VolatileCache exhibits a long tail due to the skewed access pattern. Gemini-O reduces the average read latency by 20% and the 90th percentile read latency by 70%. With the 99th percentile read latency, the gap between VolatileCache and Gemini-O is only 19% since the cache hit ratio is 98% and the 99th percentile read latency is an approximate of the latency to query the data store for cache misses attributed to the write-around policy. The throughput difference between VolatileCache and Gemini-O is less than 20% since the throughput is aggregated across 5 instances. With more instance failures, the throughput difference becomes more significant. We repeat the same experiment with Gemini-O+W and observe similar performance trends since the access pattern is static. 5.4.2 Transferring versus Invalidating Dirty Keys Figure 9 shows Gemini’s elapsed time to restore cache hit ratio of the recovering instance when it either deletes (Gemini-I) or overwrites (Gemini-O) dirty keys in the recovering instance. The x-axis of this figure varies the percentage of updates. The y-axis is the time to restore the cache hit ratio after a 100-second failure. We show results with both a high and a low system load. Gemini-O is considerably faster than Gemini-I. Gemini-I observes cache misses for the dirty keys that it deletes, forcing a reference for it to query the data store. Gemini-O does not incur this overhead and restores the cache hit ratio faster. 5.4.3 Discarding Fragments Lastly, we quantify the number of keys that are discarded due to failure of the instance hosting a fragment’s secondary replica. We fail two instances (cache-1 and cache-2) one after another. We vary the total number of fragments as 10, 100 and 1000. Hence, each instance hosts 2, 20 and 200 fragments, respectively. Cache entries are distributed evenly across the fragments. The coordinator assigns fragments of a failed instance to other available instances in a round-robin manner. For example, with a total of 10 fragments, a fragment contains 1 million keys. When cache-1 fails, its first fragment $F_0$ is assigned to cache-2 and its second fragment $F_1$ is assigned to cache-3. When cache-2 fails before cache-1 recovers, the fragment $F_0$ must be discarded. The coordinator detects this and updates the fragment $F_0$’s configuration id to the latest configuration id. This causes all clients to discard hits for those 1 million cache entries with a lower configuration id. With 100 and 1000 fragments, a maximum of 500,000 keys are discarded due to the failure of cache-2. The theoretical limit on this maximum is: $\lceil \frac{f}{n(n-1)} \rceil \times c$, where $f$ is the total number of fragments, $n$ is the number of instances, and $c$ is the number of cache entries assigned to a fragment. The second column of Table 3 shows the number of discarded keys in practice. This number is lower than the theoretical maximum because a write may delete an entry that must be discarded so that a future read observes a cache miss on this key. Results of Table 2 are with a high system load and 1% update ratio. Table 3: Gemini’s number of discarded keys with respect to the total number of fragments. <table> <thead> <tr> <th>Total number of fragments</th> <th>Number of discarded keys (mean ± standard deviation)</th> <th>Maximum number of discarded keys</th> </tr> </thead> <tbody> <tr> <td>10</td> <td>975,079 ± 29</td> <td>1,000,000</td> </tr> <tr> <td>100</td> <td>487,374 ± 55</td> <td>500,000</td> </tr> <tr> <td>1000</td> <td>487,397 ± 181</td> <td>500,000</td> </tr> </tbody> </table> Figure 10: Cache hit ratio improvement by the working set transfer with a 20% and a 100% access pattern change, a low and a high system load. 5.4.4 Evolving Access Pattern We emulate two evolving access patterns using the 10 million record YCSB database with Workload B as follows. We partition records into two sets, A and B, each with 5 million records. Prior to the instance’s failure, all references are directed to records in A, never referencing those in B. After the failure, we direct all references to records in B with the same distribution as to that in A. This results in a 100% change in the access pattern. Alternatively, for a 20% change in the access pattern, we switch the most frequently accessed 1 million records in A with those in B. A failure triggers the switch from records in A to those in B. This causes a different set of records to be materialized in the secondary replicas as compared to those persisted in the primary. The workload remains unchanged once the failed instance recovers. Figure 10 shows the cache hit ratio difference between Gemini-I+W and Gemini-I after the failed instance recovers with both a low and a high system load. A higher difference demonstrates the superiority of Gemini-I+W. The difference is significant and lasts a few seconds with a low system load. The difference lasts longer with a high system load because (a) these requests transfer the working set to the recovering instance with Gemini-I+W, and (b) these requests observe cache hits on the transferred entries. In contrast, Gemini-I must query the data store for the new working set. This is considerably slower than Gemini-I+W fetching the working set from a secondary replica. 5.5 Gemini’s Worst Case Scenario Theoretically, if the entire working set changes during an instance’s failure, Gemini incurs two overheads during recovery that provide no benefit. First, recovery workers overwrite dirty keys in the recovering instance but these keys will never be referenced. Second, for every read that observes a miss from the recovering instance, the lookup in an instance hosting the fragment’s secondary replica also reports a miss because the access pattern changed. Duration of the first is dictated by the number of dirty keys. Duration of the second is dictated by the termination condition of working set transfer. We quantify the overhead of Gemini by changing the working set completely before and after the failed instance recovers. The experiment issues a high load and generates 810,076 dirty keys during the instance’s failure. The average read latency increases by 10% due to the additional lookup on a secondary replica. The average update latency increases by 21% since it must be processed in both the secondary and the primary replicas. Each client also consumes significantly more CPU resources (50% more) to recover the instance though future read requests never reference these keys again. The recovery time lasts 70 seconds. 6 Related Work Gemini is inspired by existing work on persistent caches [29, 11, 30, 33, 32, 24, 19], distributed crash recovery protocols [28, 22, 27], the working set transfer [20, 35, 17, 26, 6], and configuration managements [15, 10, 1]. Gemini uses IQ-framework [14] to ensure read-after-write consistency and Redlease [4] to maximize efficiency of recovery workers. 6.1 Persistent Caches NAND flash-based key-value caches provide higher storage density, lower power per GB and higher GB per dollar than DRAM. RIPQ [29], Facebook’s photo cache, reduces write amplification by grouping similar priority keys on flash. Facebook McDipper [11] and Twitter FatCache [30] leverage flash as a larger storage medium to cache larger working sets. Bluecache [33] is also a flash-based cache that uses hardware accelerators to enhance performance and reduce cost. NVMcached [32, 24] is a persistent memcached redesigned for NVM to reduce the number of CPU cache line flushes and minimize data loss with specially designed data structures. These work focus on the performance and cost-savings with persistent caches. Gemini focuses on resolving stale cache entries in a recovering instance that were updated during its failure. 6.2 Distributed Crash Recovery RAMCloud [27] is a DRAM-based key-value data store that recovers gigabytes of data within seconds. RAMCloud maintains only one copy of data in DRAM and relies on fast crash recovery to provide high availability. Gemini is different since it can choose to not recover the cached content of a failed instance since the data is still available in the backend data store. Two-phase commit [28] based systems (e.g., Sinfonia [2]) and Paxos [22] based systems (e.g., Spanner [8]) ensure consistency in the event of node or network failures. Gemini focuses on reusing the still valid content in a recovering instance after a failure, but not maintaining consistency across multiple replicas. Facebook’s memcached cluster [26] employs a component named mcrouter that routes a client request to a cache instance. It minimizes inconsistency by guaranteeing eventual delivery of an invalidation message. A mcrouter logs an invalidation message to its local disk when it fails to deliver the message. Later, it retries the delivery of this message until success. Invalidation messages of a failed instance are spread across many mcrouters. Gemini uses its clients to record a list of dirty keys for each fragment hosted on a failed instance. A dirty list is represented as a cache entry in its secondary replica. A Gemini client uses the dirty list to discard stale entries in the primary replica to guarantee read-after-write consistency. 6.3 Working Set Transfer Key-Value storage systems, e.g., Rocksteady [20], provide on-demand live migration with low impact on the system performance by leveraging immediate transfer of ownership and load-adaptive replay. Gemini is different since its working set transfer is optional. Its objective is to enhance the cache hit ratio of a recovering instance. Zhu et al. [35] propose a migration technique that migrates the most popular data items from a server to be shut down to remaining servers when the system scales down. It also migrates the most popular data items from an existing server to warm up a new server when the system scales up. Hwang and Wood [17] describe a similar technique that uses load balancers to migrate data items when the configuration changes. Facebook [26] employs a cold cluster warmup system that allows clients to warm up a cold cluster with data from a warm cluster. These migration techniques suffer from undesirable race conditions that produce stale data. Gemini’s working set transfer ensures read-after-write consistency and its purpose is to maximize a recovering instance’s performance. Specifically, (a) Gemini overwrites dirty keys in a primary replica with their latest values from its secondary replica, (b) Gemini transfers the latest working set from the secondary replica to its primary replica. Redis [6], a popular key-value cache, supports atomic migration of keys between two Redis instances. However, the migration blocks both instances. Gemini uses IQ leases to ensure read-after-write consistency while serving online requests. 6.4 Configuration Management The design of Gemini’s coordinator, configuration management and distribution are inspired by previous work, e.g., Google File System [15], Hyperdex [10], and Slicer [1]. Google File System (GFS) \cite{15} is a distributed file system for distributed data-intensive applications. A GFS file consists of a list of chunks. Each chunk is associated with a chunk version number. The master maintains the latest chunk version number for each chunk and detects a stale chunk if its version number is lower than the master’s chunk version number. Gemini associates keys and fragments with configuration ids and updates a fragment’s configuration id to the latest to discard entries that it cannot recover. Hyperdex \cite{10} is a distributed key-value store. It employs a coordinator that manages its configurations with a strictly increasing configuration id. Upon a configuration change, the coordinator increments the configuration id and distributes the latest configuration to all servers. Both Hyperdex server and client cache the latest configuration. A client embeds its local configuration id on every request to a server and discovers a new configuration if the server’s configuration id is greater. Gemini differs in that it stores the configuration id with a cache entry to discard entries it cannot recover. Slicer \cite{1} is Google’s general purpose sharding service. It maintains assignments using generation numbers. Slicer employs leases to ensure that a key is assigned to one slicelet (equivalent to an instance) at a time. Applications are unavailable for a maximum 4 seconds during an assignment change due to updating leases to reflect the latest generation number (and assignment) to slicelets. Gemini is different in several ways. First, while its instances may cache a copy of configuration (Slicer’s assignment), they do not use it to decide whether to process a client request or not, it uses its local copy of configuration id for this purpose. Second, Slicer is agnostic to applications which compromises read-after-write consistency with assignment changes. Gemini associates configuration id with keys and fragments to detect and discard cache entries that it cannot recover. 7 Conclusion and Future Work Today’s state-of-the-art cache instances lose their content after a power failure because their DRAM is volatile. With a persistent cache, while the content of a failed instance remains intact, its cache entries may become stale if they are updated during the instance’s failure. Gemini creates a secondary replica for a fragment while the instance hosting its primary replica fails, enabling requests that reference the fragment to benefit from the high performance of the caching layer. It maintains a dirty list identifying those cache entries of the fragment that were impacted by application writes. Once the primary replica becomes available, Gemini either deletes its dirty keys or overwrites their values with those from the secondary replica. Moreover, Gemini transfers the latest working set to the primary replica. We plan to extend Gemini’s recovery protocol to support multiple replicas per fragment. Replication with persistent caches raises several design challenges. For example, as long as each replica has the latest value of a cache entry, is it important for all replicas of a fragment to be identical given that a fragment is a subset of data? If the answer to this question is affirmative then the next question is how to maintain replicas identical while performing cache evictions. One approach is for a master replica to broadcast its eviction decisions to slave replicas. Another possibility is to forward the sequence of requests referencing the master replica to the slave replicas. Assuming replicas use the same cache replacement technique, their eviction decisions should be identical given the same sequence of references. Trade-offs associated with these designs shape our immediate research directions. Acknowledgments We thank the anonymous reviewers of the ACM Middleware and Marc Shapiro for their valuable comments and helpful suggestions. A Proof for Read-after-write Consistency Without loss of generality, we prove the following theorems on Gemini-O+W using the write-around policy. The proof for the configuration management is presented in Rejig [13]. Theorem 1. Gemini guarantees read-after-write consistency for processing requests on a key $k$ mapped to a fragment $j$ in its primary replica $PR_{j,p}$ hosted on an instance $I_p$ in normal mode. It is trivial to see that concurrent writes are serialized at $PR_{j,p}$. Lemma 2 proves that Gemini guarantees read-after-write consistency with a read that observes a cache miss and a write referencing the same key $k$ concurrently. Lemma 2. $PR_{j,p}$ serializes a read $r$ that observes a cache miss and a write $w$ on a key $k$ concurrently. Proof. Let $v$ be the initial value of $k$ in the data store. $(k,v)$ does not exist in $PR_{j,p}$ initially. $PR_{j,p}$ grants an I lease on $k$ for $r$ since it observes a cache miss. Then, $r$ fetches its value from the data store and inserts it in $PR_{j,p}$ if the I lease is still present. $w$ acquires a Q lease on $k$ in $PR_{j,p}$, updates $v$ to $v'$ in the data store, atomically deletes $k$ and releases the Q lease. There are two major cases to consider. Case I: $r$’s insertion happens before $w$’s acquiring a Q lease. $r$ succeeds in inserting $(k,v)$ in $PR_{j,p}$ and returns $v$ to the application. When $w$ completes, the inserted $(k,v)$ in $PR_{j,p}$ is deleted. $r$ is serialized before $w$. Case II: $w$’s acquiring a Q lease happens before $r$’s insertion. $r$’s insertion will fail since the I lease is voided by the Q lease. If $r$ queries the data store before $w$ updates the data store, $r$ returns $v$ to the application and $r$ is serialized before $w$. Otherwise, $r$ returns $v'$ to the application and $w$ is serialized before $r$. ■ Theorem 3. Gemini preserves read-after-write consistency for a key $k$ mapped to a fragment $j$ in recovery mode when its primary replica $PR_{j,p}$ becomes available. Theorem 1 proves that Gemini achieves read-after-write consistency for fragment $j$ in normal mode. When $PR_{j,p}$ becomes available, a client processes reads using the data store before they fetch fragment $j$’s dirty list $D_j$ from $f$’s secondary replica $SR_{j,s}$. Lemma-4 and Lemma-5 prove that Gemini preserves read-after-write consistency after fetching $D_j$ with a read and a write request referencing the same key $k$ concurrently. We can treat overwriting dirty keys in $D_j$ performed by the recovery worker as read requests that reference keys in $D_j$ which is also proven by Lemma-4 and Lemma-5. Lemma 4. Gemini preserves read-after-write consistency after clients fetching the dirty list \( D_j \) from the secondary \( SR_{j,s} \) and \( k \) does not exist in the primary \( PR_{j,p} \). Proof. The read request acquires an I lease and observes a miss on \( k \) in \( PR_{j,p} \). There are two cases. Case I: \( k \) does not exist in \( SR_{j,s} \). The read request observes a miss in \( SR_{j,s} \) and queries the data store. It is trivial to see that \( PR_{j,p} \) serializes the concurrent read and write requests since I and Q leases are incompatible with each other. Case II: \( k \) exists in \( SR_{j,s} \). The read request reads \( k \) from \( SR_{j,s} \) and inserts its value \( v \) into \( PR_{j,p} \) if the I lease still exists. If the write request’s acquiring a Q lease in \( PR_{j,p} \) happens before the insert, the insert fails since the Q lease deletes the I lease associated with \( k \). Otherwise, the insert succeeds and \( v \) is valid to consume. If releasing the Q lease in \( PR_{j,p} \) happens before acquiring the I lease, \( k \) must have been deleted in \( SR_{j,s} \) and Case I proves this case. ■ Lemma 5. Gemini preserves read-after-write consistency after clients fetching the dirty list \( D_j \) from \( SR_{j,s} \) and \( k \) exists in \( PR_{j,p} \). Proof. There are two cases. Case I: \( k \in D_j \). The read request knows that \( k \) is dirty and treats it as a cache miss. Lemma-4 proves this case. Case II: \( k \notin D_j \). The read request observes a cache hit and consumes the value. ■ References
{"Source-Url": "http://dblab.usc.edu/Users/papers/Gemini.pdf", "len_cl100k_base": 12975, "olmocr-version": "0.1.50", "pdf-total-pages": 29, "total-fallback-pages": 0, "total-input-tokens": 69114, "total-output-tokens": 17034, "length": "2e13", "weborganizer": {"__label__adult": 0.00033402442932128906, "__label__art_design": 0.00049591064453125, "__label__crime_law": 0.0003736019134521485, "__label__education_jobs": 0.0010223388671875, "__label__entertainment": 0.00017178058624267578, "__label__fashion_beauty": 0.00019228458404541016, "__label__finance_business": 0.0006999969482421875, "__label__food_dining": 0.0003960132598876953, "__label__games": 0.0008006095886230469, "__label__hardware": 0.0024566650390625, "__label__health": 0.0006327629089355469, "__label__history": 0.0004911422729492188, "__label__home_hobbies": 0.00010627508163452148, "__label__industrial": 0.0006008148193359375, "__label__literature": 0.0003464221954345703, "__label__politics": 0.00039124488830566406, "__label__religion": 0.0004839897155761719, "__label__science_tech": 0.342529296875, "__label__social_life": 0.00010484457015991212, "__label__software": 0.03326416015625, "__label__software_dev": 0.61328125, "__label__sports_fitness": 0.0002570152282714844, "__label__transportation": 0.0005545616149902344, "__label__travel": 0.000247955322265625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 67652, 0.03209]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 67652, 0.10607]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 67652, 0.86624]], "google_gemma-3-12b-it_contains_pii": [[0, 2269, false], [2269, 4200, null], [4200, 7368, null], [7368, 7937, null], [7937, 9998, null], [9998, 11430, null], [11430, 14566, null], [14566, 17626, null], [17626, 20110, null], [20110, 21487, null], [21487, 23839, null], [23839, 27200, null], [27200, 30254, null], [30254, 33156, null], [33156, 35143, null], [35143, 38014, null], [38014, 38126, null], [38126, 38232, null], [38232, 41516, null], [41516, 43164, null], [43164, 45127, null], [45127, 48042, null], [48042, 51296, null], [51296, 54921, null], [54921, 57864, null], [57864, 60625, null], [60625, 63381, null], [63381, 65837, null], [65837, 67652, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2269, true], [2269, 4200, null], [4200, 7368, null], [7368, 7937, null], [7937, 9998, null], [9998, 11430, null], [11430, 14566, null], [14566, 17626, null], [17626, 20110, null], [20110, 21487, null], [21487, 23839, null], [23839, 27200, null], [27200, 30254, null], [30254, 33156, null], [33156, 35143, null], [35143, 38014, null], [38014, 38126, null], [38126, 38232, null], [38232, 41516, null], [41516, 43164, null], [43164, 45127, null], [45127, 48042, null], [48042, 51296, null], [51296, 54921, null], [54921, 57864, null], [57864, 60625, null], [60625, 63381, null], [63381, 65837, null], [65837, 67652, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 67652, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 67652, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 67652, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 67652, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 67652, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 67652, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 67652, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 67652, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 67652, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 67652, null]], "pdf_page_numbers": [[0, 2269, 1], [2269, 4200, 2], [4200, 7368, 3], [7368, 7937, 4], [7937, 9998, 5], [9998, 11430, 6], [11430, 14566, 7], [14566, 17626, 8], [17626, 20110, 9], [20110, 21487, 10], [21487, 23839, 11], [23839, 27200, 12], [27200, 30254, 13], [30254, 33156, 14], [33156, 35143, 15], [35143, 38014, 16], [38014, 38126, 17], [38126, 38232, 18], [38232, 41516, 19], [41516, 43164, 20], [43164, 45127, 21], [45127, 48042, 22], [48042, 51296, 23], [51296, 54921, 24], [54921, 57864, 25], [57864, 60625, 26], [60625, 63381, 27], [63381, 65837, 28], [65837, 67652, 29]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 67652, 0.04575]]}
olmocr_science_pdfs
2024-12-01
2024-12-01
df0c21fb943723e690a49e79317fa66d1ad54106
# Table of Contents <table> <thead> <tr> <th>Section</th> <th>Page</th> </tr> </thead> <tbody> <tr> <td>Table of Contents</td> <td>i</td> </tr> <tr> <td>Requirements</td> <td>1</td> </tr> <tr> <td>Introduction</td> <td>2</td> </tr> <tr> <td>User Types</td> <td>3</td> </tr> <tr> <td>Resources</td> <td>4</td> </tr> <tr> <td>Using the API</td> <td>5</td> </tr> <tr> <td>Authentication using Service Accounts</td> <td>6</td> </tr> <tr> <td>Authentication using OAuth</td> <td>8</td> </tr> <tr> <td>Authentication using an existing token</td> <td>9</td> </tr> <tr> <td>Configuration Settings</td> <td>10</td> </tr> <tr> <td>Enable Logging</td> <td>12</td> </tr> <tr> <td>Examples</td> <td>14</td> </tr> <tr> <td>Example 1: Connect and authenticate a user</td> <td>15</td> </tr> <tr> <td>Example 2: Add users to a workspace</td> <td>16</td> </tr> <tr> <td>Example 3: Add permissions for a group of users to access a file</td> <td>19</td> </tr> <tr> <td>Example 4: Upload a file</td> <td>21</td> </tr> <tr> <td>Example 5: Download a file</td> <td>23</td> </tr> <tr> <td>Example 6: Enumerate files in a workspace</td> <td>24</td> </tr> <tr> <td>Example 7: Change file permissions</td> <td>25</td> </tr> <tr> <td>Example 8: Enumerate folders and workspaces</td> <td>26</td> </tr> <tr> <td>Example 9: Retrieve a list of activities for a named file</td> <td>27</td> </tr> <tr> <td>Example 10: Add a user to a room group</td> <td>28</td> </tr> <tr> <td>Example 11: Delete a file from a workspace</td> <td>29</td> </tr> <tr> <td>Example 12: Remove a file from the Workspaces Inbox or Sent items</td> <td>30</td> </tr> <tr> <td>Example 13: Handling events</td> <td>31</td> </tr> <tr> <td>Legal notice</td> <td>34</td> </tr> <tr> <td>Table of Contents</td> <td></td> </tr> <tr> <td>-------------------</td> <td></td> </tr> <tr> <td>© 2021, BlackBerry • ALL RIGHTS RESERVED.</td> <td></td> </tr> </tbody> </table> Requirements Audience The intended audience for this guide is developers of .NET applications wanting to connect to the Workspaces services. Required Knowledge Developers should be familiar with creating applications for the .NET platform. Knowledge of the HTTP protocol and JSON formats for HTTP messages will also be useful. Prerequisites In order to use the Workspaces .NET SDK you must have an organization account in the Workspaces cloud service or have an on-premises Workspaces installation (deployed as a virtual appliance). An organization administrator account will be set up by BlackBerry. Introduction This guide explains how developers can use the Workspaces .NET SDK to develop applications to allow end users to work with files protected by Workspaces. Workspaces allows users to securely share files with others. File owners maintain full control of each file that they share, including permissions to view, print, copy and download a file. For example, file owners can change access permissions, set a file expiration date, or revoke access to a file at any time even after a file is shared with devices beyond your organization’s control. Workspaces consists of two core services a. Workspaces: into which files can be uploaded to be securely shared with others b. Send: by which files are securely shared with others API Version This document refers to Workspaces API version 3.0. Workspaces model The Workspaces platform is a web-based service that may be hosted on Workspaces cloud-based servers or locally on virtual appliances at an organization (on-premises). User Types Workspaces has the following types of users: **Organization Administrator** An administrator that has access to all workspaces in the organization’s account, with the ability to create, remove, and modify users (including other administrators), workspaces, groups and all other entities associated with the organization’s account. The first Organization Administrator is defined by BlackBerry when the account is first created. The Organization Administrator cannot view documents within the account. There is more than one type of organization administrator. For more information about the different types of organization administrators, see the Workspaces web application. **Workspace Administrator** An administrator for a workspace or group of workspaces within an organization that can view all files in these workspaces, add groups and users, and upload files. **Contributor** A user with the ability to manage content in a workspace (for example, view, upload and delete files). **Visitor** Someone who is not a user of the service that can view files that they receive from a Workspaces user. The file can be viewed in protected format only. A visitor cannot upload files to a workspace or update files in a workspace. Resources The Workspaces API is divided into the following categories, each relating to a distinct part of the service: **Files** - The following resources are used to manage the Workspaces Send feature for an organization (a service for ad-hoc sending and receiving of document securely). <table> <thead> <tr> <th>Resource</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>Upload &amp; download</td> <td>Upload files to the Workspaces server where the files can be shared from and download files received from other Workspaces users</td> </tr> <tr> <td>Send</td> <td>Send files by email to recipients</td> </tr> <tr> <td>Enumerate</td> <td>List the files sent via Workspaces</td> </tr> <tr> <td>Manage permissions</td> <td>Set or change access permissions for files sent via Workspaces</td> </tr> <tr> <td>Search</td> <td>Search for files by text or metadata</td> </tr> <tr> <td>Track</td> <td>View audit and tracking information for activities on files sent and received via Workspaces</td> </tr> </tbody> </table> **Organization administration** - The following resources are used to manage the workspaces, Workspaces Inbox, and Sent Items in an Organization account. <table> <thead> <tr> <th>Resource</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>Users</td> <td>Create, update, and remove the organization's users</td> </tr> <tr> <td>Roles</td> <td>Assign roles to users (e.g. workspace Administrator, Contributor)</td> </tr> <tr> <td>Aliases</td> <td>Set email aliases which enable a user to view, in a single session, all files received under different email addresses</td> </tr> <tr> <td>Distribution lists</td> <td>Setup and manage distribution lists of users. Distribution Lists are named sets of users defined globally at the organization level. They can be used as an alias for sending files or be referred to by workspace groups.</td> </tr> <tr> <td>Tags</td> <td>Define metadata tags that can be assigned to files in workspaces</td> </tr> <tr> <td>Watermarks</td> <td>Define the watermark template that can be applied to files downloaded from workspaces</td> </tr> <tr> <td>Global Policies</td> <td>Set global access and usage policies</td> </tr> </tbody> </table> **Workspace management** - The following resources can be used to manage a single workspace. For example, a single workspace might be used by a group that is collaborating on a common set of files. <table> <thead> <tr> <th>Resource</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>Groups &amp; Users</td> <td>Set up groups and users of a workspace</td> </tr> <tr> <td>Folders</td> <td>Set up folders in a workspace</td> </tr> <tr> <td>Enumerate</td> <td>List the files, folders and groups in a workspace</td> </tr> <tr> <td>Alerts</td> <td>Configure alerts for new or changes to files that users should be aware of</td> </tr> <tr> <td>Upload, download</td> <td>Upload or download files to a workspace</td> </tr> <tr> <td>Permissions</td> <td>Set access permissions for files in a workspace</td> </tr> </tbody> </table> Using the API The Workspaces .NET SDK provides classes for the previously-noted resources which include Authentication, Files, Workspaces, Users, and Organizations, in addition to others. These resource classes provide methods that allow access to their functionality. In general, most of the methods often require a JSON object that represents the data the resource method needs. Successful requests will generally return a string, JSON object or Stream (e.g., when downloading documents) to indicate that the requested action has been successfully performed. A common JSON object returned is the BulkOperationResultJson that provides details on the success of each operation or any problem(s) encountered. Here's a simple example that illustrates those ideas. It uses an instance of ApiSession class to start a service account session for a given user. StartSessionWithServiceAccount method of Apisession requires the user's email address for which the service account has been created, the issuer (an ID created when the service account is created), the token expiration in minutes, and the certificate. It will return a “Success” LoginResult if the session starts successfully. The ApiSession then sends a request, to one of the getters to the resources, to get an instance of a resource. In the following code sample, the listRoomsV30 of workspaces object gets back an iterable JSON object representing a list of WorkspaceInfoJson (with each item inside representing a workspace). ```csharp ApiSession apiSession = new ApiSession(serverUrl); Workspaces workspaces = apiSession.GetWorkspacesResource(); LoginResult loginResult = apiSession.StartSessionWithServiceAccount(username, serviceAccount, expiresInMinutes, certificate); ItemListJson<WorkspaceInfoJson> itemListJson = workspaces.listRoomsV30(workspaceTypes); ``` Many domain-specific errors will result in a WebException being returned to the caller. More-generalized C# errors like Exception are also possible. Examples for using the Workspaces resource and other resources can be found in the Examples section. Authentication using Service Accounts Service Accounts provide an alternative means of authenticating requests sent to the Workspaces server. Using a service account removes the need to have a user's password in order to authenticate a user. When using a Service Account you can configure Workspaces to allow groups of users based on their email domain(s) and/or specific users access to their Workspaces accounts. 6.1 Steps for creating a Service Account 1. Create or obtain a SSL certificate. There are a number of ways to do this including using tools like OpenSSL to create a Self-Signed certificate, or you can purchase a commercial certificate from any number of certificate providers. For example we can construct and pass the certificate object with the local path to the generated certificate, a password if there is any and set the X509KeyStorageFlags to Exportable or PersistKeySet. ```csharp X509Certificate2 certificate = new X509Certificate2(path, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); ``` 2. Extract the Public key from the certificate. You'll need this to paste the Public key into the Workspaces Admin console. 3. Configure the Service Account in Workspaces. While logged in to the Workspaces Admin Console as an administrator: a. Navigate to Service Accounts under Authentication on the left-hand side, and click the + icon. b. Under System accounts: i. In the Public key field, copy and paste the contents of the Public key. Depending on how the certificate was generated and the public key displayed, the key may be bracketed by a set of tags such as -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY-----. Do not include these tags when copying the public key. ii. In the System accounts field, enter a list of user email addresses that will be allowed to authenticate using this service account. Separate each address with a space. If you only want to authenticate groups of users using theiremail domain this field may be left blank. iii. In the Domain system accounts field, enter a list of email domains that will be allowed to authenticate using this service account. Separate each domain with a space. If you only want specific users to be able to authenticate this field may be left blank. iv. In the Algorithm dropdown, select the algorithm that was used to create the certificate. c. Click Apply to save the Service Account configuration. 4. In your application code use the StartSessionWithServiceAccount method on ApiSession to authenticate a session. 6.2 Authenticating using StartSessionWithServiceAccount Once the Service Account has been created in the Workspaces Admin Console clients can connect using the certificate. The StartSessionWithServiceAccount method on ApiSession provides the means to start a session using the Service Account. This method will construct an authentication token and validate that the specified user has access to use the service account to make requests to the server. If they do then LoginResult will return with "Success". For further details see Example 1. ```java ApiSession apiSession = new ApiSession(serverUrl); LoginResult loginResult = apiSession.StartSessionWithServiceAccount(username, serviceAccountName, expiresInMinutes, certificate); ``` ### 6.3 Using OpenSSL to create a certificate Run the openssl application to create a certificate and private key file. In the example below `<PRIVATEKEY>` represents the name of the file where the private key will be stored. `<CERTIFICATE>` represents the name of the file where the certificate will be stored. When you run the openssl command you will be prompted for several pieces of information used in creating the certificate. ```bash openssl req -newkey rsa:2048 -nodes -keyout <PRIVATEKEY> -x509 -out <CERTIFICATE> ``` Run openssl again to display the public key. ```bash openssl rsa -in <PRIVATEKEY> -pubout ``` The output will look something like the example shown below. The public key is the text shown between the `-----BEGIN PUBLIC KEY-----` and `-----END PUBLIC KEY-----` tags. ``` -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0X43UwF1exJMv8JktJGaXlY0wArj/w95tvYuG/y42pTwh8Ttp8eYlwAX3bT5awdC/D7qlz2oEWIMb8QRH+0gF/L7KU0nBHzyWBiqggjJKywegbaFuKKHxIMzrGkcaAmiIq0VxesZyxtWzPIhvvX2i67kAgygZ2VCgj/D7KZXluLV55XY/vH44ohgPuU83mbwX8pTWqfaOeUQUzv4kIWWta yD1q4+eccsr47eNnzEUcyoAR99+2b/ammdrOn8/QjCuc6zWb1qGyXX5fhI5a 18AC32rKBKv/hLhIM5D7n3JjQ73hwiUcqct85gl14Nf9YoUwUGC3h1ejuhKf4VYah/KQIDAQAB -----END PUBLIC KEY----- ``` Authentication using OAuth Workspaces OAuth lets users allow other applications to interact with their Workspaces account without providing that other application their Workspaces authentication credentials, and for only a time-limited basis. For example, a sales management application can integrate Workspaces functionality to allow the controlled sharing of documents via Workspaces, within the sales management app, without requiring users to provide their Workspaces usernames and passwords to the sales management app. 7.1 Registering a client with a Workspaces server Someone wishing to use Workspaces OAuth must register with Workspaces and obtain a client ID and client secret that will be passed to Workspaces in order to obtain a Workspaces authentication token. 7.2 Authenticating using StartSessionWithOAuth The StartSessionWithOAuth method in ApiSession provides an easy way to authenticate users using OAuth. After creating an instance of ApiSession and making a call to the StartSessionWithOAuth method, a window will appear to accept the authentication credentials for the user. This window will remain visible until the user successfully authenticates with the Workspaces server or the user closes the window. Because of this the StartSessionWithOAuth method is a blocking call. Once the user has provided their credentials correctly or closes the window the LoginResult value is returned from the method. If the user provided a correct set of credentials the StartSessionWithOAuth method returns a "Success" LoginResult. ```java ApiSession apiSession = new ApiSession(serverUrl); LoginResult loginResult = apiSession.StartSessionWithOAuth(email); ``` 7.3 Manually authenticating using OAuth The basic flow is as follows where WORKSPACES_URL refers to the base URL of the Workspaces server being used: 1. Make an unauthenticated call to `WORKSPACES_URL/api/3.0/authentication/parameters` to get the authentication URI's. In the returned values, authorizationUri is the URI for the temporary token in #2 below; accessTokenUri is the URI for obtaining the full token in #4 below. 2. Direct the user to the Workspaces authenticationUri (e.g. via a redirect in your own web app), passing the proper params (see below). One of these params is the redirect URI in your app to which the user should be sent after authenticating with Workspaces. It will look something like this (wrapped across lines here, but one single line when used): ``` <WORKSPACES_URL>/<AUTHORIZATION_URI>?response_type=code&client_id=<CLIENT_ID>&locale=en_US &redirect_uri=<REDIRECT_URI> ``` 3. When that redirect URI is serviced in your web app, a temporary code is included on the URL that will be used to obtain a valid auth token. It will look something like this: ``` <REDIRECT_URI>?code=219e5a32-d74f-473a-91a4-fd74f95e091c&locale=en-us ``` 4. Make a call to the Workspaces accessTokenUri to obtain a valid auth token, refresh token, and an expiration value for the auth token. That auth token can be used to authenticate subsequent API calls to the Workspaces server (wrapped across lines here, but one single line when used). ``` WORKSPACES_URL/<ACCESS_TOKEN_URI>?client_id=<CLIENT_ID>&redirect_uri=<REDIRECT_URI>& client_secret=<CLIENT_SECRET>&grant_type=authorization_code&code=<AUTH_CODE> ``` 5. That call will return JSON that contains an access token, expiration, and refresh token. The access token can be used in the authorization header of subsequent calls. Authentication using an existing token In some situations a developer may want to create a separation of concerns whereby one module might be responsible for obtaining authentication tokens from the Workspaces server while other components use those tokens to communicate with the Workspaces server. The Workspaces SDK provides a means to do this using the `LoadExistingSession` method on `ApiSession`. In the module that provides the authentication tokens there would be some code, similar to the snippet below, which obtains a valid authentication token for the Workspaces server. ```csharp public String ObtainTokenFromSeparateModule(String username) { String authToken = String.Empty; String serviceAccountName = "com.watchdox.system.xxxx.yyyy"; int expiresInMinutes = 5; X509Certificate2 certificate = new X509Certificate2("myCertFile.crt", "certPassword", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); ApiSession apiSession = new ApiSession(serverUrl); LoginResult loginResult = apiSession.StartSessionWithServiceAccount(username, serviceAccountName, expiresInMinutes, certificate); if (loginResult == LoginResult.SUCCESS) { authToken = apiSession.GetToken(); } return authToken; } ``` Having obtained an authentication token from the other module, it would then passed to the `LoadExistingSession` method of an `ApiSession` instance. ```csharp String authToken = ObtainTokenFromSeparateModule(); if (!string.IsNullOrEmpty(authToken)) { ApiSession apiSession = new ApiSession(serverUrl); LoginResult loginResult = apiSession.LoadExistingSession(authToken); } ``` Configuration Settings The BlackBerry Workspaces SDK has several settings which control the behavior of the SDK. These settings are specified in your applications configuration. If a particular setting is not specified in an application’s configuration the SDK will use a default value for that setting. 9.1 Specifying configuration settings The BlackBerry Workspaces SDK uses the following settings for handling configuration files which will be configured in the App.config of the specific project. First define a section for BlackBerry.Workspaces.Settings in configSection of the App.config like this: ```xml <configSections> <section name="BlackBerry.Workspaces.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" /> </configSections> ``` Then add the list of settings inside the section defined for BlackBerry.Workspaces.Settings: ```xml <BlackBerry.Workspaces.Settings> <setting name="DefaultServerURL" serializeAs="String"> <value>www.watchdox.com</value> </setting> <setting name="DownloadBufferSize" serializeAs="String"> <value>4000</value> </setting> <setting name="DownloadToTmp" serializeAs="String"> <value>True</value> </setting> </BlackBerry.Workspaces.Settings> ``` 9.2 Accessing configuration settings The following snippet shows how to get or set the settings using BlackBerry.Workspaces.Settings.Portable: ```csharp //set BlackBerry.Workspaces.Settings.Portable["DownloadBufferSize"] = 5000; //get byte[] buffer = new byte[bufferSize]; ``` 9.3 Available configuration settings These are the types and default values used in the BlackBerry.Workspaces.Settings. **AutoSignInEmail** *used to set or get auto signIn email.* Type: string DefaultServerURL *used to set or get auto signIn email.* | Type: string | | Default value: www.watchdox.com | DownloadBufferSize *used to set or get the download buffer size.* | Type: int | | Default value: 4000 | DownloadToTmp *used to set or get whether to download a file to a temporary location.* | Type: bool | | Default value: true | MaximumTimeoutForUpload *used to set or get the maximum time out when downloading a file.* | Type: double | | Default value: 6000 | OAuthRedirectUrl *used to set or get Ouath redirect URL.* | Type: string | | Default value: www.google.com | Enable Logging The Workspaces SDK uses NLog as its underlying logging provider. Additional Information about NLog found at [NLog Tutorial](#). ### 10.1 Configuring Logging To enable logging in the SDK you need to add to the configuration for your application. First define a section for NLog in the `configSection` of your configuration. ```xml <configSections> <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/> </configSections> ``` Next, add the targets and rules inside the section defined for NLog. Targets specify where to write log messages, Rules define when to write log messages. In the example below two targets have been defined: one will send log messages to a file named "workspacessdk.log", the other will write to the console. The two rules specified will cause Trace and higher messages to be written to the log file while only Info and higher messages will be written to the console. ```xml <nlog autoReload="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <targets> <target name="logfile" xsi:type="File" fileName="${basedir}/workspacessdk.log" layout="${level} | ${message}" keepFileOpen="true"/> <target name="console" xsi:type="Console"/> </targets> <rules> <logger name="*" minlevel="Trace" writeTo="logfile"/> <logger name="*" minlevel="Info" writeTo="console"/> </rules> </nlog> ``` ### 10.2 Workspaces logging extensions The Workspaces SDK provides two extensions to NLog. - **CustomDbgOutputTarget**: Logs messages using the native OutputDebugString method. - **ResettableFileTarget**: Provides a File target which will reset or truncate the log file whenever a specified pattern is seen in a log message. To enable the Workspaces SDK extensions you must add an `extensions` section to the NLog configuration section. ```xml <nlog autoReload="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <extensions> <add assembly="WorkspacesSdk" /> </extensions> </nlog> ``` The CustomDbgOutputTarget extension extends the NLog TargetWithLayout which allows the `layout` attribute to be specified to define the format of the log messages. ```xml <nlog autoReload="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <extensions> <add assembly="WorkspacesSdk" /> </extensions> <targets> <target name="ods" xsi:type="CustomDbgOutput" layout="${level} | ${message}"/> </targets> <rules> <logger name="*" minlevel="Trace" writeTo="ods"/> </rules> </nlog> ``` The ResettableFileTarget extension extends the NLog FileTarget. Any attributes allowed on FileTarget maybe used with ResettableFileTarget. ResettableFileTarget supports an additional attribute, `DeleteToken`, which controls when the log file is reset/truncated. The default value for `DeleteToken` is `~DELETE~LOG~FILE~`. Whenever the value specified by the `DeleteToken` attribute is seen in a log message the current logfile is truncated and any future log messages will be written from the beginning of the log file. ```xml <nlog autoReload="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <extensions> <add assembly="WorkspacesSdk" /> </extensions> <targets> <target name="resetlogfile" xsi:type="ResettableFile" deleteToken="SomeDeleteToken" fileName="${basedir}/workspacessdk.log" layout="${message}" keepFileOpen="true" /> </targets> <rules> <logger name="*" minlevel="Trace" writeTo="resetlogfile"/> </rules> </nlog> ``` Additional Information about NLog found in here NLog Tutorial Examples This section describes examples of common application scenarios, to illustrate how to use the API. Note also that the term room is interchangeable with Workspace. Example 1: Connect and authenticate a user This example provides how to connect and authenticate to the server. Basically there are two methods supported: i. **Authenticating using a Service Account**: uses a certificate to sign the authentication credentials and is best used with server to server applications. ii. **Authenticating using OAuth**: is best used for client to server applications that allows a user to authenticate without exposing their credentials to the client application. In the following sections, its depicted in details how to authenticate a user to the Workspaces' services. ### 12.1 Authenticating using a Service Account To Start a session using service account, you must first know the username or email address of the user the request will be made on the behalf of, the issuer id for the Service account, and determine for how long the signed token will be valid. You will also need the certificate to use when signing the data. It assumes that you have already copied the public key to the Workspaces server (see the section on "Using Service Accounts" for more information on that). How an application determines or acquires a user's email address would be up to the application. The issuer is the identifier assigned when the service account was created in the Workspaces Admin console. This issuer would be in the format `com.watchdox.system.xxxx.yyyy` where xxxx and yyyy are some set of numbers and letters- for example, `com.watchdox.system.fadd.3015`. The expiration time represents the number of minutes for which the token should be valid. With this information in hand and creating an instance of ApiSession, a simple call to a StartSessionWithServiceAccount method in ApiSession will return the loginResult. The server returns a "Success" LoginResult if the session starts successfully: ```java ApiSession apiSession = new ApiSession(serverUrl); LoginResult loginResult = apiSession.StartSessionWithServiceAccount(username, serviceAccount, expiresInMinutes, certificate); ``` ### 12.2 Authenticating using OAuth To Start a session using OAuth, you must first know the email address to pass to service provider, null or empty if not known and to be determined during the OAuth process. It's also optional to provide refresh token and showUiIfRefreshFails (indicates whether to show UI if refresh token exists but the refresh fails). After creating an instance of ApiSession and making StartSessionWithOAuth method call, an OauthBrowser window pop ups to receive an authentication email and password. Once the user provides a correct email and password, the pop up widow will close and the StartSessionWithOAuth method returns a "Success" LoginResult if the session starts successfully. ```java ApiSession apiSession = new ApiSession(serverUrl); LoginResult loginResult = apiSession.StartSessionWithOAuth(email); ``` Example 2: Add users to a workspace This example adds a user to a Workspace. It requires three separate method calls. (Note the different permissions required for each step). 13.1 Create Workspace (can only be done by an organization admin). This returns a RoomsJson object that represents the room that was created. ```csharp #region devGuide1 Resource.Workspaces workspaces = apiSession.GetWorkspacesResource(); // Create the JSON object needed for the method call, and set its values. CreateRoomJson createRoomJson = new CreateRoomJson { Name = name, Description = description, Administrators = administrators }; // Call the method, and get a JSON object back RoomJson roomJson = workspaces.CreateRoomV30(createRoomJson); #endregion ``` 13.2 Create new room group (can only be done by a Workspace admin) ```csharp #region devGuide2 Resource.Workspaces workspaces = apiSession.GetWorkspacesResource(); // Create a JSON object the represents the new group and set its values PermittedEntityFromUserJson permittedEntityFromUserJson = new PermittedEntityFromUserJson { Address = groupName, EntityType = EntityType.GROUP }; // Create a new permissions JSON with default values PermissionFromUserJson permissionFromUserJson = new PermissionFromUserJson(); // The JSON object needed for the resource method call AddEntityVdrJson addEntityVdrJson = new AddEntityVdrJson { PermittedEntity = permittedEntityFromUserJson, NewPermissions = permissionFromUserJson }; // Make the call to the Rooms resource and return "success" return workspaces.AddEntityV30(workspaceId, addEntityVdrJson); #endregion ``` 13.3 Add members (users) to group ```csharp #region devGuide3 Resource.Workspaces workspaces = apiSession.GetWorkspacesResource(); List<AddMemberToGroupJson> memberList = new List<AddMemberToGroupJson>(); // Loop through the List<String> userAddresses foreach (string currentAddress in userAddresses) { PermittedEntityFromUserJson currentEntity = new PermittedEntityFromUserJson { Address = currentAddress, EntityType = EntityType.USER }; // make a AddMemberToGroupJson for each user AddMemberToGroupJson currentMemberJson = new AddMemberToGroupJson { Entity = currentEntity }; memberList.Add(currentMemberJson); } // Set the group name to be a string and roomId is the integer identifying the room AddMembersToGroupWithGroupJson groupMemberJson = new AddMembersToGroupWithGroupJson { MembersList = memberList, RoomId = roomId, GroupName = groupName }; // Make the call to the Rooms resource and return "success" string result = workspaces.AddMembersToGroupV30(groupMemberJson); #endregion ``` Example 3: Add permissions for a group of users to access a file This example allows access to a document for a group of users. It assumes a group and a workspace exist, the latter with a single document, and group (“mygroup”) exists; these are described in the preceding example. 14.1 Get list of documents in a Workspace ``` #region devGuide4 Resource.Workspaces workspaces = apiSession.GetWorkspacesResource(); // Create a json object for the document search, and accept its defaults. // Adjust if needed. ListDocumentsVdrJson listDocumentsJson = new ListDocumentsVdrJson(); // Make the call to get the list of documents PagingItemListJson<BaseJson> documentList = workspaces.ListDocumentsV30(roomId, listDocumentsJson); #endregion ``` 14.2 Create the json object for the permissions Default to true value for all permission. Set the group name and EntityType.GROUP as well. Note the nested json objects that are created and then set on other, enclosing json objects. ```csharp #region devGuide5 PermittedEntityFromUserJson groupPermission = new PermittedEntityFromUserJson { Address = groupName, EntityType = EntityType.GROUP }; List<PermittedEntityFromUserJson> permissionsList = new List<PermittedEntityFromUserJson> { groupPermission }; // Adjust permissions as needed PermissionSetJson permissionSet = new PermissionSetJson { DownloadOriginal = YesNoDefault.YES, DownloadControlled = YesNoDefault.YES, Copy = YesNoDefault.YES, Edit = YesNoDefault.YES, Print = YesNoDefault.YES, ProgrammaticAccess = YesNoDefault.YES, Spotlight = YesNoDefault.YES, Watermark = YesNoDefault.YES }; HashSet<string> documentGuids = new HashSet<string> { myDoc.Guid }; VdrAddPermissionsJson permissionsJson = new VdrAddPermissionsJson { PermittedEntities = permissionsList, PermissionSet = permissionSet, DocumentGuids = documentGuids }; #endregion ``` 14.3 Add permissions to the group Set the document GUID from the returned document list and make the call to set the permissions. A BulkOperationResultJson is returned, which has information on the success or failure(with errors encountered) for each document in the list(which in this case was just 1). ```csharp #region devGuide6 // Add permissions BulkOperationResultJson result = workspaces.AddPermissionsV30(roomId, permissionsJson); #endregion ``` Example 4: Upload a file 15.1 Upload a file to workspace This example shows how to upload a document to a workspace. The `UploadManager` uses `UploadDocumentToRoom` method to upload a file to a specific workspace. This method returns `uploadResult` which contains a detailed information about the uploaded file. ```csharp #region devGuide16 // Get an instance of UploadManager UploadManager uploadManager = apiSession.GetUploadManager(); // Create a new SubmitDocumentsVdrJson JSON SubmitDocumentsVdrJson uploadInfo = new SubmitDocumentsVdrJson { OpenForAllRoom = false, Recipients = new RoomRecipientsJson { Groups = groups, Domains = domains, }, Folder = folder, TagValueList = null, DeviceType = DeviceType.SYNC }; // A call to the UploadDocumentToRoom UploadResult uploadResult = uploadManager.UploadDocumentToRoom(uploadInfo, roomId, destinationFileName, filename, null); #endregion ``` 15.2 Send a file via Workspaces This example is parallel to the preceding one, but applies to the Workspaces Exchange, the UploadManager uses UploadDocument method to upload a document to the exchange and send a link to it to email recipients. This method also returns uploadResult which contains a detailed information about the uploaded file. ```csharp #region devGuide17 // Get an instance of UploadManager UploadManager uploadManager = apiSession.GetUploadManager(); // Create a new SubmitDocumentSdsJson JSON SubmitDocumentSdsJson uploadInfo = new SubmitDocumentSdsJson { // A call to generate a guid for the document and assign it to DocumentGuids DocumentGuids = new HashSet<string> { uploadManager.GetNewGuidForDocument() }, // Create a new permission JSON Permission = new PermissionFromUserJson { Copy = true, Download = true, DownloadOriginal = false, ExpirationDate = DateTime.Now }, UserRecipients = userRecipients, ActiveDirectoryGroupsRecipients = ADGroupsRecipients, ListRecipients = listRecipients, WhoCanView = WhoCanView.RECEPIENTS_ONLY }; // A call to the UploadDocument UploadResult uploadResult = uploadManager.UploadDocument(uploadInfo, localPath, null, filename, null); #endregion ``` Example 5: Download a file This example shows how to download a document using `DownloadManager`. In the following snippets, it’s depicted some of the methods used to download a file. 16.1 Using DownloadFileById In the following snippet the file could be downloaded using `DownloadFileById` method for a specific document Id: ```csharp #region devGuide18 // Get an instance of DownloadManager DownloadManager downloadManager = apiSession.GetDownloadManager(); // A call to the DownloadFileById downloadManager.DownloadFileById(docId, string.Empty, roomId, destinationPath, lastUpdateTime, true, true); #endregion ``` 16.2 Using DownloadFileByName This method uses Document name to download the file: ```csharp #region devGuide19 // Get an instance of DownloadManager DownloadManager downloadManager = apiSession.GetDownloadManager(); // A call to the DownloadFileByName downloadManager.DownloadFileByName(roomId, folderPath, docName, destinationPath, lastUpdateTime); #endregion ``` 16.3 Using DownloadFileToBuffer It is also possible to download a file to a buffer using `DownloadFileToBuffer`. This method returns a byte array of the file downloaded. ```csharp #region devGuide20 // Get an instance of DownloadManager DownloadManager downloadManager = apiSession.GetDownloadManager(); // A call to the DownloadFileToBuffer byte[] buffer = downloadManager.DownloadFileToBuffer(docId, DownloadTypes.ORIGINAL); #endregion ``` Example 6: Enumerate files in a workspace This example will request a list of all documents in a Workspace that the user has access rights to. The server will return a list of documents or folders, which can then be iterated over. ```csharp #region devGuide9 Resource.Workspaces workspaces = apiSession.GetWorkspacesResource(); // Create an object to specify the details of what documents to list and how // they are returned. A few options are shown here. ListDocumentsVdrJson selectionJson = new ListDocumentsVdrJson { OrderAscending = false, FolderPath = "/" }; // Call the list method PagingItemListJson<BaseJson> response = workspaces.ListDocumentsV30(roomId, selectionJson); #endregion ``` Example 7: Change file permissions This case shows how permissions can be changed for a document in a Workspace. The document is selected by the group that has access rights to it. In this example, the permissions to be set are: edit, print, spotlight, watermark - No. All other permissions will remain unchanged. This case assumes the guid for the document is known; if not, a list of documents can be retrieved as shown in Example 3, the desired document selected by name, and the GUID retrieved from it. ```csharp #region devGuide10 // Create the json that indicates the group that has permissions to the document PermittedEntityFromUserJson groupPermission = new PermittedEntityFromUserJson { Address = groupName, EntityType = EntityType.GROUP }; List<PermittedEntityFromUserJson> permissionsList = new List<PermittedEntityFromUserJson> { groupPermission }; // Add the document GUID HashSet<string> documentGuids = new HashSet<string> { myDoc(Guid }; // Create the json for the permissions and set them to NO PermissionSetJson permissionSet = new PermissionSetJson { DownloadOriginal = YesNoDefault.NO, DownloadControlled = YesNoDefault.NO, Edit = YesNoDefault.NO, Print = YesNoDefault.NO, Spotlight = YesNoDefault.NO, Watermark = YesNoDefault.NO, Copy = YesNoDefault.NO, ProgrammaticAccess = YesNoDefault.NO, }; VdrEditPermissionsJson editPermissionsJson = new VdrEditPermissionsJson { PermittedEntities = permissionsList, DocumentGuids = documentGuids, PermissionSet = permissionSet }; // Make the call and get a BulkOperationResultJson back BulkOperationResultJson result = workspaces.EditPermissionsV30(roomId, editPermissionsJson); #endregion ``` Example 8: Enumerate folders and workspaces This example gets a list of all folders and workspaces that the user has access to. There are two steps: get a list of all workspaces and then get a list of all folders in these workspaces. 19.1 Get list of workspaces (rooms) for the user ```csharp #region devGuide11 Resource.Workspaces workspaces = apiSession.GetWorkspacesResource(); // This returns a list of rooms, which can be iterated over. The other parameters // include: addExternalData, adminMode, includeSyncData, includeWorkspacePolicyData, // and workspaceTypes. Please see the javadoc documentation for details. ItemListJson<WorkspaceInfoJson> itemListJson = workspaces.ListRoomsV30(null, true, true, false, false); #endregion ``` 19.2 Get list of folders in a specific Workspace ```csharp #region devGuide12 Resource.Workspaces workspaces = apiSession.GetWorkspacesResource(); // This returns a folder object, which contains details about the current workspace, // as well as a sub folder list that can be iterated over. FolderJson folderJson = workspaces.GetFolderTreeV30(roomId, null); List<FolderJson> subFolders = folderJson.SubFolders; #endregion ``` Example 9: Retrieve a list of activities for a named file This example shows how an activity log is retrieved for a document using the guid. The server will return a list of activity log entries, which can then be iterated over. ```csharp #region devGuide13 Files files = apiSession.GetFilesResource(); // Create an object to specify the documents activityLog request GetDocumentActivityLogRequestJson getDocumentActivityLogRequestJson = new GetDocumentActivityLogRequestJson { // The guid of a document to retrieve activity for DocumentGuid = documentGuid, // Indicates if only the last action for a user should be retrieved LastActionPerUser = false, // Indicates the page number to fetch of a multipage response PageNumber = 1, // The number of items to fetch per page PageSize = 100 }; // Call the get activity method PagingItemListJson<ActivityLogRecordJson> result = files.GetActivityLogV30(getDocumentActivityLogRequestJson); #endregion ``` Example 10: Add a user to a room group In this example, a new user list (of one or more users) is added to an existing group. The users’ email addresses, room id, and the group name are passed in as parameters. Request ```csharp #region devGuide3 Resource.Workspaces workspaces = apiSession.GetWorkspacesResource(); List<AddMemberToGroupJson> memberList = new List<AddMemberToGroupJson>(); // Loop through the List<String> userAddresses foreach (string currentAddress in userAddresses) { PermittedEntityFromUserJson currentEntity = new PermittedEntityFromUserJson { Address = currentAddress, EntityType = EntityType.USER }; // make a AddMemberToGroupJson for each user AddMemberToGroupJson currentMemberJson = new AddMemberToGroupJson { Entity = currentEntity }; memberList.Add(currentMemberJson); } // Set the group name to be a string and roomId is the integer identifying the room AddMembersToGroupWithGroupJson groupMemberJson = new AddMembersToGroupWithGroupJson { MembersList = memberList, RoomId = roomId, GroupName = groupName }; // Make the call to the Rooms resource and return "success" string result = workspaces.AddMembersToGroupV30(groupMemberJson); #endregion ``` Example 11: Delete a file from a workspace This example deletes one or more documents from a room. The server will return an object that indicates success, or details about any error that may have occurred. ```csharp #region devGuide14 Resource.Workspaces workspaces = apiSession.GetWorkspacesResource(); // Create an object to specify the documents to delete and if that will be permanent. DeleteDocumentsSelectionVdrJson documentGuidsJson = new DeleteDocumentsSelectionVdrJson { // Set permanent document deletion IsPermanent = true, // The set of guids for the documents to delete DocumentGuids = guidsForDeletion }; // Call the delete method BulkOperationResultJson bulkOperationResultJson = workspaces.DeleteDocumentsV30(roomId, documentGuidsJson); #endregion ``` Example 12: Remove a file from the Workspaces Inbox or Sent items This example is similar to the preceding case, but for a document in the Workspaces Exchange. ```csharp #region devGuide15 Files files = apiSession.GetFilesResource(); // Create an object to specify the documents to delete and if that will be permanent. DeleteDocumentsSelectionSdsJson documentGuidsJson = new DeleteDocumentsSelectionSdsJson { // Set permanent document deletion IsPermanent = true, // The set of guids for the documents to delete DocumentGuids = guidsForDeletion }; // Call the delete method BulkOperationResultJson bulkOperationResultJson = files.DeleteDocumentsV30(documentGuidsJson); #endregion ``` Example 13: Handling events Several objects in the Workspaces .NET SDK generate events when certain things happen such as when a user has successfully been authenticated or when an file upload has completed. The following examples show how to make use of these events. Classes that generate events: - ApiSession - SignInManager - DownloadManager - UploadManager Consult the Workspaces .NET SDK documentation for the events generated by each of these classes. 24.1 User authenticated event In this example the `SignInCompleteEventHandler` method is added to the `SignInCompleted` event of the `SignInManager`. Once this has been done, any time a user is successfully authenticated on the instance of the `ApiSession` class the event will be fired and the `SignInCompleteEventHandler` method would be called. ```csharp public ApiSession InitializeSession (string workspacesServer, string userEmail) { // create a new ApiSession object ApiSession apiSession = new ApiSession(workspacesServer); // get a reference to the SignInManager ISignInManager signInMgr = apiSession.SignInManager; // register our event handler signInMgr.SignInCompleted += SignInCompleteEventHandler; // login the user using OAuth LoginResult loginResult = apiSession.StartSessionWithOAuth(userEmail); // return the ApiSession return apiSession; } private void SignInCompleteEventHandler(object sender, EventArgs eventArgs) { Console.WriteLine("User signin completed"); } ``` ©2021, BlackBerry • ALL RIGHTS RESERVED. 24.2 Session expired event Whenever the authentication token for a user expires the Workspaces .NET SDK will attempt to obtain a new token. If the SDK is unable to create a new token it will fire a SessionExpired event. In this example the `SessionExpiredEventHandler` method is added to the ApiSession instance. ```csharp #endregion public ApiSession InitializeSession(string workspacesServer) { // create a new ApiSession object ApiSession apiSession = new ApiSession(workspacesServer); // register our event handler apiSession.SessionExpired += SessionExpiredEventHandler; // return the ApiSession return apiSession; } private void SessionExpiredEventHandler(object sender) { Console.WriteLine("Session expired"); } #endregion 24.3 Upload progress event When a file is being uploaded it might be good to provide feedback to a user on how the upload is progressing. By providing an event handler to the UploadManager an application could do just that. This example adds the OnUploadProgressChangedEventHandler method to the OnUploadProgressChanged event of an instance of the UploadManager class. At regular intervals the Workspaces .NET SDK will fire this event as a file is being upload. ```csharp #region devGuide3 public void UploadFile(ApiSession apiSession, SubmitDocumentsVdrJson uploadInfo, int workspaceId, string destinationName, string filename) { // get the UploadManager UploadManager upldMgr = apiSession.GetUploadManager(); // register our event handler upldMgr.OnUploadProgressChanged += OnUploadProgressChangedEventHandler; // upload the file upldMgr.UploadDocumentToRoom(uploadInfo, workspaceId, destinationName, filename, null); } private void OnUploadProgressChangedEventHandler( object sender, IFileRequestData fileRequestData, int progress, UploadStatus status) { Console.WriteLine("Uploading " + fileRequestData.LocalPath + ", " + progress + " percent complete."); } #endregion ``` Legal notice ©2016 BlackBerry. All rights reserved. Trademarks, including but not limited to BLACKBERRY, EMBLEM Design, WORKSPACES, WORKSPACES & Design and BLACKBERRY WORKSPACES & Design are the trademarks or registered trademarks of BlackBerry Limited, its subsidiaries and/or affiliates, the exclusive rights to which are expressly reserved. All other trademarks are the property of their respective owners. This documentation including all documentation incorporated by reference herein such as documentation provided or made available on the BlackBerry website provided or made accessible "AS IS" and "AS AVAILABLE" and without condition, endorsement, guarantee, representation, or warranty of any kind by BlackBerry Limited and its affiliated companies ("BlackBerry") and BlackBerry assumes no responsibility for any typographical, technical, or other inaccuracies, errors, or omissions in this documentation. In order to protect BlackBerry proprietary and confidential information and/or trade secrets, this documentation may describe some aspects of BlackBerry technology in generalized terms. BlackBerry reserves the right to periodically change information that is contained in this documentation; however, BlackBerry makes no commitment to provide any such changes, updates, enhancements, or other additions to this documentation to you in a timely manner or at all. This documentation might contain references to third-party sources of information, hardware or software, products or services including components and content such as content protected by copyright and/or third-party websites (collectively the "Third Party Products and Services"). BlackBerry does not control, and is not responsible for, any Third Party Products and Services including, without limitation the content, accuracy, copyright compliance, compatibility, performance, trustworthiness, legality, decency, links, or any other aspect of Third Party Products and Services. The inclusion of a reference to Third Party Products and Services in this documentation does not imply endorsement by BlackBerry of the Third Party Products and Services or the third party in any way. EXCEPT TO THE EXTENT SPECIFICALLY PROHIBITED BY APPLICABLE LAW IN YOUR JURISDICTION, ALL CONDITIONS, ENDORSEMENTS, GUARANTEES, REPRESENTATIONS, OR WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY CONDITIONS, ENDORSEMENTS, GUARANTEES, REPRESENTATIONS OR WARRANTIES OF DURABILITY, FITNESS FOR A PARTICULAR PURPOSE OR USE, MERCHANTABILITY, MERCHANTABLE QUALITY, SATISFACTORY QUALITY, OR TITLE, OR ARISING FROM A STATUTE OR CUSTOM OR A COURSE OF DEALING OR USAGE OF TRADE, OR RELATED TO THE DOCUMENTATION OR ITS USE, OR PERFORMANCE OR NON-PERFORMANCE OF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD PARTY PRODUCTS AND SERVICES REFERENCED HEREIN, ARE HEREBY EXCLUDED. YOU MAY ALSO HAVE OTHER RIGHTS THAT VARY BY STATE OR PROVINCE. SOME JURISDICTIONS MAY NOT ALLOW THE EXCLUSION OR LIMITATION OF IMPLIED WARRANTIES AND CONDITIONS. TO THE EXTENT PERMITTED BY LAW, ANY IMPLIED WARRANTIES OR CONDITIONS RELATING TO THE DOCUMENTATION TO THE EXTENT THEY CANNOT BE EXCLUDED AS SET OUT ABOVE, BUT CAN BE LIMITED, ARE HEREBY LIMITED TO NINETY (90) DAYS FROM THE DATE YOU FIRST ACQUIRED THE DOCUMENTATION OR THE ITEM THAT IS THE SUBJECT OF THE CLAIM. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION, IN NO EVENT SHALL BLACKBERRY BE LIABLE FOR ANY TYPE OF DAMAGES RELATED TO THIS DOCUMENTATION OR ITS USE, OR PERFORMANCE OR NON-PERFORMANCE OF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD PARTY PRODUCTS AND SERVICES REFERENCED HEREIN INCLUDING WITHOUT LIMITATION ANY OF THE FOLLOWING DAMAGES: DIRECT, CONSEQUENTIAL, EXEMPLARY, INCIDENTAL, INDIRECT, SPECIAL, PUNITIVE, OR AGGRAVATED DAMAGES, DAMAGES FOR LOSS OF PROFITS OR REVENUES, FAILURE TO REALIZE ANY EXPECTED SAVINGS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, LOSS OF BUSINESS OPPORTUNITY, OR CORRUPTION OR LOSS OF DATA, FAILURES TO TRANSMIT OR RECEIVE ANY DATA, PROBLEMS ASSOCIATED WITH ANY APPLICATIONS USED IN CONJUNCTION WITH BLACKBERRY PRODUCTS OR SERVICES, DOWNTIME COSTS, LOSS OF THE USE OF BLACKBERRY PRODUCTS OR SERVICES OR ANY PORTION THEREOF OR OF ANY AIRTIME SERVICES, COST OF SUBSTITUTE GOODS, COSTS OF COVER, FACILITIES OR SERVICES, COST OF CAPITAL, OR OTHER SIMILAR PECUNIARY LOSSES, WHETHER OR NOT SUCH DAMAGES WERE FORESEEN OR UNFORESEEN, AND EVEN IF BLACKBERRY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION, BLACKBERRY SHALL HAVE NO OTHER OBLIGATION, DUTY, OR LIABILITY WHATSOEVER IN CONTRACT, TORT, OR OTHERWISE TO YOU INCLUDING ANY LIABILITY FOR NEGLIGENCE OR STRICT LIABILITY. THE LIMITATIONS, EXCLUSIONS, AND DISCLAIMERS HEREIN SHALL APPLY: (A) IRRESPECTIVE OF THE NATURE OF THE CAUSE OF ACTION, DEMAND, OR ACTION BY YOU INCLUDING BUT NOT LIMITED TO BREACH OF CONTRACT, NEGLIGENCE, TORT, STRICT LIABILITY OR ANY OTHER LEGAL THEORY AND SHALL SURVIVE A FUNDAMENTAL BREACH OR BREACHES OR THE FAILURE OF THE ESSENTIAL PURPOSE OF THIS AGREEMENT OR OF ANY REMEDY CONTAINED HEREIN; AND (B) TO BLACKBERRY AND ITS AFFILIATED COMPANIES, THEIR SUCCESSORS, ASSIGNS, AGENTS, SUPPLIERS (INCLUDING AIRTIME SERVICE PROVIDERS), AUTHORIZED BLACKBERRY DISTRIBUTORS (ALSO INCLUDING AIRTIME SERVICE PROVIDERS) AND THEIR RESPECTIVE DIRECTORS, EMPLOYEES, AND INDEPENDENT CONTRACTORS. IN ADDITION TO THE LIMITATIONS AND EXCLUSIONS SET OUT ABOVE, IN NO EVENT SHALL ANY DIRECTOR, EMPLOYEE, AGENT, DISTRIBUTOR, SUPPLIER, INDEPENDENT CONTRACTOR OF BLACKBERRY OR ANY AFFILIATES OF BLACKBERRY HAVE ANY LIABILITY ARISING FROM OR RELATED TO THE DOCUMENTATION. Prior to subscribing for, installing, or using any Third Party Products and Services, it is your responsibility to ensure that your airtime service provider has agreed to support all of their features. Some airtime service providers might not offer Internet browsing functionality with a subscription to the BlackBerry® Internet Service. Check with your service provider for availability, roaming arrangements, service plans and features. Installation or use of Third Party Products and Services with BlackBerry's products and services may require one or more patent, trademark, copyright, or other licenses in order to avoid infringement or violation of third party rights. You are solely responsible for determining whether to use Third Party Products and Services and if any third party licenses are required to do so. If required you are responsible for acquiring them. You should not install or use Third Party Products and Services until all necessary licenses have been acquired. Any Third Party Products and Services that are provided with BlackBerry's products and services are provided as a convenience to you and are provided "AS IS" with no express or implied conditions, endorsements, guarantees, representations, or warranties of any kind by BlackBerry and BlackBerry assumes no liability whatsoever, in relation thereto. Your use of Third Party Products and Services shall be governed by and subject to you agreeing to the terms of separate licenses and other agreements applicable thereto with third parties, except to the extent expressly covered by a license or other agreement with BlackBerry. The terms of use of any BlackBerry product or service are set out in a separate license or other agreement with BlackBerry applicable thereto. NOTHING IN THIS DOCUMENTATION IS INTENDED TO SUPERSEDE ANY EXPRESS WRITTEN AGREEMENTS OR WARRANTIES PROVIDED BY BLACKBERRY FOR PORTIONS OF ANY BLACKBERRY PRODUCT OR SERVICE OTHER THAN THIS DOCUMENTATION. BlackBerry Enterprise Software incorporates certain third-party software. The license and copyright information associated with this software is available at http://worldwide.blackberry.com/legal/thirdpartysoftware.jsp. BlackBerry Limited 2200 University Avenue East Waterloo, Ontario Canada N2K 0A7 BlackBerry UK Limited 200 Bath Road Slough, Berkshire SL1 3XE United Kingdom Published in Canada ©2021, BlackBerry • ALL RIGHTS RESERVED.
{"Source-Url": "https://docs.blackberry.com/content/dam/docs-blackberry-com/release-pdfs/en/blackberry-workspaces-server/net/11_5/BlackBerry%20Workspaces%20-%20.NET%20SDK%20Developers%20Guide.pdf", "len_cl100k_base": 12992, "olmocr-version": "0.1.49", "pdf-total-pages": 39, "total-fallback-pages": 0, "total-input-tokens": 70297, "total-output-tokens": 14697, "length": "2e13", "weborganizer": {"__label__adult": 0.0003027915954589844, "__label__art_design": 0.00022971630096435547, "__label__crime_law": 0.0002129077911376953, "__label__education_jobs": 0.00048422813415527344, "__label__entertainment": 4.8995018005371094e-05, "__label__fashion_beauty": 0.00010949373245239258, "__label__finance_business": 0.000560760498046875, "__label__food_dining": 0.0001856088638305664, "__label__games": 0.0006508827209472656, "__label__hardware": 0.0015764236450195312, "__label__health": 0.00010216236114501952, "__label__history": 0.00010132789611816406, "__label__home_hobbies": 8.422136306762695e-05, "__label__industrial": 0.00018143653869628904, "__label__literature": 0.00011539459228515624, "__label__politics": 7.957220077514648e-05, "__label__religion": 0.00019049644470214844, "__label__science_tech": 0.0017261505126953125, "__label__social_life": 5.519390106201172e-05, "__label__software": 0.033203125, "__label__software_dev": 0.95947265625, "__label__sports_fitness": 0.00017750263214111328, "__label__transportation": 0.00023806095123291016, "__label__travel": 0.00011789798736572266}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 58748, 0.01055]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 58748, 0.34092]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 58748, 0.75404]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 0, null], [0, 2308, false], [2308, 2398, null], [2398, 3002, null], [3002, 3997, null], [3997, 5244, null], [5244, 8730, null], [8730, 10839, null], [10839, 13714, null], [13714, 15544, null], [15544, 19052, null], [19052, 20796, null], [20796, 22747, null], [22747, 23342, null], [23342, 25143, null], [25143, 27321, null], [27321, 27494, null], [27494, 30363, null], [30363, 31122, null], [31122, 32034, null], [32034, 33209, null], [33209, 33959, null], [33959, 35604, null], [35604, 36551, null], [36551, 37923, null], [37923, 39369, null], [39369, 40082, null], [40082, 41954, null], [41954, 43132, null], [43132, 44128, null], [44128, 45382, null], [45382, 46233, null], [46233, 46940, null], [46940, 48485, null], [48485, 49497, null], [49497, 50646, null], [50646, 54988, null], [54988, 58748, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 0, null], [0, 2308, true], [2308, 2398, null], [2398, 3002, null], [3002, 3997, null], [3997, 5244, null], [5244, 8730, null], [8730, 10839, null], [10839, 13714, null], [13714, 15544, null], [15544, 19052, null], [19052, 20796, null], [20796, 22747, null], [22747, 23342, null], [23342, 25143, null], [25143, 27321, null], [27321, 27494, null], [27494, 30363, null], [30363, 31122, null], [31122, 32034, null], [32034, 33209, null], [33209, 33959, null], [33959, 35604, null], [35604, 36551, null], [36551, 37923, null], [37923, 39369, null], [39369, 40082, null], [40082, 41954, null], [41954, 43132, null], [43132, 44128, null], [44128, 45382, null], [45382, 46233, null], [46233, 46940, null], [46940, 48485, null], [48485, 49497, null], [49497, 50646, null], [50646, 54988, null], [54988, 58748, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 58748, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 58748, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 58748, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 58748, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 58748, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 58748, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 58748, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 58748, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 58748, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 58748, null]], "pdf_page_numbers": [[0, 0, 1], [0, 0, 2], [0, 2308, 3], [2308, 2398, 4], [2398, 3002, 5], [3002, 3997, 6], [3997, 5244, 7], [5244, 8730, 8], [8730, 10839, 9], [10839, 13714, 10], [13714, 15544, 11], [15544, 19052, 12], [19052, 20796, 13], [20796, 22747, 14], [22747, 23342, 15], [23342, 25143, 16], [25143, 27321, 17], [27321, 27494, 18], [27494, 30363, 19], [30363, 31122, 20], [31122, 32034, 21], [32034, 33209, 22], [33209, 33959, 23], [33959, 35604, 24], [35604, 36551, 25], [36551, 37923, 26], [37923, 39369, 27], [39369, 40082, 28], [40082, 41954, 29], [41954, 43132, 30], [43132, 44128, 31], [44128, 45382, 32], [45382, 46233, 33], [46233, 46940, 34], [46940, 48485, 35], [48485, 49497, 36], [49497, 50646, 37], [50646, 54988, 38], [54988, 58748, 39]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 58748, 0.07432]]}
olmocr_science_pdfs
2024-11-25
2024-11-25