Data Algorithms:

Recipes for Scaling up with Hadoop and Spark

Mahmoud Parsian

Data Algorithms:
Recipes for Scaling up with Hadoop and Spark

Mahmoud Parsian

September 15, 2014

Dedication

This book is dedicated to my dear family:
my wife, Behnaz,
my daughter, Maral,
my son, Yaseen

i

Contents

Preface

xxiii

xxiv
Preface
0.1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiv
0.2 Relationship of Spark and Hadoop . . . . . . . . . . . . . . . xxvi
0.3 What is MapReduce? . . . . . . . . . . . . . . . . . . . . . . . xxxi
0.4 Why use MapReduce? . . . . . . . . . . . . . . . . . . . . . . xxxii
0.5 What Is in This Book? . . . . . . . . . . . . . . . . . . . . . . xxxiv
0.6 What Is the Focus of This Book? . . . . . . . . . . . . . . . . xxxv
0.7 What are Core Concepts of MapReduce/Hadoop? . . . . . . . xxxvi
0.8
Is MapReduce for Everything? . . . . . . . . . . . . . . . . . . xxxvii
0.9 What is not MapReduce . . . . . . . . . . . . . . . . . . . . . xxxvii
0.10 Who Is This Book For? . . . . . . . . . . . . . . . . . . . . . . xxxviii
0.11 What Software Is Used in This Book? . . . . . . . . . . . . . . xxxix
0.12 Using Code Examples
. . . . . . . . . . . . . . . . . . . . . . xxxix
xl
0.13 Where NOT to use MapReduce?
0.14 Chapters in This Book?
. . . . . . . . . . . . . . . . . . . . . xli
0.15 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . xlii
0.16 Comments and Questions for This Book? . . . . . . . . . . . . xliii

. . . . . . . . . . . . . . . .

1 Secondary Sort: Introduction

1.1 What is a Secondary Sort Problem? . . . . . . . . . . . . . . .
1.2 Solutions to Secondary Sort Problem . . . . . . . . . . . . . .
Sort Order of Intermediate Keys . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .

1.3 Data Flow Using Plug-in Classes

1.2.1

1
1
3
5
8

ii

1.4 Mapreduce/Hadoop Solution . . . . . . . . . . . . . . . . . . . 10
1.4.1
Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.4.2 Expected Output . . . . . . . . . . . . . . . . . . . . . 10
1.4.3 map() function . . . . . . . . . . . . . . . . . . . . . . 10
1.4.4
reduce() function . . . . . . . . . . . . . . . . . . . . . 11
1.4.5 Hadoop Implementation . . . . . . . . . . . . . . . . . 11
Sample Run of Hadoop Implementation . . . . . . . . . 13
1.4.6
Sample Run . . . . . . . . . . . . . . . . . . . . . . . . 14
1.4.7
1.5 What If Sorting Ascending or Descending . . . . . . . . . . . . 15
1.6 Spark Solution To Secondary Sorting . . . . . . . . . . . . . . 16
1.6.1 Time-Series as Input . . . . . . . . . . . . . . . . . . . 16
1.6.2 Expected Output . . . . . . . . . . . . . . . . . . . . . 17
1.6.3 Option-1: Secondary Sorting in Memory . . . . . . . . 17
1.6.4
Spark Sample Run . . . . . . . . . . . . . . . . . . . . 25
1.6.5 Option-2: Secondary Sorting using Framework . . . . . 30

2 Secondary Sorting: Detailed Example

31
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.1
2.2 Secondary Sorting Technique . . . . . . . . . . . . . . . . . . . 32
2.3 Complete Example of Secondary Sorting . . . . . . . . . . . . 37
2.3.1 Problem Statement . . . . . . . . . . . . . . . . . . . . 37
Input Format . . . . . . . . . . . . . . . . . . . . . . . 37
2.3.2
2.3.3 Output Format . . . . . . . . . . . . . . . . . . . . . . 38
2.3.4 Composite Key . . . . . . . . . . . . . . . . . . . . . . 38
Sample Run . . . . . . . . . . . . . . . . . . . . . . . . 42
2.3.5
2.4 Secondary Sort using New Hadoop API . . . . . . . . . . . . . 44

3 Top 10 List

47
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
3.1
3.2 Top-N Formalized . . . . . . . . . . . . . . . . . . . . . . . . . 48
3.3 MapReduce Solution . . . . . . . . . . . . . . . . . . . . . . . 49
Implementation in Hadoop . . . . . . . . . . . . . . . . . . . . 54
3.4
Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
3.4.1
3.4.2
Sample Run 1: ﬁnd top 10 list . . . . . . . . . . . . . . 55
3.4.3 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
. . . . . . . . . . . . . . 57
3.4.4
3.5 Bottom 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
. . . . . . . . . . . . . . 58
3.6 Spark Implementation: Unique Keys

Sample Run 2: ﬁnd top 5 list

iii

Introduction . . . . . . . . . . . . . . . . . . . . . . . . 59
3.6.1
3.6.2 What is an RDD? . . . . . . . . . . . . . . . . . . . . . 60
Spark’s Function Classes . . . . . . . . . . . . . . . . . 60
3.6.3
Spark Solution for Top-10 Pattern . . . . . . . . . . . . 61
3.6.4
3.6.5 Complete Spark Solution for Top-10 Pattern . . . . . . 62
Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
3.6.6
. . . . . . . . . . . . . . 67
Sample Run : ﬁnd top-10 list
3.6.7
3.7 What If for Top-N . . . . . . . . . . . . . . . . . . . . . . . . 69
. . . . . 70
Shared Data Structures Deﬁnition and Usage
3.8 What If for Bottom-N . . . . . . . . . . . . . . . . . . . . . . 70
3.9 Spark Implementation : Non-Unique Keys . . . . . . . . . . . 71
3.9.1 Complete Spark Solution for Top-10 Pattern . . . . . . 73

3.7.1

4 Left Outer Join in MapReduce

4.1
4.2

84
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Implementation of Left Outer Join in MapReduce . . . . . . . 89
4.2.1 MapReduce Phase-1 . . . . . . . . . . . . . . . . . . . 89
. . . 94
4.2.2 MapReduce Phase-2: Counting Unique Locations
Implementation Classes in Hadoop . . . . . . . . . . . 95
4.2.3
4.3 Sample Run . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Input for Phase-1 . . . . . . . . . . . . . . . . . . . . . 95
4.3.1
run Phase-1 . . . . . . . . . . . . . . . . . . . . . . . . 96
4.3.2
4.3.3 View Output of Phase-1 (Input of Phase-2)
. . . . . . 97
4.3.4 Run Phase-2 . . . . . . . . . . . . . . . . . . . . . . . . 97
4.3.5 View Output of Phase-2 . . . . . . . . . . . . . . . . . 98
4.4 Spark Implementation . . . . . . . . . . . . . . . . . . . . . . 98
Spark Program . . . . . . . . . . . . . . . . . . . . . . 101
STEP-0: Import Required Classes . . . . . . . . . . . . 101
. . . . . . . . . . . . 102
STEP-1: Read Input Parameters
STEP-2: Create JavaSparkContext Object . . . . . . . 103
STEP-3: Create a JavaPairRDD for Users . . . . . . . 103
STEP-4: Create a JavaPairRDD for Transactions . . . 104
STEP-5: Create a union of RDD’s created by STEP-3
and STEP-4 . . . . . . . . . . . . . . . . . . . . . . . . 104
STEP-6: Create a JavaPairRDD(userID, List(T2)) by
calling groupBy() . . . . . . . . . . . . . . . . . . . . . 105
STEP-7: Create a productLocationsRDD as JavaPair-
RDD(String,String) . . . . . . . . . . . . . . . . . . . . 106

4.4.1
4.4.2
4.4.3
4.4.4
4.4.5
4.4.6
4.4.7

4.4.9

4.4.8

iv

4.4.10 STEP-8: Find all locations for a product . . . . . . . . 108
4.4.11 STEP-9: Finalize output by changing ”value” . . . . . 108
4.4.12 STEP-10: Print the ﬁnal result RDD . . . . . . . . . . 109
4.4.13 Running Spark Solution . . . . . . . . . . . . . . . . . 109
4.5 Running Spark on YARN . . . . . . . . . . . . . . . . . . . . 111
4.5.1
Script to Run Spark on YARN . . . . . . . . . . . . . . 111
4.5.2 Running Script . . . . . . . . . . . . . . . . . . . . . . 112
. . . . . . . . . . . . . . . 114
4.5.3 Checking Expected Output
4.6 Left Outer Join by Spark’s leftOuterJoin() . . . . . . . . . . . 114
. . . . . . . . . . . . . . . . . . . . . 116
. . . . 117
STEP-0: import required classes and interfaces
STEP-1: read input parameters . . . . . . . . . . . . . 117
STEP-2: create Spark’s context object . . . . . . . . . 118
STEP-3: create RDD for user’s data . . . . . . . . . . 118
STEP-4: Create usersRDD: The ”right” Table . . . . . 119
STEP-5: create transactionRDD for transaction’s data 119
STEP-6: Create transactionsRDD: The Left Table . . . 120
STEP-7: use Spark’s built-in JavaPairRDD.leftOuterJoin()
method . . . . . . . . . . . . . . . . . . . . . . . . . . 120
4.6.10 STEP-8: create (product, location) pairs . . . . . . . . 121
4.6.11 STEP-9: group (K=product, V=location) pairs by K . 122
4.6.12 STEP-10: create ﬁnal output (K=product, V=Set(location))122
4.6.13 Sample Run by YARN . . . . . . . . . . . . . . . . . . 123

4.6.1 High-Level Steps
4.6.2
4.6.3
4.6.4
4.6.5
4.6.6
4.6.7
4.6.8
4.6.9

5 Order Inversion Pattern

126
5.1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
5.2 Example of Order Inversion Pattern . . . . . . . . . . . . . . . 128
5.3 MapReduce for Order Inversion Pattern . . . . . . . . . . . . 129
5.3.1 Custom Partitioner . . . . . . . . . . . . . . . . . . . . 130
5.3.2 Relative Frequency Mapper
. . . . . . . . . . . . . . . 131
5.3.3 Relative Frequency Reducer . . . . . . . . . . . . . . . 133
Implementation Classes in Hadoop . . . . . . . . . . . 134
5.3.4
5.4 Sample Run . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
5.4.1
Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
5.4.2 Running MapReduce Job . . . . . . . . . . . . . . . . . 135
. . . . . . . . . . . . . . . . . . . . 135
5.4.3 Generated Output

v

6 Moving Average

6.1

137
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
6.1.1 Example-1: Time Series Data . . . . . . . . . . . . . . 138
6.1.2 Example-2: Time Series Data . . . . . . . . . . . . . . 138
6.2 Formal Deﬁnition . . . . . . . . . . . . . . . . . . . . . . . . . 139
6.3 Moving Average by POJO . . . . . . . . . . . . . . . . . . . . 140
6.3.1 First solution: using Queue
. . . . . . . . . . . . . . . 140
Second Solution : using Array . . . . . . . . . . . . . . 141
6.3.2
6.3.3 Testing of Moving Average . . . . . . . . . . . . . . . . 142
Sample Run . . . . . . . . . . . . . . . . . . . . . . . . 143
6.3.4
6.4 MapReduce Solution . . . . . . . . . . . . . . . . . . . . . . . 143
6.4.1
Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
6.4.2 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
6.4.3 MapReduce Solution: Option-1: sort in RAM . . . . . 145
6.4.4 Hadoop Implementation: sort in RAM . . . . . . . . . 148
6.4.5
Sample Run . . . . . . . . . . . . . . . . . . . . . . . . 148
6.4.6 MapReduce Solution: Option-2: Sort by MR Framework151
6.5 Sample Run . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157

7 Market Basket Analysis

160
7.1 What is Market Basket Analysis? . . . . . . . . . . . . . . . . 160
7.2 MapReduce/Hadoop Solution . . . . . . . . . . . . . . . . . . 161
7.3 What are the Application areas for MBA? . . . . . . . . . . . 163
7.4 Market Basket Analysis using MapReduce . . . . . . . . . . . 163
. . . . . . . . . . . . . . . . . . . . . . 167
7.4.1 Mapper Formal
7.4.2 Reducer . . . . . . . . . . . . . . . . . . . . . . . . . . 168
7.5 MapReduce/Hadoop Implementation Classes . . . . . . . . . . 169
7.5.1 Find Sorted Combinations . . . . . . . . . . . . . . . . 169
7.5.2 Market Basket Analysis Driver: MBADriver . . . . . . 170
7.5.3 Market Basket Analysis Mapper: MBAMapper
. . . . 171
Sample Run . . . . . . . . . . . . . . . . . . . . . . . . 173
7.5.4
7.6 Spark/Hadoop Solution . . . . . . . . . . . . . . . . . . . . . . 174
7.6.1 MapReduce Algorithm . . . . . . . . . . . . . . . . . . 176
Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
7.6.2
Spark Implementation . . . . . . . . . . . . . . . . . . 176
7.6.3
. . . . . . . . . 191
7.6.4 Creating Item Sets From Transactions

vi

8 Common Friends

8.5.1

8.5 Solution 1: Hadoop Implementation using Text

194
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
8.1
8.2
Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
8.3 Common Friends Algorithm . . . . . . . . . . . . . . . . . . . 196
8.4 MapReduce Algorithm . . . . . . . . . . . . . . . . . . . . . . 197
8.4.1 MapReduce Algorithm in Action . . . . . . . . . . . . 198
. . . . . . . . 201
Sample Run for Solution 1 . . . . . . . . . . . . . . . . 202
8.6 Solution 2: Hadoop Implementation using ArrayListOfLongsWritable
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Sample Run for Solution 2 . . . . . . . . . . . . . . . . 205
8.6.1
8.7 Spark Solution . . . . . . . . . . . . . . . . . . . . . . . . . . 207
STEP-0: Import Required Classes . . . . . . . . . . . . 209
STEP-1: Check Input Parameters . . . . . . . . . . . . 210
STEP-2: Create a JavaSparkContext Object . . . . . . 210
STEP-3: Read Input . . . . . . . . . . . . . . . . . . . 210
STEP-4: Apply a Mapper . . . . . . . . . . . . . . . . 211
STEP-5: Apply a Reducer . . . . . . . . . . . . . . . . 212
STEP-6: Find Common Friends . . . . . . . . . . . . . 212
8.8 Sample Run of a Spark Program . . . . . . . . . . . . . . . . . 214
8.8.1 HDFS Input . . . . . . . . . . . . . . . . . . . . . . . . 214
Script to Run Spark Program . . . . . . . . . . . . . . 214
8.8.2
8.8.3 Log of Sample Run . . . . . . . . . . . . . . . . . . . . 215

8.7.1
8.7.2
8.7.3
8.7.4
8.7.5
8.7.6
8.7.7

9 Recommendation Engines using MapReduce

218
9.1 Customers Who Bought This Item Also Bought . . . . . . . . 220
9.1.1
Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
9.1.2 Expected Output . . . . . . . . . . . . . . . . . . . . . 220
9.1.3 MapReduce Solution . . . . . . . . . . . . . . . . . . . 220
9.2 Frequently Bought Together . . . . . . . . . . . . . . . . . . . 226
9.2.1
Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
9.2.2 MapReduce Solution . . . . . . . . . . . . . . . . . . . 228
9.3 Recommend People Connection . . . . . . . . . . . . . . . . . 232
9.3.1
Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
9.3.2 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
9.3.3 MapReduce Solution . . . . . . . . . . . . . . . . . . . 236
9.4 Spark Implementation . . . . . . . . . . . . . . . . . . . . . . 237
STEP-0: Import Required Classes . . . . . . . . . . . . 239

9.4.1

vii

. . . . . . . . . . . 239
STEP-1: Handle Input Parameters
9.4.2
STEP-2: Create Spark’s Context Object . . . . . . . . 240
9.4.3
STEP-3: Read HDFS Input File . . . . . . . . . . . . . 240
9.4.4
STEP-4: Implement map() Function . . . . . . . . . . 241
9.4.5
STEP-5: Implement reduce() Function . . . . . . . . . 243
9.4.6
. . . . . . . . . . . . 243
STEP-6: Generate Final Output
9.4.7
9.4.8 Convenient Methods
. . . . . . . . . . . . . . . . . . . 244
9.4.9 HDFS Input . . . . . . . . . . . . . . . . . . . . . . . . 245
9.4.10 Script to Run Spark Program . . . . . . . . . . . . . . 245
9.4.11 Program Run Log . . . . . . . . . . . . . . . . . . . . . 246

10 Content-Based Recommendation: Movies

252
10.1 Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
10.2 MapReduce PHASE-1 . . . . . . . . . . . . . . . . . . . . . . 254
10.3 MapReduce PHASE-2 and PHASE-3 . . . . . . . . . . . . . . 255
10.4 MapReduce-Phase-2 Mapper . . . . . . . . . . . . . . . . . . . 256
10.5 MapReduce-Phase-2 Reducer
. . . . . . . . . . . . . . . . . . 257
10.6 MapReduce-Phase-3 Mapper . . . . . . . . . . . . . . . . . . . 259
10.7 MapReduce-Phase-3 Reducer
. . . . . . . . . . . . . . . . . . 260
10.8 More Similarity Measures
. . . . . . . . . . . . . . . . . . . . 262
10.9 Movie Recommendation in Spark . . . . . . . . . . . . . . . . 263
10.9.1 High-Level Solution in Spark . . . . . . . . . . . . . . . 264
10.9.2 High-Level Solution: All Steps . . . . . . . . . . . . . . 264
. . . . . . . . . . . 265
10.9.3 STEP-0: Import Required Classes
. . . . . . . . . . . 265
10.9.4 STEP-1: Handle Input Parameters
10.9.5 STEP-2: Create a Spark’s Context Object . . . . . . . 266
10.9.6 STEP-3: Read Input File and Create RDD . . . . . . . 266
10.9.7 STEP-4: Find Who Has Rated Movies . . . . . . . . . 267
10.9.8 STEP-5: Group moviesRDD by Movie . . . . . . . . . 268
10.9.9 STEP-6: Find Number of Raters per Movie
. . . . . . 269
10.9.10 STEP-7: Perform Self-Join . . . . . . . . . . . . . . . . 270
10.9.11 STEP-8: Remove Duplicate (movie1, movie2) Pairs . . 272
10.9.12 STEP-9: Generate All (movie1, movie2) Combinations 273
10.9.13 STEP-10: Group Movie Pairs . . . . . . . . . . . . . . 274
10.9.14 STEP-11: Calculate Correlations
. . . . . . . . . . . . 274
10.9.15 STEP-12: Print Final Results . . . . . . . . . . . . . . 275
10.9.16 Helper Method: calculateCorrelations() . . . . . . . . . 275
10.9.17 Helper Method: calculatePearsonCorrelation() . . . . . 276

viii

10.9.18 Helper Method: calculateCosineCorrelation() . . . . . . 277
10.9.19 Helper Method: calculateJaccardCorrelation() . . . . . 277
10.10Sample Run of Spark Program . . . . . . . . . . . . . . . . . . 277
10.10.1 HDFS Input . . . . . . . . . . . . . . . . . . . . . . . . 277
. . . . . . . . . . . . . . . . . . . . . . . . . . . 278
10.10.2 Script
10.11Log of Sample Run . . . . . . . . . . . . . . . . . . . . . . . . 279
10.11.1 Inspecting HDFS Output . . . . . . . . . . . . . . . . . 283

11 Smarter Email Marketing with Markov Model

285
11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
. . . . . . . . . . . . . . . . . . . 286
11.2 Markov Chain in a Nutshell
. . . . . . . . . . . . . . . . 288
11.3 Markov Model using MapReduce
11.3.1 MapReduce to Generate Time-ordered Transactions . . 290
11.3.2 MapReduce to Generate Markov State Transition . . . 300
11.4 Using Markov Model to Predict Next Email Marketing Date . 306

12 K-Means Clustering

308
12.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
12.2 What is K-Means Clustering . . . . . . . . . . . . . . . . . . . 311
12.3 What are the Applications of Clustering? . . . . . . . . . . . . 312
12.4 K-Means Clustering Method: Partitioning Approach . . . . . 313
12.5 K-Means Distance Function . . . . . . . . . . . . . . . . . . . 314
12.6 K-Means Clustering Step-by-Step Example . . . . . . . . . . . 315
12.7 K-Means Clustering Formalized . . . . . . . . . . . . . . . . . 315
12.8 MapReduce Solution for K-Means Clustering . . . . . . . . . . 316
12.8.1 MapReduce Solution: map() . . . . . . . . . . . . . . . 318
12.8.2 MapReduce Solution: combine() . . . . . . . . . . . . . 319
12.8.3 MapReduce Solution: reduce() . . . . . . . . . . . . . . 320
12.9 MapReduce K-Means Clustering Step-by-Step Example . . . . 321
12.10K-Means Implementation by Spark . . . . . . . . . . . . . . . 321
12.10.1 Sample Run of K-Means by Spark . . . . . . . . . . . . 324

13 kNN: k-Nearest-Neighbors

326
13.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
13.2 kNN Classiﬁcation . . . . . . . . . . . . . . . . . . . . . . . . 327
13.3 Distance Functions . . . . . . . . . . . . . . . . . . . . . . . . 328
13.4 kNN Example . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
13.5 An Informal kNN Algorithm . . . . . . . . . . . . . . . . . . . 329

ix

13.6 Formal kNN Algorithm . . . . . . . . . . . . . . . . . . . . . . 331
13.6.1 Java-like Non-MapReduce Solution for kNN . . . . . . 331
13.7 kNN Implementation in Spark . . . . . . . . . . . . . . . . . . 333
13.7.1 Formalizing kNN for Spark Implementation . . . . . . 334
13.7.2 Input Data Set Formats
. . . . . . . . . . . . . . . . . 335
13.7.3 kNN Implementation in Spark . . . . . . . . . . . . . . 337

14 Naive Bayes

352
14.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
14.2 Training and Learning Stage . . . . . . . . . . . . . . . . . . . 354
14.2.1 Example: Training Data (Numeric Data) . . . . . . . . 355
. . . . . . . 356
14.2.2 Example: Training Data (Symbolic Data)
14.3 Conditional Probability . . . . . . . . . . . . . . . . . . . . . . 357
14.4 The Naive Bayes Classiﬁer . . . . . . . . . . . . . . . . . . . . 358
14.4.1 The Naive Bayes Classiﬁer Example . . . . . . . . . . . 359

14.5 The Naive Bayes Classiﬁer: MapReduce Solution for Symbolic

Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
14.5.1 STAGE-1: Building Classiﬁer Using Symbolic Training

Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362

14.5.2 STAGE-2: Using Classiﬁer To Classify New Symbolic

Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369

14.6 The Naive Bayes Classiﬁer: MapReduce Solution for Numeric

Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
14.7 Naive Bayes Classiﬁer Implementation in Spark . . . . . . . . 374
14.7.1 STAGE-1: Building Classiﬁer Using Training Data . . 375
14.7.2 STAGE-2: Using Classiﬁer To Classify New Data . . . 385
. . . . . . . . . . . . . . . . . . . . . . 391

14.8 Using Apache Mahout

15 Sentiment Analysis

392
15.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
15.1.1 Sentiment Examples
. . . . . . . . . . . . . . . . . . . 393
15.1.2 Sentiment Scores: Positive or Negative . . . . . . . . . 393
15.2 Steps for Sentiment Analysis . . . . . . . . . . . . . . . . . . . 395
15.3 A Simple MapReduce for Sentiment Analysis . . . . . . . . . . 395
15.3.1 map() for Sentiment Analysis
. . . . . . . . . . . . . . 396
15.3.2 reduce() for Sentiment Analysis . . . . . . . . . . . . . 397

x

16 Finding, Counting and Listing all Triangles in Large Graphs398
16.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
16.2 Basic Graph Concepts
. . . . . . . . . . . . . . . . . . . . . . 399
16.3 Importance of Counting Triangles . . . . . . . . . . . . . . . . 402
16.4 MapReduce Solution . . . . . . . . . . . . . . . . . . . . . . . 402
16.5 MapReduce in Action . . . . . . . . . . . . . . . . . . . . . . . 403
16.6 STEP-3: Remove Duplicate Triangles . . . . . . . . . . . . . . 406
16.6.1 STEP-3: Mapper . . . . . . . . . . . . . . . . . . . . . 406
. . . . . . . . . . . . . . . . . . . . . 407
16.6.2 STEP-3: Reduer
16.7 Hadoop Implementation . . . . . . . . . . . . . . . . . . . . . 408
16.7.1 Sample Run . . . . . . . . . . . . . . . . . . . . . . . . 408
16.8 Spark Implementation . . . . . . . . . . . . . . . . . . . . . . 413
. . . 413
16.8.1 STEP-0: Import Required Classes and Interfaces
16.8.2 STEP-1: Read Input Parameters
. . . . . . . . . . . . 414
16.8.3 STEP-2: Create a Spark Context Object . . . . . . . . 414
16.8.4 STEP-3: Read Graph via HDFS Input . . . . . . . . . 415
16.8.5 STEP-4: Create All Graph Edges . . . . . . . . . . . . 415
16.8.6 STEP-5: Create RDD To Generate Triads . . . . . . . 416
16.8.7 STEP-6: Create All Possible Triads . . . . . . . . . . . 417
16.8.8 STEP-7: Create RDD To Generate Triangles . . . . . . 418
16.8.9 STEP-8: Create All Triangles . . . . . . . . . . . . . . 419
16.8.10 Step-9: Create Unique Triangles . . . . . . . . . . . . . 421
16.9 Spark Sample Run . . . . . . . . . . . . . . . . . . . . . . . . 421
16.9.1 Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
. . . . . . . . . . . . . . . . . . . . . . . . . . . 422
16.9.2 Script
16.9.3 Running Script . . . . . . . . . . . . . . . . . . . . . . 422

17 K-mer Counting

425
17.1 Introduction to K-mers . . . . . . . . . . . . . . . . . . . . . . 425
17.2 K-mer counting using MapReduce . . . . . . . . . . . . . . . . 427
17.2.1 K-mer counting using MapReduce: map()
. . . . . . . 427
17.2.2 K-mer counting using MapReduce: reduce() . . . . . . 427
17.2.3 K-mer Counting with MapReduce and Hadoop . . . . . 428
17.3 Input Data for K-mer Counting . . . . . . . . . . . . . . . . . 429
17.3.1 Sample Runs of K-mer Counting . . . . . . . . . . . . 429
17.4 K-mer Implementation in Spark . . . . . . . . . . . . . . . . . 430
17.4.1 K-mer High-Level Solution in Spark . . . . . . . . . . . 431
. . . . 432
17.4.2 STEP-0: import required classes and interfaces

xi

. . . . . . . . . . . . . . . . 432
17.4.3 createJavaSparkContext()
17.4.4 STEP-1: handle input parameters . . . . . . . . . . . . 433
17.4.5 STEP-2: create a Spark context object . . . . . . . . . 433
17.4.6 STEP-3: broadcast global shared objects . . . . . . . . 433
17.4.7 STEP-4: read FASTQ ﬁle from HDFS and create the

ﬁrst RDD . . . . . . . . . . . . . . . . . . . . . . . . . 434
17.4.8 STEP-5: ﬁlter redundant records
. . . . . . . . . . . . 435
. . . . . . . . . . . . . . . . 436
17.4.9 STEP-6: generate K-mers
17.4.10 STEP-7: combine/reduce frequent kmers . . . . . . . . 437
17.4.11 STEP-8: create a local top-N . . . . . . . . . . . . . . 438
17.4.12 STEP-9: Find Final top-N . . . . . . . . . . . . . . . . 439
17.4.13 STEP-10: Emit Final top-N . . . . . . . . . . . . . . . 439
17.4.14 YARN Script for Spark . . . . . . . . . . . . . . . . . . 440
17.4.15 HDFS Input . . . . . . . . . . . . . . . . . . . . . . . . 440
17.4.16 Output for Final Top-N . . . . . . . . . . . . . . . . . 441

18 DNA-Sequencing

442
18.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
18.2 Input to DNA-Sequencing . . . . . . . . . . . . . . . . . . . . 446
18.3 Input data validation . . . . . . . . . . . . . . . . . . . . . . . 446
18.4 DNA-Sequencing: Alignment . . . . . . . . . . . . . . . . . . . 447
18.5 MapReduce Algorithms for DNA-Sequencing . . . . . . . . . . 448
. . . . 453
18.6 MR Algorithms: Step-1: DNA-Sequencing: Alignment
18.6.1 Step-1: map(): Alignment . . . . . . . . . . . . . . . . 455
18.6.2 Step-1: reduce(): Alignment . . . . . . . . . . . . . . . 456
18.7 Step-2: DNA-Sequencing: Recalibration . . . . . . . . . . . . 461
18.8 Step-3: DNA-Sequencing: Variant Detection . . . . . . . . . . 466
18.8.1 Variant Detection Mapper . . . . . . . . . . . . . . . . 467
18.8.2 Variant Detection Reducer . . . . . . . . . . . . . . . . 468

19 Cox Regression

470
19.1 Introduction to Survival Analysis using Cox Regression . . . . 470
19.2 Cox Model in a Nutshell
. . . . . . . . . . . . . . . . . . . . . 471
19.3 MapReduce Solution for Cox Regression . . . . . . . . . . . . 472
19.3.1 Cox Regression Basic Terminology . . . . . . . . . . . 473
19.4 Cox Regression by using R Language . . . . . . . . . . . . . . 474
19.5 Problem Statement . . . . . . . . . . . . . . . . . . . . . . . . 475
19.6 Cox Regression POJO Solution . . . . . . . . . . . . . . . . . 476

xii

19.7 Input for MapReduce . . . . . . . . . . . . . . . . . . . . . . . 477
. . . . . . . . . . . . . . . . . 479
19.8 Cox Regression by MapReduce
19.8.1 Cox Regression PHASE-1: map() . . . . . . . . . . . . 479
19.8.2 Cox Regression PHASE-1: reduce() . . . . . . . . . . . 480
19.8.3 Cox Regression PHASE-2: map() . . . . . . . . . . . . 481
19.8.4 Sample Output Generated by PHASE-2 reduce()
. . . 483
19.8.5 Sample Output Generated by PHASE-2 map() . . . . . 484
19.8.6 Cox Regression by MapReduce: How Does It Work . . 484

20 Cochran-Armitage Test for Trend

486
20.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
20.2 Cochran-Armitage Algorithm . . . . . . . . . . . . . . . . . . 487
20.3 Application of Cochran-Armitage . . . . . . . . . . . . . . . . 493
20.4 MapReduce Solution . . . . . . . . . . . . . . . . . . . . . . . 496
20.4.1 Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
20.4.2 Expected Output . . . . . . . . . . . . . . . . . . . . . 497
20.4.3 Mapper
. . . . . . . . . . . . . . . . . . . . . . . . . . 498
20.4.4 Reducer . . . . . . . . . . . . . . . . . . . . . . . . . . 499
20.5 MapReduce/Hadoop Implementation . . . . . . . . . . . . . . 503
20.5.1 Sample Run of MapReduce/Hadoop Implementation . 504

21 Allelic Frequency

507
21.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
. . . . . . . . . . . . . . . . . . . . . . . . . 509
21.2 Basic Deﬁnitions
. . . . . . . . . . . . . . . . . . . . . . . 509
21.2.1 Chromosome
21.2.2 Bioset
. . . . . . . . . . . . . . . . . . . . . . . . . . . 509
21.2.3 Allele and Allelic Frequency . . . . . . . . . . . . . . . 510
21.2.4 Source of Data for Allelic Frequency . . . . . . . . . . 510
21.2.5 Allelic Frequency Analysis by Fisher’s Exact Test . . . 512
21.2.6 Fisher’s Exact Test . . . . . . . . . . . . . . . . . . . . 512
21.3 Formal Problem Statement . . . . . . . . . . . . . . . . . . . . 514
21.4 MapReduce Phase-1 . . . . . . . . . . . . . . . . . . . . . . . 515
21.4.1 Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
21.4.2 Output/Result
. . . . . . . . . . . . . . . . . . . . . . 517
21.4.3 MapReduce Solution for Allelec Frequency . . . . . . . 519
21.4.4 Phase-1 Mapper . . . . . . . . . . . . . . . . . . . . . . 519
21.4.5 Phase-1 Reducer
. . . . . . . . . . . . . . . . . . . . . 520
21.4.6 Sample Run of MapReduce/Hadoop Implementation . 526

xiii

21.4.7 Sample Plot of Pvalues . . . . . . . . . . . . . . . . . . 528
21.5 MapReduce Phase-2 . . . . . . . . . . . . . . . . . . . . . . . 530
21.5.1 Phase-2: Mapper for Bottom-100 . . . . . . . . . . . . 532
21.5.2 Phase-2: Reducer for ”Bottom 100” . . . . . . . . . . . 533
21.6 Is Bottom 100 List A Monoid? . . . . . . . . . . . . . . . . . . 534
21.6.1 Hadoop Solution for Bottom 100 List . . . . . . . . . . 535
21.6.2 Sample Run of Bottom 100 List . . . . . . . . . . . . . 536
21.7 MapReduce Phase-3 . . . . . . . . . . . . . . . . . . . . . . . 536
21.7.1 Phase-3: Mapper for Bottom-100 . . . . . . . . . . . . 538
21.7.2 Phase-3: Reducer for ”Bottom 100” . . . . . . . . . . . 539
21.7.3 Hadoop Solution for Bottom 100 List Per Chromosome 541
21.7.4 Sample Run of Bottom 100 List Per Chromosome . . . 541

22 The T-Test

542
22.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
22.2 MapReduce Problem Statement . . . . . . . . . . . . . . . . . 547
22.3 Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
22.4 Expected Output . . . . . . . . . . . . . . . . . . . . . . . . . 548
22.5 MapReduce Solution . . . . . . . . . . . . . . . . . . . . . . . 548
22.6 Hadoop Implementation . . . . . . . . . . . . . . . . . . . . . 550
22.7 Spark Implementation . . . . . . . . . . . . . . . . . . . . . . 551
. . . . . . . . . . . . . . . . . . . . . 553
22.7.1 High Level Steps
. . . . 554
22.7.2 STEP-0: import required classes and interfaces
22.7.3 Create JavaSparkContext
. . . . . . . . . . . . . . . . 554
22.7.4 Create TimeTable Data Structure . . . . . . . . . . . . 555
22.7.5 Create RDD for All Biosets
. . . . . . . . . . . . . . . 555
22.7.6 STEP-1: handle input parameters . . . . . . . . . . . . 556
22.7.7 Create time table data structure . . . . . . . . . . . . . 556
22.7.8 STEP-3: create a spark context object . . . . . . . . . 556
22.7.9 High Level Steps
. . . . . . . . . . . . . . . . . . . . . 557
22.7.10 STEP-5: create RDD for all biosets . . . . . . . . . . . 557
22.7.11 STEP-6: map bioset records into JavaPairRDD(K,V)

pairs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
22.7.12 STEP-7: group biosets by GENE-ID . . . . . . . . . . 557
22.7.13 STEP-8: perform Ttest for every GENE-ID . . . . . . 558
22.7.14 Ttest Algorithm . . . . . . . . . . . . . . . . . . . . . . 559
22.7.15 Input for Spark Program . . . . . . . . . . . . . . . . . 560
22.7.16 Spark on YARN Script . . . . . . . . . . . . . . . . . . 560

xiv

22.7.17 Sample Run of Script . . . . . . . . . . . . . . . . . . . 561
22.7.18 Generated Outputs . . . . . . . . . . . . . . . . . . . . 561

23 Computing Pearson Correlation

563
23.1 Pearson Correlation Formula . . . . . . . . . . . . . . . . . . . 564
23.2 Pearson Correlation by Example . . . . . . . . . . . . . . . . . 569
23.3 Data Set for Pearson Correlation . . . . . . . . . . . . . . . . 569
23.4 POJO Solution for Pearson Correlation . . . . . . . . . . . . . 569
23.5 MapReduce Solution for Pearson Correlation . . . . . . . . . . 572
23.5.1 map() for Pearson Correlation . . . . . . . . . . . . . . 573
23.5.2 reduce() for Pearson Correlation . . . . . . . . . . . . . 574
23.5.3 reduce() for Pearson Correlation . . . . . . . . . . . . . 574
23.6 Hadoop Implementation for Pearson Correlation . . . . . . . . 575
23.7 Pearson Correlation using Spark/Hadoop . . . . . . . . . . . . 576
23.7.1 Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
23.7.2 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
23.7.3 Spark Solution . . . . . . . . . . . . . . . . . . . . . . 578
23.7.4 Spark Solution: High-Level Steps . . . . . . . . . . . . 580
23.7.5 STEP-0: import required classes and interfaces
. . . . 582
23.7.6 Method smaller() . . . . . . . . . . . . . . . . . . . . . 582
23.7.7 MutableDouble Class . . . . . . . . . . . . . . . . . . . 583
. . . . . . . . . . . . . . . . . . . . . 584
23.7.8 Method toMap()
23.7.9 Method toListOfString() . . . . . . . . . . . . . . . . . 584
23.7.10 Method readBiosets() . . . . . . . . . . . . . . . . . . . 586
23.7.11 STEP-1: handle input parameters . . . . . . . . . . . . 587
23.7.12 STEP-2: create a Spark context object . . . . . . . . . 587
23.7.13 STEP-3: create list of input ﬁles/biomarkers . . . . . . 588
23.7.14 STEP-4: broadcast ”reference” as global shared object 589
23.7.15 STEP-5: read all biomarkers from HDFS and create

the ﬁrst RDD . . . . . . . . . . . . . . . . . . . . . . . 589
23.7.16 STEP-6: ﬁlter biomarkers by reference . . . . . . . . . 590
23.7.17 STEP-7: create (Gene-ID, (Patient-ID, Gene-Value)

pairs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
23.7.18 STEP-8: group by gene
. . . . . . . . . . . . . . . . . 593
23.7.19 STEP-9: create Cartesian product of all genes . . . . . 593
23.7.20 STEP-10: ﬁlter redundant pairs of genes . . . . . . . . 594
23.7.21 STEP-11: calculate Pearson Correlation and p-value
. 595
23.7.22 Pearson Class . . . . . . . . . . . . . . . . . . . . . . . 597

xv

23.7.23 Test Pearson Class . . . . . . . . . . . . . . . . . . . . 598
23.7.24 Pearson Correlation Using R . . . . . . . . . . . . . . . 599
23.7.25 YARN Script to Run Spark Program . . . . . . . . . . 600
23.8 Spearman Correlation . . . . . . . . . . . . . . . . . . . . . . 600
23.8.1 Spearman Correlation Wrapper Class . . . . . . . . . . 601
23.8.2 Test Spearman Correlation Wrapper Class . . . . . . . 601

24 DNA Base Count

603
24.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603
24.2 FASTA Format . . . . . . . . . . . . . . . . . . . . . . . . . . 604
24.2.1 FASTA Format Example . . . . . . . . . . . . . . . . . 605
24.3 FASTQ Format . . . . . . . . . . . . . . . . . . . . . . . . . . 605
24.3.1 FASTQ Format Example . . . . . . . . . . . . . . . . . 606
24.4 MapReduce Solution: FASTA Format . . . . . . . . . . . . . . 606
24.4.1 Reading FASTA Files . . . . . . . . . . . . . . . . . . . 606
24.4.2 MapReduce Solution: map() . . . . . . . . . . . . . . . 606
24.4.3 MapReduce Solution: reduce() . . . . . . . . . . . . . . 608
24.5 Hadoop Implementation: FASTA Format . . . . . . . . . . . . 609
24.5.1 Hadoop Sample Run . . . . . . . . . . . . . . . . . . . 609
24.5.2 What If 1 . . . . . . . . . . . . . . . . . . . . . . . . . 610
24.5.3 What If 2 . . . . . . . . . . . . . . . . . . . . . . . . . 612
24.6 MapReduce Solution: FASTQ Format . . . . . . . . . . . . . . 615
24.6.1 MapReduce Solution: map() . . . . . . . . . . . . . . . 615
24.6.2 MapReduce Solution: reduce() . . . . . . . . . . . . . . 617
24.7 Hadoop Implementation . . . . . . . . . . . . . . . . . . . . . 617
24.7.1 Sample Run of Hadoop Implementation . . . . . . . . . 618
. . . . . . . . . . . . . . . . . . 619
24.7.2 Reading FASTQ Files

25 RNA-Sequencing

621
25.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621
25.2 Data Size and Format
. . . . . . . . . . . . . . . . . . . . . . 622
25.3 MapReduce Solution . . . . . . . . . . . . . . . . . . . . . . . 622
25.3.1 Input data validation . . . . . . . . . . . . . . . . . . . 622
25.4 MapReduce Algorithms for RNA-Sequencing . . . . . . . . . . 624
25.4.1 STEP-1: MapReduce Tophat mapping . . . . . . . . . 628
25.4.2 STEP-2: MapReduce Calling Cuﬀdiﬀ . . . . . . . . . . 633

xvi

26 Gene Aggregation

636
26.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 636
26.2 Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 637
26.3 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638
26.4 MapReduce Solution . . . . . . . . . . . . . . . . . . . . . . . 638
26.4.1 Mapper: Filter by Individual . . . . . . . . . . . . . . . 640
26.4.2 Reducer: Filter by Individual
. . . . . . . . . . . . . . 642
26.4.3 Mapper: Filter by Average . . . . . . . . . . . . . . . . 642
. . . . . . . . . . . . . . . 643
26.4.4 Reducer: Filter by Average
26.5 Computing Gene Aggregation . . . . . . . . . . . . . . . . . . 644
26.6 Hadoop Implementation . . . . . . . . . . . . . . . . . . . . . 646
26.7 Analysis of Output . . . . . . . . . . . . . . . . . . . . . . . . 650
26.8 Gene Aggregation in Spark . . . . . . . . . . . . . . . . . . . . 654
26.9 Gene Aggregation in Spark: Filter by Individual . . . . . . . . 654
26.9.1 High Level Solution . . . . . . . . . . . . . . . . . . . . 656
26.9.2 High Level Solution . . . . . . . . . . . . . . . . . . . . 656
26.9.3 STEP-1: handle input parameters . . . . . . . . . . . . 657
26.9.4 STEP-2: Create a Spark Context Object . . . . . . . . 657
26.9.5 STEP-3: Broadcast Shard Variables . . . . . . . . . . . 658
26.9.6 STEP-4: Create a JavaRDD For Biosets . . . . . . . . 658
26.9.7 STEP-5: Map Biosets into JavaPairRDD(K,V)
. . . . 659
26.9.8 STEP-6: ﬁlter out the redundant RDD elements . . . . 660
26.9.9 STEP-7: reduce by Key and sum up the frequency count661
26.9.10 STEP-8: prepare the ﬁnal output . . . . . . . . . . . . 661
26.9.11 Utitilty Functions . . . . . . . . . . . . . . . . . . . . . 661
26.9.12 Running Spark on YARN . . . . . . . . . . . . . . . . 663
26.10Gene Aggregation in Spark: Filter by Average . . . . . . . . . 664
. . . . 666
26.10.1 STEP-0: import required classes and interfaces
26.10.2 STEP-1: handle input parameters . . . . . . . . . . . . 666
26.10.3 STEP-2: create a Java Spark context object . . . . . . 667
26.10.4 STEP-3: share global variables in all cluster nodes . . . 668
26.10.5 STEP-4: read all bioset records and create an RDD . . 668
26.10.6 STEP-5: map bioset records and create JavaPairRDD(K,

V)

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669
26.10.7 STEP-6: ﬁlter redundant records created by STEP-5 . 670
26.10.8 STEP-7: group biosets by geneID and referenceType . 670
26.10.9 STEP-8: prepare the ﬁnal desired output . . . . . . . . 671
26.10.10STEP-9: emit the ﬁnal output . . . . . . . . . . . . . . 672

xvii

26.10.11toList() Method . . . . . . . . . . . . . . . . . . . . . . 672
26.10.12readInputFiles() Method . . . . . . . . . . . . . . . . . 673
26.10.13buildPatientsMap() Method . . . . . . . . . . . . . . . 673
26.10.14buildPatientsMap() Method . . . . . . . . . . . . . . . 674
26.10.15Running Spark on YARN . . . . . . . . . . . . . . . . 675

27 Linear Regression

677
27.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677
27.2 Simple Facts about Linear Regression . . . . . . . . . . . . . . 678
27.3 Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . 679
27.4 Problem Statement . . . . . . . . . . . . . . . . . . . . . . . . 680
27.5 Input Data
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 682
27.6 Expected Ouput . . . . . . . . . . . . . . . . . . . . . . . . . . 682
27.7 MapReduce Solution using Apache Commons SimpleRegression683
27.8 Hadoop Implementation using Apache Commons SimpleRe-

gression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686
27.9 MapReduce Solution using R’s Linear Model . . . . . . . . . . 687
27.9.1 MapReduce Solution using R’s Linear Model: Phase 1 689
27.9.2 MapReduce Solution using R’s Linear Model: Phase 2 693
27.9.3 Hadoop Implementation using using R’s Linear Model 695

28 MapReduce and Monoids

696
28.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 696
28.2 Deﬁnition of Monoid . . . . . . . . . . . . . . . . . . . . . . . 698
28.2.1 How to form a Monoid? . . . . . . . . . . . . . . . . . 699
28.3 Monoidic and Non-Monoidic Examples . . . . . . . . . . . . . 700
28.3.1 Subtraction over Set of Integers . . . . . . . . . . . . . 700
28.3.2 Subtraction over Set of Integers . . . . . . . . . . . . . 700
28.3.3 Addition over Set of Integers . . . . . . . . . . . . . . . 700
28.3.4 Multiplication over Set of Integers . . . . . . . . . . . . 701
28.3.5 Mean over Set of Integers
. . . . . . . . . . . . . . . . 701
28.3.6 Non-Commutative Example . . . . . . . . . . . . . . . 701
28.3.7 Median over Set of Integers
. . . . . . . . . . . . . . . 701
28.3.8 Concatenation over Lists . . . . . . . . . . . . . . . . . 702
28.3.9 Union/Intersection over Integers . . . . . . . . . . . . . 702
. . . . . . . . . . . . . . . . . . . 702
28.3.10 Functional Example
28.3.11 Matrix Example . . . . . . . . . . . . . . . . . . . . . . 703
28.4 MapReduce Example: Not a Monoid . . . . . . . . . . . . . . 704

xviii

28.5 MapReduce Example: Monoid . . . . . . . . . . . . . . . . . 705
28.6 Hadoop Implementation of Monodized MapReduce
. . . . . . 707
28.7 Sample Run of Monodized Hadoop/MapReduce . . . . . . . . 708
28.7.1 Create Input File (as a SequenceFile) . . . . . . . . . . 708
28.7.2 Create HDFS Input and Output Directories
. . . . . . 709
28.7.3 Copy Input File to HDFS and Verify . . . . . . . . . . 709
28.7.4 Prepare a shell script to run your MapReduce job . . . 710
28.7.5 Run MapReduce Job . . . . . . . . . . . . . . . . . . . 711
28.7.6 View Hadoop Output . . . . . . . . . . . . . . . . . . . 712
28.8 Conclusion on Using Monoids . . . . . . . . . . . . . . . . . . 712
. . . . . . . . . . . . . . . . . . . . . . 713
28.9 Functors and Monoids

29 The Small Files Problem

29.3 Solution With SmallFilesConsolidator

716
29.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 716
29.2 Solution to The Small Files Problem . . . . . . . . . . . . . . 717
29.2.1 Input Data . . . . . . . . . . . . . . . . . . . . . . . . 720
. . . . . . . . . . . . . 721
29.3.1 Java Source Files . . . . . . . . . . . . . . . . . . . . . 721
29.3.2 Sample Run . . . . . . . . . . . . . . . . . . . . . . . . 722
. . . . . . . . . . . 724
29.4.1 Java Source Files . . . . . . . . . . . . . . . . . . . . . 724
29.4.2 Sample Run . . . . . . . . . . . . . . . . . . . . . . . . 724

29.4 Solution Without SmallFilesConsolidator

30 Huge Cache for MapReduce

726
30.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 726
30.2 Implementation Options . . . . . . . . . . . . . . . . . . . . . 727
30.3 Fromalizing the Cache Problem . . . . . . . . . . . . . . . . . 729
30.4 Elegant Scalable Solution . . . . . . . . . . . . . . . . . . . . . 729
30.5 Implementation of Elegant Scalable Solution . . . . . . . . . . 734
30.5.1 Use of LRU Map . . . . . . . . . . . . . . . . . . . . . 734
30.5.2 Test LRU Map . . . . . . . . . . . . . . . . . . . . . . 735
30.5.3 Use of MapDB . . . . . . . . . . . . . . . . . . . . . . 737
30.5.4 Test of MapDB: put() and get() . . . . . . . . . . . . . 740
30.6 MapReduce Using LRU-Map-Cache . . . . . . . . . . . . . . . 741
30.7 CacheManager Deﬁnition . . . . . . . . . . . . . . . . . . . . . 742
30.7.1 CacheManager Initilization . . . . . . . . . . . . . . . . 743
30.7.2 CacheManager Closing . . . . . . . . . . . . . . . . . . 743
30.7.3 CacheManager Usage . . . . . . . . . . . . . . . . . . . 744

xix

31 Bloom Filter

745
31.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 745
31.2 A Simple Bloom Filter Example . . . . . . . . . . . . . . . . . 748
31.3 Bloom Filter in Guava Library . . . . . . . . . . . . . . . . . . 749
31.4 Using Bloom Filter in MapReduce . . . . . . . . . . . . . . . . 751

Appendices

A Bioset

754
A.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754

B Spark RDDs

756
B.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756
B.2 What is a TupleN? . . . . . . . . . . . . . . . . . . . . . . . . 757
B.3 What is an RDD . . . . . . . . . . . . . . . . . . . . . . . . . 758
B.4 How to Create RDDs . . . . . . . . . . . . . . . . . . . . . . . 759
B.5 Create RDDs by Collection Objects . . . . . . . . . . . . . . . 759
B.6 Collect Elements of an RDD . . . . . . . . . . . . . . . . . . . 760
B.7 Transform RDD into New RDD . . . . . . . . . . . . . . . . . 761
B.8 Create RDDs by Reading Files
. . . . . . . . . . . . . . . . . 761
B.9 Grouping By Key . . . . . . . . . . . . . . . . . . . . . . . . . 762
B.10 Map Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . 763
B.11 Reducing By Key . . . . . . . . . . . . . . . . . . . . . . . . . 764
B.12 Filtering an RDD . . . . . . . . . . . . . . . . . . . . . . . . . 765
B.13 Saving RDD as HDFS Text File . . . . . . . . . . . . . . . . . 766
. . . . . . . . . . . . . . 767
B.14 Saving RDD as HDFS Sequence File
B.15 Reading RDD from HDFS Sequence File . . . . . . . . . . . . 768
B.16 Counting RDD . . . . . . . . . . . . . . . . . . . . . . . . . . 768
B.17 Spark RDD Examples in Scala . . . . . . . . . . . . . . . . . . 769

xx

List of Figures

1
2
3

Simple View of MapReduce Process . . . . . . . . . . . . . . . xxv
Relationship of Spark and Hadoop V1
Relationship of Spark and Hadoop V2

. . . . . . . . . . . . . xxviii
. . . . . . . . . . . . . xxix

1.1 Secondary Sorting Keys
. . . . . . . . . . . . . . . . . . . . .
1.2 Secondary Sorting Data Flow . . . . . . . . . . . . . . . . . .

6
9

2.1 Secondary Sorting Keys
2.2 Secondary Sorting: Composite and Natural Keys

. . . . . . . . . . . . . . . . . . . . . 34
. . . . . . . 39

3.1 Top-10 MapReduce Algorithm: for Unique Keys . . . . . . . . 51
3.2 Top-10 MapReduce Algorithm: for Non-Unique Keys . . . . . 74

4.1 Left Out Join Illustration . . . . . . . . . . . . . . . . . . . . 86
4.2 Left Outer Join Data Flow – Phase I
. . . . . . . . . . . . . . 90
4.3 Left Outer Join Data Flow – Phase II . . . . . . . . . . . . . . 91
4.4 Union Data Flow . . . . . . . . . . . . . . . . . . . . . . . . . 99

6.1 Composite and Natural Keys

. . . . . . . . . . . . . . . . . . 153

7.1 MapReduce Algorithm for Market Basket Analysis
. . . . . . 164
. . . . . . . . . . . . . . . . . . 177
7.2 Generating Association Rules
7.3 Generating Association Rules: MR Phase I . . . . . . . . . . . 179
7.4 Generating Association Rules: MR Phase I . . . . . . . . . . . 180

9.1 Frequently Bought Together . . . . . . . . . . . . . . . . . . . 226
9.2 Friendship Graph . . . . . . . . . . . . . . . . . . . . . . . . . 233

xxi

11.1 Markov Work Flow . . . . . . . . . . . . . . . . . . . . . . . . 289
11.2 Composite Key for Secondary Sorting . . . . . . . . . . . . . . 297

12.1 Raw Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
12.2 Clustered Data . . . . . . . . . . . . . . . . . . . . . . . . . . 310

13.1 kNN Classiﬁcation with 4 Classes {C1, C2, C3, C4} . . . . . . 330
13.2 kNN Implementation in Spark . . . . . . . . . . . . . . . . . . 336

14.1 Naive Bayes: Training Phase . . . . . . . . . . . . . . . . . . . 353
14.2 Naive Bayes: Classiﬁcation . . . . . . . . . . . . . . . . . . . . 354
14.3 Naive Bayes: Training Phase . . . . . . . . . . . . . . . . . . . 374

16.1 Graph Triangles . . . . . . . . . . . . . . . . . . . . . . . . . . 400

17.1 K-mer MapReduce WorkFlow . . . . . . . . . . . . . . . . . . 430

18.1 High-Level View of DNA Sequencing . . . . . . . . . . . . . . 444
18.2 DNA Sequencing Pipeline
. . . . . . . . . . . . . . . . . . . . 445
18.3 FreeMarker Template Engine . . . . . . . . . . . . . . . . . . . 449
18.4 3 Steps MapReduce Solution (Steps 1 and 2) . . . . . . . . . . 450
18.5 3 Steps MapReduce Solution (Step 3) . . . . . . . . . . . . . . 451
18.6 DNA-Sequencing Data Flow . . . . . . . . . . . . . . . . . . . 452
18.7 DNA-Sequencing: Alignment Workﬂow . . . . . . . . . . . . . 453
18.8 DNA-Sequencing: Recalibration . . . . . . . . . . . . . . . . . 462

21.1 Mutation Example . . . . . . . . . . . . . . . . . . . . . . . . 508
21.2 Allelic Frequency WorkFlow . . . . . . . . . . . . . . . . . . . 511
21.3 p-value for Allelic Frequency . . . . . . . . . . . . . . . . . . . 531

22.1 Ttest Spark WorkFlow . . . . . . . . . . . . . . . . . . . . . . 552

23.1 Positive Correlation . . . . . . . . . . . . . . . . . . . . . . . . 565
23.2 Negative Correlation . . . . . . . . . . . . . . . . . . . . . . . 566
23.3 No Correlation . . . . . . . . . . . . . . . . . . . . . . . . . . 570
. . . . . . . . . . . . . . . . 581
23.4 Pearson Correlation of All-vs-All

25.1 RNA-Seq WorkFlow . . . . . . . . . . . . . . . . . . . . . . . 623
. . . . . . . . . . . . . . . . . . . . 626
25.2 RNA-Seq Data Structures

27.1 Linear Regression by R . . . . . . . . . . . . . . . . . . . . . . 681

xxii

27.2 Linear Regression Model

. . . . . . . . . . . . . . . . . . . . . 688

30.1 Hige Cache Partition Data Structure . . . . . . . . . . . . . . 733

xxiii

Preface

0.1

Introduction

With the development of massive search engines (such as Google and Yahoo),
genomic analysis (in DNA-Sequencing, RNA-Sequencing, and biomarker anal-
ysis), and social networks (such as Facebook and Twitter), data volumes
generated and processed cross the peta-bytes scale threshold. To solve these
massive computational requirements, we need eﬃcient, scalable, and parallel
algorithms. One such framework to tackle these problems is the MapReduce
paradigm. The term MapReduce (originated from functional programming)
was introduced by Google in a paper called ”MapReduce: Simpliﬁed Data
Processing on Large Clusters.” Google’s MapReduce [8] implementation is a
proprietary solution and has not been released to the public yet.
A simple view of MapReduce process is illustrated below ( 1).

Input data is partitioned into small chunks (here we have 5 input parti-
tions – called chunks), each chunk is sent to a mapper. Each mapper may
generate any number of (K,V) pairs. In this simple example, all mappers
only generate 2 keys: {K1, K2}. When all mappers are completed, Keys are
sorted, shuﬄed, and grouped and sent to reducers. Finally reducers gener-
ate desired outputs. For this example, we have two reducers identiﬁed by
{K1, K2} keys. Once all mappers are completed, then reducers start their
execution process. Each reducer may create (as an output) any (zero or
more) number of (key, value) pairs.

Simply put, MapReduce is about scalability. Using the MapReduce paradigm,

xxiv

Figure 1: Simple View of MapReduce Process

xxv

you focus on writing two functions: map() – ﬁlter and aggregate data –
and reduce() – reduce, group, and summarize by keys generated by map().
When writing your map() and reduce() functions, your solution has to be
scalable. For example, if you are utilizing any data structure (such as List,
Array, or HashMap), which will not easily ﬁt into the memory of a com-
modity server, then your solution is not scalable. Note that your map()
and reduce() functions will be executing in basic commodity servers, which
might have 16GB or 32GB of RAM at most. Scalability is therefore the key
and heart of MapReduce. If your MapReduce solution does not ”scale out”
well, then you should not call it a MapReduce solution. Here, when we talk
about scalability, we mean ”scaling out” (the term ”scale out” means to add
more commodity nodes to a system). MapReduce is mainly about ”scaling
out” (as opposed to ”scale up” which means to add resources – such as mem-
ory and CPU – to a single node). For example, if DNA-Sequencing1 takes 60
hours with three servers, then by ”scaling out” the solution might produce
the same DNA-Sequencing with 50 similar servers in less than 2 hours.

This book provides essential MapReduce algorithms in the following areas
and chapters are organized accordingly:

1. Basic Design Patterns

2. Data Mining and Machine Learning

3. Bioinformatics, Genomics, and Statistics

4. Optimization Techniques

0.2 Relationship of Spark and Hadoop

In this book, most of the MapReduce algorithms are presented in a cook-
book (compiled, complete and working solutions) format and implemented

1In a nutshell, DNA-Sequencing means reading a patient’s blood sample (as input)
and generating variants (output) for a DNA sample. Formally, ”DNA sequencing is the
process of determining the precise order of nucleotides within a DNA molecule. It includes
any method or technology that is used to determine the order of the four bases – adenine
(A), guanine (G), cytosine (C), and thymine (T) – in a strand of DNA.” (source:http:
//en.wikipedia.org/wiki/DNA_sequencing)

xxvi

in Java/MapReduce/Hadoop2 and or Java/Spark/Hadoop3. Both Hadoop
and Spark frameworks are open-source and enable us to perform huge vol-
ume of computations and data processing in a distributed environments.
These frameworks enable scaling up by providing ”scale out” methodology.
These frameworks can be set up to run intensive computations in MapReduce
paradigm on thousands of servers. Spark’s API has a higer level abstraction
that Hadoop’s API; and because of this, we are able to express Spark solu-
tions in a single Java driver class.

Hadoop and Spark are two diﬀerent MapReduce software frameworks. Spark
programs may run4 with or without Hadoop and Spark may use HDFS5
or other persistent mediums for Input/Output. Relationship of Spark and
Hadoop (V1 and V2) are illustrated below in Figure 2 and Figure 3. This
relationship shows that there are many ways to run MapReduce and Spark
using HDFS. Note that Spark and Hadoop are two diﬀerent software frame-
works and Spark can run with or without Hadoop. In this book, I will use
the following keywords:

• MapReduce refers to a general map/reduce framework paradigm

• MapReduce/Hadoop refers to a speciﬁc implementation of MapReduce

framework using Hadoop

• Spark/Hadoop refers to a speciﬁc implementation of MapReduce frame-

work using Spark:

– Spark can run without Hadoop using ”Spark Cluster”

– Spark can run with Hadoop using Hadoop’s YARN or MapReduce

Hadoop and Spark provide the following rich features for big data processing:

• Reliable: it is fault-tolerant (any node can go down without losing the

result of desired computation)

• Scalable: large clusters of servers

2http://hadoop.apache.org/
3http://spark.apache.org/
4For details on Spark Programming Guide, refer to http://spark.apache.org/docs/

latest/programming-guide.html

5HDFS = Hadoop’s Distributed File System

xxvii

Figure 2: Relationship of Spark and Hadoop V1

xxviii

Figure 3: Relationship of Spark and Hadoop V2

xxix

• Distributed:

input data and processing is distributed (supports big

data from ground up)

• Parallel: computations are executed on cluster of nodes in parallel

Hadoop is designed mainly for batch processing, while with enough mem-
ory/RAM, Spark may be used for near real-time processing. To understand
basic usage of Spark RDDs, you may reference Appendix B.

Using this book, you will learn step-by-step the algorithms and tools you
need to build MapReduce applications with Hadoop. Apache Hadoop is a
revolutionary technology which fundamentally alters the way we approach
everything we do with big data. MapReduce/Hadoop has become the pro-
gramming model of choice for processing large data sets (such as log data,
genome sequences, statistical applications, and social graphs). MapReduce
can be applied for any application that does not require tightly coupled par-
allel processing. Keep in mind that Hadoop is designed for MapReduce batch
processing and is not an ideal solution for real-time processing. Do not ex-
pect to get your answers from in Hadoop in 2 to 5 seconds. The smallest jobs
might take 20+ seconds – Spark6 is a subproject of Hadoop and is well-suited
for real-time processing, but will require more RAM). It is very possible to
run a job (such as Biomarker Analysis or Cox Regression), which processes
200 million records in 25 to 35 seconds by just using a cluster of 100 nodes.
Typically, Hadoop jobs have a latency of 15 to 25 seconds; this depends on
the size and conﬁguration of the Hadoop cluster. Also note that Hadoop is
primarily designed for batch jobs and not for realtime processing.

An implementation of MapReduce (such as Hadoop) runs on a large clus-
ter of commodity machines and is highly scalable. For example, a typical
MapReduce computation processes many peta-bytes or tera-bytes of data
on hundreds/thousands of machines. MapReduce can easily by used by
programmers since MapReduce framework implementation hides messy de-
tails of parallelization, fault-tolerance, data distribution and load balancing.
Instead, a programmer focuses on writing two key functions: map() and
reduce().

The following are some of the major applications of MapReduce/Hadoop:

6Apache Spark is a fast and general engine for large-scale data processing. (source:

http://spark.apache.org/)

xxx

• Query log processing

• Crawling, indexing, and search

• Analytics, Text processing, and sentiment analysis

• Machine learning (such as Markov chains and Bayes algorithm)

• Recommendation systems

• Document Clustering and Classiﬁcation

• Bioinformatics (alignment, re-calibration, germline ingestion, and DNA/RNA-

Sequencing)

• Genome analysis (biomarker analysis, regression algorithms such as

linear and Cox)

0.3 What is MapReduce?

MapReduce [8] is a software framework (or paradigm) for processing large
(giga, tera, or peta bytes) data sets in a parallel and distributed fashion over a
set of machines (typically server computers). There are many ways to express
MapReduce (in this book, our primary focus will be MapReduce/Hadoop and
we will show how to accomplish MapReduce in Hadoop/Spark). MapReduce
is a programming model for expressing distributed computations on massive
amounts of data and an execution framework for large-scale data processing
on clusters of commodity7 servers. The core concept behind MapReduce is
mapping your input data set into a collection of <key, value> pairs, and
then reducing over all pairs with the same key. Even though the overall con-
cept is simple, it is actually quite expressive and powerful when you consider
that:

• Almost all data can be mapped into <key, value> pairs

7”Commodity computing (or Commodity cluster computing) is to use large numbers
of already available computing components for parallel computing to get the greatest
amount of useful computation at a low cost. It is computing done in commodity computers
as opposed to high-cost super microcomputers or boutique computers.” (source:http:
//en.wikipedia.org/wiki/Commodity_server)

xxxi

• Your keys and values may be of any type: strings, integers, FASTQ
(for DNA-Sequencing), and user-deﬁned custom types and, of course,
<key, value> pairs themselves.

MapReduce can be used to scale computations over a set of commodity
servers. How does MapReduce scale over a set of servers? The key to how
MapReduce works is to take input as, conceptually, a list of records (each
single record can be one or more lines of data). Then input records are split
and passed to the many servers in the cluster to be consumed by the map()
function. The result of the map() computation is a list of <key, value>
pairs. Then the reduce() takes each set of values that has the same key and
combines them into a single value (or set of values). So the map() takes a
set of data chunks and produces <key, value> pairs and reduce() merges
output of data generated by map(), so that instead of a set of <key, value>
pair sets, you get your desired result.

Simple Explanation of MapReduce

What is a very simple explanation of MapReduce? Let’s say that we want
to count the number of books in a library, which has 1000 shelves.

• Goal: count the number of books in the library.

• MapReduce solution:

– Map: Hire 1000 workers, each worker counts one shelf.

– Reduce: All workers get together and add up individual counts.

One of the major beneﬁts of MapReduce is its ”shared-nothing” data-
processing platform. This means that all mappers can work independently,
and when mappers complete their job, reducers start to work independently
(no data or critical-region is shared among mappers or reducers – having
a critical-region will slow distributed computing). This ”shared-nothing”
paradigm enables us to write map() and reduce() functions in an easy
manner and improves parallelism eﬀectively and eﬀortlessly. Even though,
MapReduce frameworks (such as Hadoop and Spark) is built on ”shared-
nothing” paradigm, but they do support sharing immutable data structures
among all cluster nodes. In Hadoop, you may pass these values by Hadoop’s

xxxii

Configuration object to mappers and reducers and in Spark, you may share
data structures among mappers and reducers by using Broadcast objects.

0.4 Why use MapReduce?

The simple answer is to ”scale out” by adding more commodity servers (to
scale horizontally or ”scale out” means to add more nodes to a system, such
as adding a new computer to a distributed software application; an example
might be scaling out from one Web server system to ﬁve). MapReduce works
on the promise of ”scale out” (the opposite is ”scale up”, which means that
to add more resources to a single node in a system – this can very in cost
and at some point you will not be able to add more resources due to cost
and software or hardware limits). Many times, there are promising main
memory-based algorithms available for solving data problems, but they lack
scalability as the main memory is a bottleneck. For example, in DNA-Seq
analysis, you might need over 512GB of RAM, which is very costly and not
scalable.

If you need to increase your computational power, you’ll need to distribute
it across more than one machine. For example, to do DNA-Sequecing of
500GB sample data, it will take over 4 days by one server to just do the
alignment phase; using 60 servers with MapReduce can cut this time to less
than two hours. To process large volumes of data, you must be able to
split-up the data in chunks for processing, which are then recombined later.
MapReduce/Hadoop enables you to increase your computational power by
just writing two functions: map() and reduce(). Now for sure we can say
that data analytics have a powerful new tool with the MapReduce paradigm,
which has recently surged in popularity as open source solutions such as
Hadoop.

In a nutshell, MapReduce provides the following beneﬁts:

• Programming model + infrastructure

• Write programs that run on hundreds/thousands of machines

• Automatic parallelization and distribution

• Fault-tolerance (if a server dies, job will be completed)

• Program/job scheduling, status and monitoring

xxxiii

Hadoop is the de facto standard for implementation of MapReduce appli-
cations. Hadoop is comprised of one (or more) master nodes and any number
of slave nodes. Hadoop simpliﬁes distributed applications by saying that ”the
data center is the computer,” and by providing "map" and "reduce" func-
tions (deﬁned by programmer) for application developers/programmers to
utilize data centers.

These two functions can be deﬁned as (in informal presentation of map()
and reduce() functions, the convention [. . .] is used throughout this book to
denote a list):

• map() function: The master node takes the input, partitions it up
into smaller data chunks, and distributes them to worker (slave) nodes.
The worker nodes apply the same transformation function to each data
chunk then pass the answers back to the master node. In MapReduce,
the programmer deﬁnes a mapper with the following signature:

map(): (key1, value1) → [(key2, value2)]

• reduce() function: The master node shuﬄes and clusters the received
results based on unique (key, values) then – through another redistribu-
tion to the workers/slaves – these values are combined through another
type of transformation function. In MapReduce, the programmer de-
ﬁnes a reducer with the following signature:

reduce(): (key2, [value2]) → [(key3, value3)]

Hadoop implements paradigm eﬃciently and is quite simple to learn; it is
a powerful tool for processing large amounts of data in the range of TeraBytes.
But does it provide the right level of abstraction for distributed computing.

0.5 What Is in This Book?

Each chapter of this book presents a problem and solves it by a set of MapRe-
duce algorithms. MapReduce algorithms/solutions are a complete recipe (in-
cluding the MapReduce driver, mapper, combiner, and reducer programs).
You can use the code directly in your projects (although sometimes you may
need to cut and paste the sections you need). This book is not about the-
ory of MapReduce framework, but practical algorithms and examples using
MapReduce/Hadoop on Big Data.

xxxiv

This book provides solid algorithms and guidelines for using MapRe-

duce/Hadoop to solve tough big data problems, such as how to

• Market Basket Analysis for large set of transactions

• Data Mining algorithms (K-menas, KNN, and Naive Bayes)

• Process huge genome data for DNA-seq and RNA-Seq (data from 1000

Genomes project)

• Apply Naive Bayes’ Theorem and Markov Chains for data and market

prediction

• Recommendation algorithms and Pairwise document similarity

• Linear regression, Cox Regression, and Pearson Correlation for a big

set of data

• Allelic-frequency and Mining DNA

• Social network analysis (recommendation systems, counting triangles,

sentiment analysis)

You may cut and paste provided solutions from this book to build your
own MapReduce applications and solutions using Hadoop. All the solutions
have been compiled and tested using Java (JDK6) and Hadoop 1.2.1. This
book is ideal for anyone who knows some Java (can read/write basic Java
programs) and wants to be writing and deploying MapReduce algorithms
using Java/Hadoop. MapReduce [14] has been discussed in detail in an
excellent manner by Jimmy Lin and Chris Dyer [14]. The goal of this book
is to provide concrete MapReduce algorithms and solutions using Hadoop.
Also, this book will not discuss Hadoop in detail; Tom White’s excellent
book [28] addresses detailed Hadoop very well.

This book will not cover how to install Hadoop; I am going to assume you
already have it installed. Also, any Hadoop commands are executed relative
to the directory where Hadoop is installed (the $HADOOP_HOME environment
variable). This book is explicitly about MapReduce/Hadoop algorithms and
programming. We do, for example, discuss APIs, command-line invocations
for running jobs, and provide complete working programs (including driver,
mapper, combiner, and reducer).

xxxv

Why do we use Hadoop? Hadoop, is the industry-standard; it is the very
popular, scalable, aﬀordable (apache license) and ﬂexible solution that helps
address myriad Big Data issues dealing with colossal data, complex in nature
and from multiple sources. However, Hadoop has its own set of limitations
and bottlenecks, such as batch-processing, data security, and so on.

0.6 What Is the Focus of This Book?

The focus of this book is to embrace MapReduce paradigm and provide con-
crete problems that can be solved using MapReduce/Hadoop algorithms. For
each problem presented, we will detail the map(), combine(), and reduce()
functions and ﬁnally provide a complete solution, which has:

• A client (calls the driver with proper input and output parameters)

• A driver (identiﬁes, map() and reduce() functions, and identiﬁes input

and output)

• A mapper class, which implements the map() function

• A combiner class (when possible), which implements the combine()

function. We will discuss when it is possible to use a combiner.

• A reducer class, which implements the reduce() function

The goal of this book is to provide step-by-step instructions for using
Hadoop as a solution for MapReduce algorithms. Another goal is to show
how an output of one MapReduce job can be used as an input to another
MapReduce job (this is called chaining or pipelining MapReduce jobs).

0.7 What are Core Concepts of MapReduce/Hadoop?

• Input/output data are (key, value) pairs.

– Typically, keys are integers, long, string, ...

– Value can be almost any data type: string, integer, long, sentence,

special format data

xxxvi

• Partition data over commodity nodes ﬁlling racks in a data center.

• Software handles failures, restarts, etc. This is an important feature of

Hadoop (called fault-tolerance)

• MapReduce/Hadoop provides ﬁne-grain fault tolerance for large jobs;
failure in the middle of a multi-day/multi-hour execution does not re-
quire restarting the job from scratch.

• Basic examples: Word Count, Inverted index, Log Processing, Data

Mining, Index Creation, Linear Regression, ...

0.8

Is MapReduce for Everything?

The simple answer is no. When we have big data, if we can partition data
and each partition can be processed independently, then its possible to think
about MapReduce algorithms. For example, graph algorithms do not work
very well with MapReduce due to an iterative approach of graph algorithms.
But if you are grouping or aggregating over a lot of data, then MapReduce
paradigm works pretty well. To process graphs using MapReduce, you should
take a look at the Apache Giraph8 project.

When is MapReduce appropriate?

• When you have to handle lots of input data (e.g., aggregate or compute

statistics over big amounts of data)

• When you need to take advantage of parallel and distributed comput-

ing, data storage, and data locality

• When you can do many tasks independently without synchronization

• When you can take advantage of sorting/shuﬄing

• When you need fault tolerance and you can not aﬀord job failures

• When there is lots of input/output data

• When synchronization is not required

8Apache Giraph is an iterative graph processing system built for high scalability.

Source: http://giraph.apache.org/

xxxvii

0.9 What is not MapReduce

• MapReduce is not a programming language, but it is a framework to
develop distributed application programming using Java, Scala, and
other programming languages

• MapReduce’s distributed ﬁle system is not a replacement for a re-
lational database management systems (such as MySQL or Oracle).
Typically, the input to MapReduce is usually plain text ﬁles (a mapper
input record can be one or many lines).

• Online tool: The process starts in batches, might run for hours (DNA-

Sequencing can take 24 hours on a cluster of ﬁve servers)

• A programming language: Any programming language (such as Java,
Scala, Python, PERL, ...) can be used to create Map and Reduce steps
(depending on the framework used)

• MapReduce is not a solution for all software problems

0.10 Who Is This Book For?

This book is for software engineers, software architects, data scientists, and
application developers who know the basics of Java and want to develop
MapReduce algorithms (in Data Mining, Machine Learning, Bioinformatics,
Genomics, and Statistics) and solutions using Hadoop. I also assume you
know the basics of the Java programming language (writing a class, deﬁning
a new class from an existing class, using basic control structures such as
while-loop, if-then-else, and so on).

This book, MapReduce Algorithms, is targeted for the following readers:

1. Data science engineers and professionals/engineers who want to do an-
alytics (classiﬁcation, regression algorithms) on big data. The book
shows basic steps, in the format of a cookbook, on how to apply clas-
siﬁcation and regression algorithms using big data. The book details
map() and reduce() functions by showing how it is applied to real
data. This book shows where to apply basic design patterns in solv-
ing MapReduce problems. These MapReduce algorithms can be easily
adapted across the professions by some minor changes (for example

xxxviii

by changing input format). All solutions have been implemented in
Apache Hadoop so that these can be adapted in real-world situations.

2. Software engineers and software architects who want to design machine
learning algorithms such as Naive Bayes’ and Markov Chain algorithms.
The book shows how build the model and then apply them for a new
data using MapReduce design patterns

3. Software engineers and software architects who want to do data min-
ing (such as K-Means Clustering and K-Nearest-Neighbors) algorithms
using MapReduce. Detailed Examples are given to guide professional
to implement similar algorithms.

4. Data science engineers who want to apply MapReduce algorithms to
clinical and biological data (such as DNA-Seq and RNA-Seq). The
book clearly shows practical algorithms suitable for bioinformaticians
and clinicians. This book presents the most relevant regression/ana-
lytical algorithms used for diﬀerent biological data types. Majority of
these algorithms have been deployed in real-world production systems.

5. Software architects who want to apply the most important optimiza-

tions in a MapReduce/distributed environment.

0.11 What Software Is Used in This Book?

When developing solutions and examples for this book, I used the following
software and programming environments:

Software and Version
Software
Java programming language (JDK7)
Operating system: Linux CentOS
Operating system: Mac OS X
Apache Hadoop
Apache Spark
Eclipse IDE

Version
1.7.0_67
6.3
10.9
2.5.0
1.0.2
luna

xxxix

All programs in this book were tested with JDK7, Hadoop 2.4.1/2.5.0, and
Spark 1.0.2/1.1.0. Examples are given in mixed operating system environ-
ments (Linux and MacBook Pro). For all examples and solutions, I engaged
basic text editors (such as vi, vim, and TextWrangler) and compiled them
using the Java command-line compiler (javac).

0.12 Using Code Examples

This book is here to help you get your job done using MapReduce/Hadoop.
You may use the code in this book in your programs and documentation. You
do not need to contact us for permission. All code and examples presented
in this book are ”open-source”; you may use it in any way you wish.

Book Prerequisites

This book assumes you have a basic understanding of Java and Hadoop’s
HDFS concepts. If you need to become familiar with the Hadoop, then the
following books will oﬀer you the background information you will need:

• Hadoop, The Deﬁnitive Guide by Tom White (publisher: O’Reilly Me-

dia, Inc.)

• Hadoop in Action by Chuck Lam (publisher: Manning Publications)

• Hadoop in Practice by Alex Holmes (publisher: Manning Publications)

0.13 Where NOT to use MapReduce?

There are few scenarios[9] where MapReduce programming model cannot be
employed. If the computation of a value depends on previously computed
values, then MapReduce cannot be used. One good example is the Fibonacci
series where each value is summation of the previous two values. i.e.,

F(k + 2) = F(k + 1) + F(k)

Also, if the data set is small enough to be computed on a single machine,
then it is better to do it as a single reduce(map(data)) operation rather
than going through the entire map reduce process.

xl

When is MapReduce less appropriate?

• synchronization is required to access shared data

• all of your input data ﬁts in memory

• one operation depends on other operations

• basic computations are processor-intensive

0.14 Chapters in This Book?

This book is organized in 5 sections:

Section-1: Basic Design Patterns

• Chapter 1 introduces ”secondary sort” design pattern
• Chapter 2 presents ”secondary sort” design pattern and provide
detail implementation of the algorithm in MapReduce/Hadoop.

• Chapter 3 implements the TOP-10 design pattern in MapReduce/Hadoop

and Spark/Hadoop.

• Chapter 4 presents the ”Left-Join” algorithm and provides its im-

plementation in Mapreduce/Hadoop.

• Chapter 5 implements the ”Order-Inversion” algorithm.
• Chapter 6 presents the ”Moving-Average” algorithm.

Section-2: Data Mining and Machine Learning

• Chapter 7 Market-Basket-Analysis
• Chapter 8 Common-Friends
• Chapter 9 Recommendation Engines using MapReduce
• Chapter 10 Content-based Recommendation
• Chapter 11 Computing Markov Models
• Chapter 12 K-means Clustering
• Chapter 13 KNN
• Chapter 14 Naive Bayes

xli

• Chapter 15 Sentiment Analysis
• Chapter 16 Counting Triangles in Social Networks

Section-3: Bioinformatics, Genomics, and Statistics

• Chapter 17 K-mer Counting
• Chapter 18 DNA-Sequencing
• Chapter 19 Cox Regression
• Chapter 20 Cochran-Armitage Test for Trend
• Chapter 21 Allelic Frequency
• Chapter 22 The T-Test
• Chapter 23 Computing Pearson Correlation
• Chapter 24 DNA Base Count
• Chapter 25 RNA-Sequencing
• Chapter 26 Gene Aggregation
• Chapter 27 Linear Regression

Section-4: Optimization Techniques

• Chapter 28 MapReduce and Monoids
• Chapter 29 The Small Files Problem
• Chapter 30 Huge Cache for MapReduce
• Chapter 31 Bloom Filter

Section-5: Appendices

• Appendix A: Biosets
• Appendix B: Spark RDDs

0.15 Online Resources

There are two web sites that accompanies this book:

xlii

• https://github.com/mahmoudparsian/data-algorithms-book/

In this GitHub site, you will ﬁnd links to the source code (organized by
chapters), some shell scripts, sample input ﬁles for testing, and some
extra content that isnt in the book, including a couple of chapters.

• http://mapreduce4hackers.com/

In this site, you will ﬁnd links to the extra source ﬁles (not mentioned
in book) plus some extra content that isnt in the book. Expect more
coverage of MapReduce/Hadoop/Spark topics as time progresses.

0.16 Comments and Questions for This Book?

I am always interested in your feedback and comments regarding the prob-
lems and solutions described in this book. Please e-mail comments and ques-
tions for this book to mahmoud.parsian@yahoo.com. You can also ﬁnd me
at http://www.mapreduce4hackers.com.

Mahmoud Parsian
Sunnyvale, California
September 12, 2014

xliii

Chapter 1

Secondary Sort: Introduction

1.1 What is a Secondary Sort Problem?

The goal of this chapter is to implement ”secondary sort” design-pattern by
MapReduce/Hadoop and Spark/Hadoop. In software design and program-
ming, a design pattern is a reusable algorithm (typically, a design pattern is
not presented in a speciﬁc programming language – but can be implemented
by many programming languages) to a commonly occurring problem.

MapReduce framework automatically sorts the keys generated by mappers.
This means that, before starting reducers all intermediate (key, value) pairs
generated by mappers must be sorted by key (and not by value). Values
passed to each reducer are not sorted at all and they can be in any order.
What we know is that MapReduce sorts input to reducers by key and values
may be arbitrarily ordered. What if we want to sort reducer’s values also?
MapReduce/Hadoop and Spark/Hadoop do not sort values for a reducer.
For example, for some applications (such as time series data), you want your
data to be sorted. Secondary Sort design pattern enable us to sort redcer’s
values.

First we focus on MapReduce/Hadoop solution. Let’s look at the MapReduce
paradigm and then explain the concept of the Secondary Sort:

map(key1, value1) → list(key2, value2)
reduce(key2, list(value2)) → list(key3, value3)

1

First, the map() function receives a key-value pair input, (key1, value1).
Then it outputs another (any number of them) key-value pair, (key2, value2).
Second, the reduce() function receives as input another key-value pair,
(key2, list(value2)), and outputs (any number of them) (key3, value3).

Now consider the following key-value pair (key2, list(value2)) as an

input for a reducer:

list(value2) = (V1, V2, ..., Vn)

where there in no ordering between reducer values (V1, V2, ..., Vn).
The goal of the ”secondary sort” is to give some ordering for the values
received by a reducer. So, once we apply/inject ”secondary sort” to our
MapReduce paradigm, then we will have:

list(value2) = (S1, S2, ..., Sn)

where

• S1 < S2 < ... < Sn (ascending order) or
• S1 > S2 > ... > Sn (descending order)
• Si ∈ {V1, V2, ..., Vn}

We will show by a concrete example how to achieve secondary sorting
in ascending or descending order. What is ”secondary sorting” problem?
”Secondary Sorting Problem” is the problem of sorting values associated
with a key in the reduce phase. Sometimes, this is called ”value-to-key
conversion.” The ”secondary sorting” technique will enable us to sort the
values (in ascending or descending order) passed to each reducer.

Apache Hadoop and Spark, which are popular MapReduce paradigms, do
not sort the values passed to reducers (values can be in any arbitrary order).
On the otherhand, it is believed that the Google’s MapReduce implementa-
tion provides an option for sorting the values passed to each reducer. Note,
that since we do not have access to Google’s MapReduce implementation,
we just rely on Google’s documentation for this claim.

Consider the example of temperature data from a scientiﬁc experiment.
A dump of the temperature data might look something like the following
(columns are year, month, day, and the temperature for that day).

2

2012, 01, 01, 5
2012, 01, 02, 45
2012, 01, 03, 35
2012, 01, 04, 10
...
2001, 11, 01, 46
2001, 11, 02, 47
2001, 11, 03, 48
2001, 11, 04, 40
...
2005, 08, 20, 50
2005, 08, 21, 52
2005, 08, 22, 38
2005, 08, 23, 70

Suppose we want to output the temperature for every ”Year-Month” with
temperature values sorted (ascending). Essentially, we want the reducers
values iterator to be sorted. Therefore, we want to generate something like
this output (the ﬁrst column is Year-Month and the second column is the
sorted temperatures):

5, 10, 35, 45, ...
2012-01:
2001-11: 40, 46, 47, 48, ...
2005-08: 38, 50, 52, 70, ...

1.2 Solutions to Secondary Sort Problem

There are at least two possible approaches for sorting the reducers values.

1. The ﬁrst approach involves having the reducer read and buﬀer all of
the values for a given key (in an array data structure, for example)
Then do an in-reducer sort on the values. This approach will not
scale: since the reducer will be receiving all values for a given key,
this approach could possibly cause the reducer to run out of mem-
ory (java.lang.OutOfMemoryError). This approch can work well if
the the number of values is small enough, which will not cause out-of-
memory error.

3

2. The second approach involves using MapReduce framework for sort-
ing the reducers values (does not require in-reducer sorting of values
passed to the reducer). This approach involves ”creating a compos-
ite key by adding a part of, or the entire value to, the natural key
to achieve your sorting objectives.” For the details on this approach,
see javacodegeeks1. The second approach is scaleable and you will
not see out-of-memory errors. Here, we basically oﬄoad the sorting to
the MapReduce framework (sorting is a paramount feature of MapRe-
duce/Hadoop framework)..

This is the summary of second approach:

(a) Use ”Value-to-Key Conversion” design pattern:

form compos-
ite intermediate key, (k, v1), where v1 is the secondary key.
Here, k is called a natural key. How to inject value (i.e., v1
into a reducer key? Just create a composite key (for details,
see the DateTemperaturePair class). In our example, v1 is the
temperature data.

(b) Let MapReduce execution framework do the sorting (rather than
sorting in memory, let the framework do the sorting by using the
cluster nodes)

(c) Preserve state across multiple (key, value) pairs to handle pro-
cessing; this can be achieved by having proper mapper output
partitioners (for example, we partition mapper’s output by the
natural key)

Implementation details

To implement the ”secondary sort” feature, we do need additional plug-in
Java classes. We have to tell to MapReduce/Hadoop framework:

1. how to sort reducer keys

2. how to partition keys passed to reducers (custom partitioner)

3. how to group data reached to reducers

1http://www.javacodegeeks.com/2013/01/mapreduce-algorithms-secondary-sorting.

html

4

1.2.1 Sort Order of Intermediate Keys

To accomplish ”secondary sorting,” we do need to take control of the ”sort
order of intermediate keys” and the control order in which reducers process
keys. First, we inject value (temperature data) to the composite key and
then provide control on sort order of intermediate keys. The relationships of
natural key, composite key, and (key, value) pairs are depicted below:

In this section, we will implement the ”secondary sort” (or so called ”value
to key”) approach. What value should we add to the natural key? The answer
is the temperature data ﬁeld (because we want the reducer’s values to be
sorted by temperature). So, we have to mention how DateTemperaturePair
objects are sorted by the compareTo() method. You need to deﬁne a proper
data structure for holding your key and value, while also providing the sort
order of intermediate keys. In Hadoop, to persist custom data types (such as
DateTemperaturePair), they have to implement the Writable interface; and
if we are going to compare custom data types, then they have to implement
an additional interface called WritableComparable.

Listing 1.1: DateTemperaturePair Class

1 public class DateTemperaturePair
2

implements Writable, WritableComparable<DateTemperaturePair> {

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22
23 }

private Text yearMonth = new Text(); // natural key
private Text day = new Text();
private IntWritable temperature = new IntWritable(); // secondary key

...

@Override
/**
* This comparator controls the sort order of the keys.
*/
public int compareTo(DateTemperaturePair pair) {

int compareValue = this.yearMonth.compareTo(pair.getYearMonth());
if (compareValue == 0) {

compareValue = temperature.compareTo(pair.getTemperature());

}
//return compareValue;
return -1*compareValue;

// sort ascending
// sort descending

}
...

5

Figure 1.1: Secondary Sorting Keys

6

1.2.1.1 Partition code

In a nutshell, partitioner decides which mapper output goes to which reduer
based on mapper output key. We do need a plug-in partitioner to control
which reducer processes which keys. We do need to write a custom partitioner
to ensure that all the data with same key (the natural key not including
the composite key with the value – value is the temperature data ﬁeld)
is sent to the same reducer and a custom Comparator so that the natural
key (composition of year and month) groups the data once it arrives at the
reducer.

Listing 1.2: DateTemperaturePartitioner Class

1 import org.apache.hadoop.io.Text;
2 import org.apache.hadoop.mapreduce.Partitioner;
3
4 public class DateTemperaturePartitioner
5

extends Partitioner<DateTemperaturePair, Text> {

6

7

8

9

10

11

12

@Override
public int getPartition(DateTemperaturePair pair,

Text text,
int numberOfPartitions) {
// make sure that partitions are non-negative
return Math.abs(pair.getYearMonth().hashCode() % numberOfPartitions);

}

13
14 }

How do we inject the partitioner code? Hadoop provides a plug-in archi-
tecture for custom code. This is how we do it inside the driver class (which
submits the MapReduce job to Hadoop):

job.setPartitionerClass(TemperaturePartitioner.class);

1.2.1.2 Grouping Comparator

We deﬁne the comparator (DateTemperatureGroupingComparator class )
that controls which keys are grouped together for a single call to Reducer.reduce()
function.

Listing 1.3: DateTemperatureGroupingComparator Class

7

1 import org.apache.hadoop.io.WritableComparable;
2 import org.apache.hadoop.io.WritableComparator;
3
4 public class DateTemperatureGroupingComparator
5

extends WritableComparator {

6

7

8

9

10

11

12

13

14

15

16

17

18

19

public DateTemperatureGroupingComparator() {

super(DateTemperaturePair.class, true);

}

@Override
/**
* This comparator controls which keys are grouped
* together into a single call to the reduce method
*/
public int compare(WritableComparable wc1, WritableComparable wc2) {

DateTemperaturePair pair = (DateTemperaturePair) wc1;
DateTemperaturePair pair2 = (DateTemperaturePair) wc2;
return pair.getYearMonth().compareTo(pair2.getYearMonth());

}

20
21 }

How do we inject the ”grouping comparator” code? Hadoop provides a
plug-in architecture for ”grouping comparator” code. This is how we do it
inside the driver class (which submits the MapReduce job to Hadoop):

job.setGroupingComparatorClass(YearMonthGroupingComparator.class);

1.3 Data Flow Using Plug-in Classes

To understand the map(), reduce(), and custom plug-in classes, the data ﬂow
for portion of input is illustrated below.

The mappers create (K,V) pairs, where K is a composite key of (year,month,temperature)
and V is a temperature. Note that (year,month) part of the composite key is
called a natural key. The partitioner plug-in class enables us to send all natu-
ral keys to the same reducer and ”grouping comparator” plug-in class enable
temperature’s to arrive sorted to reducers. The ”secondary sort” design pat-
tern uses Mapreduce’s framework for sorting the reducer’s values rather than
collecting all and then sort in memory. The ”secondary sort” design pattern
enale us to ”scale out” no matter how many reducer values we want to sort.

8

Figure 1.2: Secondary Sorting Data Flow

9

1.4 Mapreduce/Hadoop Solution

This section provides a complete MapReduce implementation of ”secondary
sort” problem by using Hadoop framework.

1.4.1

Input

Input will be a set of ﬁles, which will have the following format:

Format:

<year><,><month><,><day><,><temperature>

Example-1:

2012, 01, 01, 35

Example-2:

2011, 12, 23, -4

1.4.2 Expected Output

Input will be a set of ﬁles, which will have the following format:

Format:

<year>-<month>: <temperature1>,<temperature2>, ...

Example:

2012-01:
5, 10, 35, 45, ...
2001-11: 40, 46, 47, 48, ...
2005-08: 38, 50, 52, 70, ...

1.4.3 map() function

The map() function parses and tokenizes the input and then injects the value
(value of temperature) into the reducer key.

10

Listing 1.4: map() for Secondary Sorting

* @param key is generated by Hadoop (ignored here)
* @param value has this format: "YYYY,MM,DD,temperature"
*/

1 /**
2

3

4
5 map(key, value) {
6

String[] tokens = value.split(",");
// YYYY = tokens[0]
// MM = tokens[1]
// DD = tokens[2]
// temperature = tokens[3]
String yearMonth = tokens[0] + tokens[1];
String day = tokens[2];
int temperature = Integer.parseInt(tokens[3]);
// prepare reducer key
DateTemperaturePair reducerKey = new DateTemperaturePair();
reducerKey.setYearMonth(yearMonth);
reducerKey.setDay(day);
reducerKey.setTemperature(temperature); // inject value into key
// send it to reducer
emit(reducerKey, temperature);

7

8

9

10

11

12

13

14

15

16

17

18

19

20
21 }

1.4.4

reduce() function

Listing 1.5: reduce() for Secondary Sorting

1 /**
2

3

7

8

9

10

11
12 }

* @param key is a DateTemperaturePair object
* @param value is a list of temperature
*/

4
5 reduce(key, value) {
6

StringBuilder sortedTemperatureList = new StringBuilder();
for (Integer temperature : value) {

sortedTemperatureList.append(temperature);
sortedTemperatureList.append(",");

}
emit(key, sortedTemperatureList);

1.4.5 Hadoop Implementation

The following classes are used to solve the problem.

11

Class Name
SecondarySortDriver.java

SecondarySortMapper.java
SecondarySortReducer.java
DateTemperatureGroupingComparator.java Deﬁnes how keys will be grouped together
DateTemperaturePair.java

Class Description
The driver class, deﬁnes input/output
and registers plug-in classes.
Deﬁnes the map() function
Deﬁnes the reduce() function

Deﬁnes pair of date and temperature
as a Java object
Deﬁnes custom partitioner

DateTemperaturePartitioner.java

How is the value is injected into the key? The ﬁrst comparator (DateTemperaturePair.compareTo()

method) controls the sort order of the keys and the second comparator
(DateTemperatureGroupingComparator.compare() method) controls which
keys are grouped together into a single call to the reduce method. The com-
bination of these two allows you to set up jobs that act like you’ve deﬁned
an order of the values.

The SecondarySortDriver is the driver class, which registers the custom

plug-in classes (DateTemperaturePartitioner and DateTemperatureGroupingComparator
classes) with the Mapreduce/Hadoop framework. This class is presentd be-
low:

Listing 1.6: SecondarySortDriver Class

1 public class SecondarySortDriver
2

extends Configured implements Tool {

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

public int run(String[] args) throws Exception {

Configuration conf = getConf();
Job job = new Job(conf);
job.setJarByClass(SecondarySortDriver.class);
job.setJobName("SecondarySortDriver");

// args[0] = input directory
// args[1] = output directory
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));

job.setOutputKeyClass(TemperaturePair.class);
job.setOutputValueClass(NullWritable.class);

job.setMapperClass(SecondarySortingTemperatureMapper.class);
job.setReducerClass(SecondarySortingTemperatureReducer.class);
job.setPartitionerClass(TemperaturePartitioner.class);
job.setGroupingComparatorClass(YearMonthGroupingComparator.class);

boolean status = job.waitForCompletion(true);

12

theLogger.info("run(): status="+status);
return status ? 0 : 1;

}

/**
* The main driver for word count map/reduce program.
* Invoke this method to submit the map/reduce job.
* @throws Exception When there is communication problems with the job tracker.
*/
public static void main(String[] args) throws Exception {

// Make sure there are exactly 2 parameters
if (args.length != 2) {

throw new IllegalArgumentException("Usage: SecondarySortDriver <input-dir> <output-dir>");

}

//String inputDir = args[0];
//String outputDir = args[1];
int returnStatus = ToolRunner.run(new SecondarySortDriver(), args);
System.exit(returnStatus);

}

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43
44 }

1.4.6 Sample Run of Hadoop Implementation

1.4.6.1

Input

# cat sample_input.txt
2000,12,04, 10
2000,11,01,20
2000,12,02,-20
2000,11,07,30
2000,11,24,-40
2012,12,21,30
2012,12,22,-20
2012,12,23,60
2012,12,24,70
2012,12,25,10
2013,01,22,80
2013,01,23,90
2013,01,24,70
2013,01,20,-10

13

1

2

3

4

5

6

7

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

1.4.6.2 HDFS Input

# hadoop fs -mkdir /secondary_sort
# hadoop fs -mkdir /secondary_sort/input
# hadoop fs -mkdir /secondary_sort/output
# hadoop fs -put sample_input.txt /secondary_sort/input/
# hadoop fs -ls /secondary_sort/input/
Found 1 items
-rw-r--r--

1 mahmoud staff

128 2013-02-26 15:14 /secondary_sort/input/sample_input.txt

1.4.7 Sample Run

1.4.7.1 The Script

# cat run.sh
#!/bin/bash

export HADOOP_HOME=/Users/mahmoud/zmp/zs/hadoop
export HADOOP_HOME_WARN_SUPPRESS=true

export JAVA_HOME=‘/usr/libexec/java_home‘
echo "JAVA_HOME=$JAVA_HOME"

PATH=.:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
PATH=$PATH:$HADOOP_HOME/bin
PATH=$PATH:$JAVA_HOME/bin
export PATH

CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-ant-1.0.3.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-core-1.0.3.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-examples-1.0.3.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-test-1.0.3.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-tools-1.0.3.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/lib/log4j-1.2.15.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/lib/commons-cli-1.2.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/lib/commons-logging-1.1.1.jar

export JAR=/Users/mahmoud/zmp/map_reduce_book/hadooptests/secondary_sort/secondary_sort.jar
export CLASSPATH=$CLASSPATH:$JAR
export HADOOP_CLASSPATH=$CLASSPATH

javac *.java
jar cvf $JAR *.class

$HADOOP_HOME/bin/hadoop fs -rmr /secondary_sort/output
$ INPUT=/secondary_sort/input
$ OUTPUT=/secondary_sort/output
$HADOOP_HOME/bin/hadoop jar

$JAR SecondarySortDriver $INPUT $OUTPUT

14

1.4.7.2 Log of Sample Run

map 0% reduce 0%
map 100% reduce 0%
map 100% reduce 10%

# ./run.sh
...
Deleted hdfs://localhost:9000/secondary_sort/output
13/02/27 19:39:54 INFO input.FileInputFormat: Total input paths to process : 1
...
13/02/27 19:39:54 INFO mapred.JobClient: Running job: job_201302271939_0001
13/02/27 19:39:55 INFO mapred.JobClient:
13/02/27 19:40:10 INFO mapred.JobClient:
13/02/27 19:40:22 INFO mapred.JobClient:
...
13/02/27 19:41:10 INFO mapred.JobClient:
13/02/27 19:41:16 INFO mapred.JobClient:
13/02/27 19:41:21 INFO mapred.JobClient: Job complete: job_201302271939_0001
...
13/02/27 19:41:21 INFO mapred.JobClient:
...
13/02/27 19:41:21 INFO mapred.JobClient:
13/02/27 19:41:21 INFO mapred.JobClient:
13/02/27 19:41:21 INFO mapred.JobClient:
13/02/27 19:41:21 INFO mapred.JobClient:
13/02/27 19:41:21 INFO mapred.JobClient:
13/02/27 19:41:21 INFO SecondarySortDriver: run(): status=true
13/02/27 19:41:21 INFO SecondarySortDriver: returnStatus=0

Reduce input records=14
Reduce input groups=4
Combine output records=0
Reduce output records=4
Map output records=14

map 100% reduce 90%
map 100% reduce 100%

Map-Reduce Framework

1.4.7.3

Inspecting Output

# hadoop fs -cat /secondary_sort/output/p*
2013-01 90,80,70,-10
2000-12 10,-20
2000-11 30,20,-40
2012-12 70,60,30,10,-20

1.5 What If Sorting Ascending or Descend-

ing

You can easily control the sorting order of the values (Ascending or Descend-
ing) by the DateTemperaturePair.compareTo() method. This is how you
can do it:

public int compareTo(DateTemperaturePair pair) {

int compareValue = this.yearMonth.compareTo(pair.getYearMonth());

15

if (compareValue == 0) {

compareValue = temperature.compareTo(pair.getTemperature());

}
//return compareValue;
return -1*compareValue;

// sort ascending
// sort descending

}

1.6 Spark Solution To Secondary Sorting

To solve a ”secondary sorting” in Spark2, we have at least two options and
we will present a solution to each option.

• OPTION-1: read and buﬀer all of the values for a given key in an array
of list data structure and then do an in-reducer sort on the values. This
solution works if you have small set of values (which will ﬁt in memory)
per reducer key.

• OPTION-2: use Spark framework for sorting the reducers values (does
not require in-reducer sorting of values passed to the reducer). This
approach involves ”creating a composite key by adding a part of, or
the entire value to, the natural key to achieve your sorting objectives.”
This option always scales (because you are not limited by memory of
a commodity server).

1.6.1 Time-Series as Input

To demostrate ”secondary sorting”, let’s use a time-series data:

name time value
2
2
1
1
3

9
5
3
7
1

x
y
x
y
y

2Apache Spark is a fast and general engine for large-scale data processing. (source:

http://spark.apache.org/)

16

x
z
z
z
z
p
p
p
p
p

3
1
2
3
4
2
4
1
6
7

6
4
8
7
0
6
7
9
0
3

1.6.2 Expected Output

Our expected output is illustrated below. As you observe, the values of
reducers are grouped by ”name” and sorted by ”time”.

t1
name
x => [3,
y => [7,
z => [4,
p => [9,

t2
9,
5,
8,
6,

t3
6]
1]
7,
7,

t4

t5 ...

0]
0,

3]

1.6.3 Option-1: Secondary Sorting in Memory

Since Spark has a very powerfull and high-level API, we will present the
entire solution in a single Java class. Spark API is built by the basic ab-
straction concept of RDD (Resilient Distributed Dataset). To fully utilize
Spark’s API, we have to understand RDD’s. An RDD<T> (or type T) ob-
ject represents an immutable, partitioned collection of elements (or type T)
that can be operated on in parallel. The RDD<T> class contains the ba-
sic MapReduce operations available on all RDDs, such as map, filter, and
persist. While JavaPairRDD<K,V> class contains the basic MapReduce
operations such as mapToPair, flatMapToPair, and groupByKey. In addi-
tion, Spark’s PairRDDFunctions contains operations available only on RDDs
of (key, value) pairs, such as reduce, groupByKey and join. For details on

17

RDDs, see Spark’s API3. Therefore, JavaRDD<T> is a list of objects of type T
and JavaPairRDD<K,V> is a list of objects of type Tuple2<K,V> (each tuple
represents a (key,value) pair).

The Spark-based algorithm is listed below: even though we have 9 steps, but
most of them are trivial and some are provided for debugging purposes only.

STEP-0 : Import required Java/Spark classes. The main Java classes for
MapReduce are given in the org.apache.spark.api.java package.
This package includes the following classes and interfaces:

• JavaRDDLike (interface)
• JavaDoubleRDD
• JavaPairRDD
• JavaRDD
• JavaSparkContext
• StorageLevels

STEP-1 : Pass Sark master and input data as arguments and validate.

Spark master URL is speciﬁed as: spark://<spark-master-server>:7077.

STEP-2 : Connect to the Sark master by creating JavaSparkContext

object, which is a factory class for creating new RDDs.

STEP-3 : Use the context object (created in STEP-2) and create an RDD
for input ﬁle, the resulting RDD will RDD will be JavaRDD<String>.
Each element of this RDD will be a record of time series data: <name><,><time><,><value>.

STEP-4 : Next we want to create (key, value) pairs from JavaRDD¡String¿
where key is the name and value is a pair of (time, value). The resulting
RDD will be JavaPairRDD<String, Tuple2<Integer, Integer>>.

STEP-5 : To validate STEP-4, we collect all values from JavaPairRDD<>

and print it.

3http://spark.apache.org/docs/1.0.0/api/java/org/apache/spark/rdd/RDD.

html

18

STEP-6 : We group JavaPairRDD<> elements by the key (name). To ac-
complish this, we use the groupByKey() method. The result will be
the RDD:

JavaPairRDD<String, Iterable<Tuple2<Integer, Integer>>>

Note that the resulting list (Iterable<Tuple2<Integer, Integer>>)
is unsorted.

STEP-7 : To validate STEP-6, we collect all values from JavaPairRDD<String,

Iterable<Tuple2<Integer, Integer>>> and print it.

STEP-8 : Sort the reducer’s values and this will give us the ﬁnal output.
This is accomplished by writing a custom mapValues() method. We
just sort the values (key remains the same).

STEP-9 : To validate the ﬁnal result, we collect all values from sorted

JavaPairRDD<> and print it.

A solution for Option-1 is implemented by a single class: SecondarySorting.

All steps (STEP-0 – STEP-9) are listed inside the class deﬁnition, which will
be presented in the following sections. Typically, a Spark application pro-
gram consists of a driver program that runs the user’s main() function and
executes various parallel operations on a cluster. Parallel operations will be
achieved by using an extensive use of RDDs. In a nutshell, and RDD is a
fundamental Spark abstraction of data (an immutable data structure) and is
a collection of elements partitioned across the nodes of the cluster that can
be operated on in parallel.

Listing 1.7: SecondarySort Class Overall Structure

1 // STEP-0: import required Java/Spark classes.
2 public class SecondarySort {
3

public static void main(String[] args) throws Exception {

4

5

6

7

8

9

10

11

// STEP-1: read input parameters and validate them
// STEP-2: Connect to the Sark master by creating JavaSparkContext object
// STEP-3: Use ctx to create JavaRDD<String>
// STEP-4: create (key, value) pairs from JavaRDD<String> where
//
// STEP-5: validate STEP-4, we collect all values from JavaPairRDD<> and print it.
// STEP-6: We group JavaPairRDD<> elements by the key ({name}).
// STEP-7: validate STEP-6, we collect all values from JavaPairRDD<> and print it.

key is the {name} and value is a pair of (time, value).

19

// STEP-8: Sort the reducer’s values and this will give us the final output.
// STEP-9: validate STEP-8, we collect all values from JavaPairRDD<> and print it.
System.exit(0);

12

13

14

}

15
16 }

1.6.3.1 STEP-0: Import Required Classes

The main Spark package for Java API is org.apache.spark.api.java, which
includes JavaRDD, JavaPairRDD, and JavaSparkContext classes. The JavaSparkContext
is a factory class for creating new RDDs (such as JavaRDD and JavaPairRDD).

Listing 1.8: STEP-0: Import Required Classes

1 // STEP-0: import required Java/Spark classes.
2 import scala.Tuple2;
3 import org.apache.spark.api.java.JavaRDD;
4 import org.apache.spark.api.java.JavaPairRDD;
5 import org.apache.spark.api.java.JavaSparkContext;
6 import org.apache.spark.api.java.function.Function;
7 import org.apache.spark.api.java.function.Function2;
8 import org.apache.spark.api.java.function.PairFunction;
9
10 import java.util.List;
11 import java.util.ArrayList;
12 import java.util.Map;
13 import java.util.Collections;
14 import java.util.Comparator;

1.6.3.2 STEP-1: Read Input Parameters

This step reads a spark master URL and HDFS input ﬁle. The examples for
this step can be:

• Spark master URL: spark://<spark-master-node>:7077

• HDFS ﬁle: /dir1/dir2/myfile.txt

Listing 1.9: STEP-1: Read Input Parameters

1

2

3

4

5

// STEP-1: read input parameters and validate them
if (args.length < 2) {

System.err.println("Usage: Top10 <master> <file>");
System.exit(1);

}

20

6

7

8

1

2

3

4

5

6

System.out.println("args[0]: <master>="+args[0]);
System.out.println("args[1]: <file>="+args[1]);

1.6.3.3 STEP-2: Connect to the Sark Master

To do some work with RDDs, ﬁrst you need to create a JavaSparkContext
object, which is a factory class for creating JavaRDD and JavaPairRDD ob-
jects. It is also possible to create a JavaSparkContext object by injecting
SparkConf object to JavaSparkContext’s class constructor. This approach
is useful when you read your cluster conﬁgurations from an XML ﬁle. In a
nutshell, JavaSparkContext object has the following responsibilities:

• Initializes the application driver

• Registers the application driver to the cluster manager (if you are using
Spark cluster, then this will be Spark master, and if you are using
YARN, then that will be YARN’s resource manager)

• Obtain a list of executors for executing your application driver

Listing 1.10: STEP-2: Connect to the Sark Master

// STEP-2: Connect to the Sark master by creating JavaSparkContext object
final JavaSparkContext ctx = new JavaSparkContext(

args[0],
"Top10",
System.getenv("SPARK_HOME"),
System.getenv("SPARK_EXAMPLES_JAR"));

1.6.3.4 STEP-3: Use JavaSparkContext to create JavaRDD

This step reads an HDFS ﬁle and creates a JavaRDD<String> (represents a
set of records – each record is a String object). By deﬁnition, Spark’s RDDs
are immutable (cannot be altered or modiﬁed). Note that Spark’s RDDs are
the basic abstraction for parallel execution.

Listing 1.11: STEP-3: Create JavaRDD

21

1

2

3

// STEP-3: Use ctx to create JavaRDD<String>
//
input record format: <name><,><time><,><value>
JavaRDD<String> lines = ctx.textFile(args[1], 1);

1.6.3.5 STEP-4: Create (key, value) pairs from JavaRDD

This step implements a mapper. Each record (from JavaRDD<String> as
<name><,><time><,><value>) is converted to a (key, value) where key is a
name and value is a Tuple2(time, value).

Listing 1.12: STEP-4: create (key, value) pairs from JavaRDD

// STEP-4: create (key, value) pairs from JavaRDD<String> where
// key is the {name} and value is a pair of (time, value).
// The resulting RDD will be JavaPairRDD<String, Tuple2<Integer, Integer>>.
// convert each record into Tuple2(name, time, value)
// PairFunction<T, K, V>
//
//
//
JavaPairRDD<String, Tuple2<Integer, Integer>> pairs =

T => Tuple2(K, V) where T is input (as String),
K=String
V=Tuple2<Integer, Integer>

//

K
lines.map(new PairFunction<String, String, Tuple2<Integer, Integer>>() {

V

T

public Tuple2<String, Tuple2<Integer, Integer>> call(String s) {

String[] tokens = s.split(","); // x,2,5
System.out.println(tokens[0] + "," + tokens[1] + "," + tokens[2]);
Integer time = new Integer(tokens[1]);
Integer value = new Integer(tokens[2]);
Tuple2<Integer, Integer> timevalue = new Tuple2<Integer, Integer>(time, value);
return new Tuple2<String, Tuple2<Integer, Integer>>(tokens[0], timevalue);

}
});

1.6.3.6 STEP-5: Validate STEP-4

To debug and validate your steps in Spark, you may use JavaRDD.collect()
and JavaPairRDD.collect().

Listing 1.13: STEP-5: Validate STEP-4

// STEP-5: validate STEP-4, we collect all values from JavaPairRDD<> and print it.
List<Tuple2<String, Tuple2<Integer, Integer>>> output = pairs.collect();
for (Tuple2 t : output) {

Tuple2<Integer, Integer> timevalue = (Tuple2<Integer, Integer>) t._2;
System.out.println(t._1 + "," + timevalue._1 + "," + timevalue._1);

}

22

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

1

2

3

4

5

6

1.6.3.7 STEP-6: Group JavaPairRDD elements by the key (name)

We implement the reducer operation by groupByKey(). As you observe, it is
much easier to implement the reducer by Spark than MapReduce/Hadoop.

Listing 1.14: STEP-6: Group JavaPairRDD Elements

1

2

// STEP-6: We group JavaPairRDD<> elements by the key ({name}).
JavaPairRDD<String, Iterable<Tuple2<Integer, Integer>>> groups = pairs.groupByKey();

1.6.3.8 STEP-7: Validate STEP-6

Listing 1.15: STEP-7: Validate STEP-6

1

2

3

4

5

6

7

8

9

10

11

// STEP-7: validate STEP-6, we collect all values from JavaPairRDD<> and print it.
System.out.println("===DEBUG1===");
List<Tuple2<String, Iterable<Tuple2<Integer, Integer>>>> output2 = groups.collect();
for (Tuple2<String, Iterable<Tuple2<Integer, Integer>>> t : output2) {

Iterable<Tuple2<Integer, Integer>> list =
System.out.println(t._1);
for (Tuple2<Integer, Integer> t2 : list) {

t._2;

System.out.println(t2._1 + "," + t2._2);

}
System.out.println("=====");

}

The output of this step is presented below. As you can observe, the

reducer values are not sorted.

y
2,5
1,7
3,1
=====
x
2,9
1,3
3,6
=====
z
1,4
2,8

23

3,7
4,0
=====
p
2,6
4,7
6,0
7,3
1,9
=====

1.6.3.9 STEP-8: Sort the Reducer’s Values in Memory

This step uses another powerful Spark method mapValues() to just sort the
values generted by reducers. The mapValues() method enable us to convert
(K, V1) into (K, V2). One important note about Spark’s RDD is that they
are immutable and can not be altered/updated by any means. For example,
in STEP-8, to sort our values, we have to copy them into another list before
sorting. Immutability applies to RDD itself and its elements.

Listing 1.16: STEP-8: Sort the Reducer’s Values in Memory

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

//STEP-8: Sort the reducer’s values and this will give us the final output.
// OPTION-1: worked
// mapValues[U](f: (V) => U): JavaPairRDD[K, U]
// Pass each value in the key-value pair RDD through a map function
// without changing the keys;
// this also retains the original RDD’s partitioning.
JavaPairRDD<String, Iterable<Tuple2<Integer, Integer>>> sorted =

groups.mapValues(new Function<Iterable<Tuple2<Integer, Integer>>,

Iterable<Tuple2<Integer, Integer>>

>() {

// input
// output

public Iterable<Tuple2<Integer, Integer>> call(Iterable<Tuple2<Integer, Integer>> s) {
List<Tuple2<Integer, Integer>> newList = new ArrayList<Tuple2<Integer, Integer>>(s);
Collections.sort(newList, new TupleComparator());
return newList;

}
});

1.6.3.10 STEP-9: Output Final Result

The collect() method collects all RDD’s elements into a java.util.List
object. Then we iterate through the List to get all ﬁnal elements.

24

Listing 1.17: STEP-9: Output Final Result

// STEP-9: validate STEP-8, we collect all values from JavaPairRDD<> and print it.
System.out.println("===DEBUG2=");
List<Tuple2<String, Iterable<Tuple2<Integer, Integer>>>> output3 = sorted.collect();
for (Tuple2<String, Iterable<Tuple2<Integer, Integer>>> t : output3) {

Iterable<Tuple2<Integer, Integer>> list =
System.out.println(t._1);
for (Tuple2<Integer, Integer> t2 : list) {

t._2;

System.out.println(t2._1 + "," + t2._2);

}
System.out.println("=====");

}

1

2

3

4

5

6

7

8

9

10

11

1.6.4 Spark Sample Run

1.6.4.1 HDFS Input

hadoop@hnode01319:~# hadoop fs -cat /mp/timeseries.txt
x,2,9
y,2,5
x,1,3
y,1,7
y,3,1
x,3,6
z,1,4
z,2,8
z,3,7
z,4,0
p,2,6
p,4,7
p,1,9
p,6,0
p,7,3

1.6.4.2 Spark Run

As far as Spark/Hadoop is concerned: you can run a Spark application in
three diﬀerent modes:4

4For details, see: http://spark.apache.org/docs/1.0.0/running-on-yarn.html

25

• Standalone mode, which is the default setup. You start Spark master
on a master node and a ”worker” on every slave node and submit you
Spark application to the Spark master.

• YARN client mode: in this mode, you do not start a spark master
or worker nodes. In this mode, you submit the Spark application to
YARN, which runs the Spark driver in the client Spark process that
submits the application.

• YARN cluster mode: in this mode, you do not start a spark master
or worker nodes. In this mode, you submit the Spark application to
YARN, which runs the Spark driver in the ApplicationMaster in YARN.

Below, we will show how to submit the ”secondary sort” application in

Standalone and YARN client modes.

1.6.4.3 Running Spark Standalone Mode

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

1

2

3

4

5

6

7

HDFS Input

# hadoop fs -cat /mp/timeseries.txt
x,2,9
y,2,5
x,1,3
y,1,7
y,3,1
x,3,6
z,1,4
z,2,8
z,3,7
z,4,0
p,2,6
p,4,7
p,1,9
p,6,0
p,7,3

The Script

# cat run_secondarysorting.sh
source /home/hadoop/conf/env_2.3.0.sh
export SPARK_HOME=/home/hadoop/spark-1.0.0
source /home/hadoop/spark_mahmoud_examples/spark_env_yarn.sh
source $SPARK_HOME/conf/spark-env.sh

CLASSPATH=$CLASSPATH:$HADOOP_HOME/etc/hadoop

26

8

9

10

11

12

13

14

15

16

17

18

19

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

jars=‘find $SPARK_HOME -name ’*.jar’‘
for j in $jars ; do

CLASSPATH=$CLASSPATH:$j

done
# app jar:
export CLASSPATH=/home/hadoop/spark_mahmoud_examples/mp.jar:$CLASSPATH
export SPARK_CLASSPATH=$CLASSPATH
export SPARK_MASTER=spark://hnode01319.nextbiosystem.net:7077
INPUT=/mp/timeseries.txt
OPTIONS="-Dspark.master=$SPARK_MASTER"
$JAVA_HOME/bin/java -cp $CLASSPATH $OPTIONS

SecondarySort $SPARK_MASTER $INPUT

Log of the Run

# ./run_secondarysorting.sh
args[0]: <master>=spark://hnode01319.nextbiosystem.net:7077
args[1]: <file>=/mp/timeseries.txt
...
=== DEBUG STEP-4 ===
14/06/04 08:42:50 INFO mapred.FileInputFormat: Total input paths to process : 1
14/06/04 08:42:50 INFO spark.SparkContext: Starting job: collect at SecondarySort.java:85
...
14/06/04 08:42:50 INFO scheduler.DAGScheduler: Submitting Stage 0

(MappedRDD[2] at mapToPair at SecondarySort.java:75), which has no missing parents
14/06/04 08:42:50 INFO scheduler.DAGScheduler: Submitting 1 missing tasks from Stage 0

(MappedRDD[2] at mapToPair at SecondarySort.java:75)

...
14/06/04 08:42:54 INFO scheduler.DAGScheduler: Stage 0 (collect at SecondarySort.java:85)

finished in 4.058 s

14/06/04 08:42:54 INFO spark.SparkContext: Job finished: collect at SecondarySort.java:85,

took 4.153418069 s

x,2,2
y,2,2
x,1,1
y,1,1
y,3,3
x,3,3
z,1,1
z,2,2
z,3,3
z,4,4
p,2,2
p,4,4
p,1,1
p,6,6
p,7,7
=== DEBUG STEP-6 ===
14/06/04 08:42:54 INFO spark.SparkContext: Starting job: collect

at SecondarySort.java:96

14/06/04 08:42:54 INFO scheduler.DAGScheduler: Registering RDD 2

(mapToPair at SecondarySort.java:75)

...
14/06/04 08:42:55 INFO scheduler.DAGScheduler: Stage 1

27

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

90

91

92

93

94

95

96

(collect at SecondarySort.java:96) finished in 0.273 s
14/06/04 08:42:55 INFO spark.SparkContext: Job finished:
collect at SecondarySort.java:96, took 1.587001929 s

z
1,4
2,8
3,7
4,0
=====
p
2,6
4,7
1,9
6,0
7,3
=====
x
2,9
1,3
3,6
=====
y
2,5
1,7
3,1
=====
=== DEBUG STEP-8 ===
14/06/04 08:42:55 INFO spark.SparkContext: Starting job: collect

at SecondarySort.java:158

...
14/06/04 08:42:55 INFO scheduler.TaskSchedulerImpl: Removed TaskSet 3.0,

whose tasks have all completed, from pool

14/06/04 08:42:55 INFO spark.SparkContext: Job finished: collect at

SecondarySort.java:158, took 0.074271723 s

z
1,4
2,8
3,7
4,0
=====
p
1,9
2,6
4,7
6,0
7,3
=====
x
1,3
2,9
3,6
=====
y
1,7
2,5
3,1
=====

28

97

1

2

3

4

5

6

7

8

9

10

11

12

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

Typically, you save the ﬁnal result to HDFS. This can be accomplished by
adding the following line of code after creating your ”sorted” RDD:

sorted.saveAsTextFile("/mp/output");

Then you may view the output as:

# hadoop fs -ls /mp/output/
Found 2 items
-rw-r--r--
-rw-r--r--

3 hadoop root,hadoop
3 hadoop root,hadoop

# hadoop fs -cat /mp/output/part-00000
(z,[(1,4), (2,8), (3,7), (4,0)])
(p,[(1,9), (2,6), (4,7), (6,0), (7,3)])
(x,[(1,3), (2,9), (3,6)])
(y,[(1,7), (2,5), (3,1)])

0 2014-06-04 10:49 /mp/output/_SUCCESS
125 2014-06-04 10:49 /mp/output/part-00000

Running Spark YARN Cluster Mode

The Script to submit our Spark application YARN cluster mode is given
below:

# cat run_secondarysorting_yarn.sh
#!/bin/bash
export HADOOP_HOME=/usr/local/hadoop/hadoop-2.3.0
export SPARK_LIBRARY_PATH=$HADOOP_HOME/lib/native
export JAVA_HOME=/usr/java/jdk7
export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop
export YARN_CONF_DIR=$HADOOP_HOME/etc/hadoop
export SPARK_HOME=/home/hadoop/spark-1.0.0
export MY_JAR=/home/hadoop/spark_mahmoud_examples/mp.jar
export SPARK_MASTER=spark://hnode01319.nextbiosystem.net:7077

$SPARK_HOME/bin/spark-submit \

--class SecondarySort \
--master yarn-cluster \
--executor-memory 2G \
--num-executors 10 \
$MY_JAR \
$SPARK_MASTER \
/mp/timeseries.txt

29

1.6.5 Option-2: Secondary Sorting using Framework

In solution for Option-1, we sorted reducers values in memory (using Java’s
Collections.sort() method), wchich might not scale if the reducers values
will not ﬁt in a commodity server’s memory. We implemented Option-2 for
MapReduce/Hadoop framework. we cannot achieve this in current Spark
(Spark-1.0.0) framework, because current Sparks Shuﬄe is based on hash,
which is diﬀerent from MapReduces sort-based shuﬄe, so you should imple-
ment sorting explicitly using RDD operator. If we had a partitioner by a
natural key (by name), which preserved the order of RDD, then that would
be a viable solution: for example, if we sort by (name, time), we would get:

(p,1),(1,9)
(p,4),(4,7)
(p,6),(6,0)
(p,7),(7,3)

(x,1),(1,3)
(x,2),(2,9)
(x,3),(3,6)

(y,1),(1,7)
(y,2),(2,5)
(y,3),(3,1)

(z,1),(1,4)
(z,2),(2,8)
(z,3),(3,7)
(z,4),(4,0)

There is a partitioner (represented as an abstract class org.apache.spark.Partitioner),
but it does not preserve the order of original RDD elements. Therefore,
Option-2 cannot be implemented by the current version of Spark (1.0.0).

30

Chapter 2

Secondary Sorting: Detailed Example

2.1

Introduction

MapReduce framework sorts input to reducers by key, but values of reduc-
ers are arbitrarily ordered. This means that if all mappers generated the
following (key-value) pairs for key = K:

(K, V1), (K, V2), ..., (K, Vn)

Then all these values {V1, V2, ..., Vn} will be processed by a single reducer
(for key = K), but there is no order (ascending or descending) between Vi’s.
Secondary sorting is a design pattern which will put some kind or ordering
(such as ”ascending sort” or ”descending sort”) among the values Vi’s. How
do we accomplish this? That is we want to have some order between the
reducer values:

S1 ≤ S2 ≤ ... ≤ Sn

or

S1 ≥ S2 ≥ ... ≥ Sn
where Si ∈ {V1, V2, ..., Vn} for i = {1, 2, ..., n}. Note that each Vi might be
a simple data type such as String or Integer or a tuple (more than a single
value – a composite object).

There are two ways to have sorted values for reducer values:

• Solution-1: Buﬀer reducer values in memory, then sort. If the num-
ber of reducer values are small enough, so they can ﬁt in memory (per

31

reducer), then this solution will work. But if the the number of re-
ducer values are high, then these values might not ﬁt in memory (not a
preferable solution). Implementation of this solution is trivial and will
not be discussed in this chapter.

• Solution-2: Use ”secondary sorting” design pattern of MapReduce frame-
work and reducer values will arrive sorted to a reducer (no need to sort
values in memory). This technique uses the shuﬄe and sort technique
of MapReduce framework to perform sorting of reducer values. This
technique is preferable to Solution-1 because you do not depend on the
memory for sorting (and if you have too many values, then Solution-
1 might not be a viable option). The rest of this chapter will focus
on presenting Solution-2. We present implementation of Solution-2 in

Hadoop by using

– Old Hadoop API (using org.apache.hadoop.mapred.JobConf and
org.apache.hadoop.mapred.*); I intentionally included Hadoop’s
old API if in case you are using an old API and have not migrated
to new Hadoop API.

– New Hadoop API (using org.apache.hadoop.mapreduce.Job and

org.apache.hadoop.mapreduce.lib.*)

2.2 Secondary Sorting Technique

Let’s have the following values for key = K:

(K, V1), (K, V2), ..., (K, Vn)

and further assume that each Vi is a tuple of m attributes as:

(ai1, ai2, ..., aim)

where we want to sort reducer’s tuple values by ai1. We will denote
(ai2, ..., aim) (the remaining attributes) by r. Therefore, we can express
reducer values as:

(K, (a1, r1)), (K, (a2, r2)), ..., (K, (an, rn))

32

To sort the reducer values by ai, we create a composite key: (K, ai). Our

new mappers will emit the following (key, value) pairs for key = K.

Key

value

(K, a1)
(K, a2)
...
(K, an)

(a1, r1)
(a2, r2)
...
(an, rn)

So the ”composite key” is (K, ai) and the ”natural key” is K. Deﬁning
the composite key (by adding the attribute ai to the ”natural key” where
the values will be sorted on) enables us to sort the reducer values by the
MapReduce framework, but when we want to partition keys, we will partition
it by the ”natural key” (as K). Below ”composite key” and ”natural key” are
presented visually in 2.2.

Since we deﬁned a ”composite key” (composed of ”natural key” (as K)
and an attribute (as ai) where the reducer values will be sorted on), we
have to tell the MapReduce framework how to sort the keys by using a
”composite key” (comprised of two ﬁelds: K and ai):
for this we need to
deﬁne a plug-in sort class, CompositeKeyComparator, which will be sorting
the Composite Keys. This is how you plug-in this comparator class to a
MapReduce framework:

Listing 2.1: Plug-in Comparator Class

1

2

3

4

5

6

7

8

9

10

11

12

import org.apache.hadoop.mapred.JobConf;
...
JobConf conf = new JobConf(getConf(), <your-mapreduce-driver-class>.class);
...
// map() creates (key-value) pairs of
// of (CompositeKey, NaturalValue)
conf.setMapOutputKeyClass(CompositeKey.class);
conf.setMapOutputValueClass(NaturalValue.class);
...
// Plug-in Comparator Class:
// how CompositeKey objects will be sorted
conf.setOutputKeyComparatorClass(CompositeKeyComparator.class);

The CompositeKeyComparator class is telling to the MapReduce frame-
work how to sort the composite keys (comprised of two ﬁelds: K and ai). The
implementation is provided below, which compares two WriteableComparables
objects (representing a CompositeKey object).

33

Figure 2.1: Secondary Sorting Keys

34

Listing 2.2: Comparator Class: CompositeKeyComparator

1 import org.apache.hadoop.io.WritableComparable;
2 import org.apache.hadoop.io.WritableComparator;
3
4 public class CompositeKeyComparator extends WritableComparator {
5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

protected CompositeKeyComparator() {

super(CompositeKey.class, true);

}

@Override
public int compare(WritableComparable k1, WritableComparable k2) {

CompositeKey ck1 = (CompositeKey) k1;
CompositeKey ck2 = (CompositeKey) k2;

// compare ck1 with ck2 and return
0,
//
//
1,
// -1,

if ck1 and ck2 are identical
if ck1 > ck2
if ck1 < ck2

// detail of implementation is provided in sub sections

}

21
22 }

The next piece of plug-in class is a ”natural key partitioner” class (let’s

call this NaturalKeyPartitioner class), which will implement the org.apache.hadoop.mapred.Partitioner
interface. This is how we plug-in the class to the MapReduce framework:

Listing 2.3: Plug in Natural Key Partitioner

1

2

3

4

5

import org.apache.hadoop.mapred.JobConf;
...
JobConf conf = new JobConf(getConf(), <your-mapreduce-driver-class>.class);
...
conf.setPartitionerClass(NaturalKeyPartitioner.class);

Next, we deﬁne the Natural Key Partitioner class:

Listing 2.4: Natural Key Partitioner Class Deﬁnition

1 import org.apache.hadoop.mapred.JobConf;
2 import org.apache.hadoop.mapred.Partitioner;
3
4 /**
5

* NaturalKeyPartitioner partitions the data output from the
* map phase before it is sent through the shuffle phase.
*
* getPartition() partitions data generated by mappers;
* This function should partition data by the "natural key".
*

6

7

8

9

10

35

*/

11
12 public class NaturalKeyPartitioner implements
Partitioner<CompositeKey, NaturalValue> {
13

14

15

16

17

18

19

20

21

22

23

24
25 }

@Override
public int getPartition(CompositeKey key,

NaturalValue value,
int numberOfPartitions) {

return <number-based-on-composite-key> % numberOfPartitions;

}

@Override
public void configure(JobConf arg) {
}

The last piece to plugin is NaturalKeyGroupingComparator, which con-
siders the natural key. This class just compares two natural keys. This is
how you plug-in the class to the MapReduce framework:

Listing 2.5: Natural Key Grouping Comparator Plug-in

1

2

3

4

5

import org.apache.hadoop.mapred.JobConf;
...
JobConf conf = new JobConf(getConf(), <your-mapreduce-driver-class>.class);
...
conf.setOutputValueGroupingComparator(NaturalKeyGroupingComparator.class);

This is how you deﬁne the NaturalKeyGroupingComparator class:

Listing 2.6: Natural Key Grouping Comparator Class

1 import org.apache.hadoop.io.WritableComparable;
2 import org.apache.hadoop.io.WritableComparator;
3
4 /**
5

6

7

8

9

*
* NaturalKeyGroupingComparator
*
* This class is used during Hadoop’s shuffle phase to group
* composite Key’s by the first part (natural) of their key.
*/

10
11 public class NaturalKeyGroupingComparator extends WritableComparator {
12

13

14

15

16

17

18

19

protected NaturalKeyGroupingComparator() {

super(NaturalKey.class, true);

}

@Override
public int compare(WritableComparable o1, WritableComparable o2) {

NaturalKey nk1 = (NaturalKey) o1;

36

NaturalKey nk2 = (NaturalKey) o2;
return nk1.getNaturalKey().compareTo(nk2.getNaturalKey());

20

21

22
23 }

}

2.3 Complete Example of Secondary Sorting

2.3.1 Problem Statement

Consider the following data:

Stock-Symbol

Date

Closed-Price

and assume that we want to generate the following output data per stock-

symbol:

Stock-Symbol: (Date1, Price1)(Date2, Price2)...(Daten, Pricen)

where

Date1 ≤ Date2 ≤ ... ≤ Daten

That is we want the reducer values to be sorted by the date of closed

price. This can be accomplished by ”secondary sorting”.

2.3.2 Input Format

We assume that input data is in CSV format:

Stock-Symbol,Date,Closed-Price

for example:

37

ILMN,2013-12-05,97.65
GOOG,2013-12-09,1078.14
IBM,2013-12-09,177.46
ILMN,2013-12-09,101.33
ILMN,2013-12-06,99.25
GOOG,2013-12-06,1069.87
IBM,2013-12-06,177.67
GOOG,2013-12-05,1057.34

2.3.3 Output Format

We want our output to be sorted by ”date of closed price”: for our sample
input, our desired output is listed beow:

ILMN: (2013-12-05,97.65)(2013-12-06,99.25)(2013-12-09,101.33)
GOOG: (2013-12-05,1057.34)(2013-12-06,1069.87)(2013-12-09,1078.14)
IBM: (2013-12-06,177.67)(2013-12-09,177.46)

2.3.4 Composite Key

The ”natural key” is the stock symbol and the ”composite key” is a pair of
(Stock-Symbol,Date). The Date ﬁeld has to be part of our ”composite key”
because we want reducer values to be sorted by Date. The ”natural key”
and ”composite key” are illustrated below:

Therefore we can deﬁne the ”composite key” as CompositeKey class and
its associated comparator class as CompositeKeyComparator (how to sort
objects of CompositeKey):

38

Figure 2.2: Secondary Sorting: Composite and Natural Keys

39

2.3.4.1 Composite Key Deﬁnition

The Composite Key Deﬁnition is implemented as a CompositeKey class,
which implements the WritableComparable<CompositeKey> interface1

Listing 2.7: Composite Key Deﬁnition

9

10

11

12

13

14

15

16

17

18

19

20

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

1 import java.io.DataInput;
2 import java.io.DataOutput;
3 import java.io.IOException;
4 import org.apache.hadoop.io.WritableComparable;
5 import org.apache.hadoop.io.WritableComparator;
6
7 /**
8

*
* CompositeKey: represents a pair of
* (String stockSymbol, long timestamp).
* Note that timestamp represents the Date.
*
*
* We do a primary grouping pass on the stockSymbol
* field to get all of the data of one type together,
* and then our "secondary sort" during the shuffle
* phase uses the timestamp long member to sort the
* data points so that they arrive at the reducer
* partitioned and in sorted order (by date).
*
*/

21
22 public class CompositeKey implements WritableComparable<CompositeKey> {
23

// natural key is (stockSymbol)
// composite key is a pair (stockSymbol, timestamp)
private String stockSymbol; // stock symbol
private long timestamp;

// date

public CompositeKey(String stockSymbol, long timestamp) {

set(stockSymbol, timestamp);

}

public CompositeKey() {
}

public void set(String stockSymbol, long timestamp) {

this.stockSymbol = stockSymbol;
this.timestamp = timestamp;

}

public String getStockSymbol() {

return this.stockSymbol;

}

1WritableComparable(s) can be compared to each other, typically via Comparator(s).
Any type which is to be used as a key in the Hadoop Map-Reduce framework should
implement this interface.

40

public long getTimestamp() {
return this.timestamp;

}

@Override
public void readFields(DataInput in) throws IOException {

this.stockSymbol = in.readUTF();
this.timestamp = in.readLong();

}

@Override
public void write(DataOutput out) throws IOException {

out.writeUTF(this.stockSymbol);
out.writeLong(this.timestamp);

}

@Override
public int compareTo(CompositeKey other) {

if (this.stockSymbol.compareTo(other.stockSymbol) != 0) {
return this.stockSymbol.compareTo(other.stockSymbol);

}
else if (this.timestamp != other.timestamp) {

return timestamp < other.timestamp ? -1 : 1;

}
else {

return 0;

}

}

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 }

2.3.4.2 Composite Key Comparator Deﬁnition

Composite Key Comparator Deﬁnition is implemented by the CompositeKeyComparator
class which compares two CompositeKey objects by implementaing the compare()
method. The compare() method returns 0 if they are identical, returns −1
if the ﬁrst composite key is smaller than the second one, otherwise returns
+1.

Listing 2.8: Composite Key Comparator Deﬁnition

1 import org.apache.hadoop.io.WritableComparable;
2 import org.apache.hadoop.io.WritableComparator;
3
4 /**
5

* CompositeKeyComparator
*
* The purpose of this class is to enable comparison of two CompositeKey(s).
*
*/

6

7

8

9

41

10 public class CompositeKeyComparator extends WritableComparator {
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

protected CompositeKeyComparator() {
super(CompositeKey.class, true);

}

@Override
public int compare(WritableComparable wc1, WritableComparable wc2) {

CompositeKey ck1 = (CompositeKey) wc1;
CompositeKey ck2 = (CompositeKey) wc2;

int comparison = ck1.getStockSymbol().compareTo(ck2.getStockSymbol());
if (comparison == 0) {

// stock symbols are equal here
if (ck1.getTimestamp() == ck2.getTimestamp()) {

return 0;

}
else if (ck1.getTimestamp() < ck2.getTimestamp()) {

return -1;

}
else {

return 1;

}

}
else {

}

return comparison;

}

37
38 }

2.3.5 Sample Run

2.3.5.1

Implementation Classes using Old Hadoop API

Description
Deﬁnes a composite key
Implements sorting composite keys
Deﬁnes some useful date handling methods
Deﬁnes some utility functions

Class name
CompositeKey
CompositeKeyComparator
DateUtil
HadoopUtil
NaturalKeyGroupingComparator Deﬁnes how natural keys will be grouped together
NaturalKeyPartitioner
NaturalValue
SecondarySortDriver
SecondarySortMapper
SecondarySortReducer

Implements how natural keys will be partitioned
Deﬁnes a natural value
Submits a job to Hadoop
Deﬁnes map()
Deﬁnes reduce()

42

2.3.5.2

Input

# hadoop fs -ls /secondary_sort_chapter/input/
Found 1 items
-rw-r--r--

... /secondary_sort_chapter/input/sample_input.txt

# hadoop fs -cat /secondary_sort_chapter/input/sample_input.txt
ILMN,2013-12-05,97.65
GOOG,2013-12-09,1078.14
IBM,2013-12-09,177.46
ILMN,2013-12-09,101.33
ILMN,2013-12-06,99.25
GOOG,2013-12-06,1069.87
IBM,2013-12-06,177.67
GOOG,2013-12-05,1057.34

2.3.5.3 Running MapReduce Job

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

map 0% reduce 0%
map 23% reduce 0%

map 100% reduce 93%
map 100% reduce 100%

# ./run.sh
...
13/12/12 21:13:20 INFO mapred.FileInputFormat: Total input paths to process : 1
13/12/12 21:13:21 INFO mapred.JobClient: Running job: job_201312122109_0002
13/12/12 21:13:22 INFO mapred.JobClient:
13/12/12 21:13:29 INFO mapred.JobClient:
...
13/12/12 21:14:24 INFO mapred.JobClient:
13/12/12 21:14:25 INFO mapred.JobClient:
13/12/12 21:14:26 INFO mapred.JobClient: Job complete: job_201312122109_0002
...
13/12/12 21:14:26 INFO mapred.JobClient:
13/12/12 21:14:26 INFO mapred.JobClient:
13/12/12 21:14:26 INFO mapred.JobClient:
13/12/12 21:14:26 INFO mapred.JobClient:
13/12/12 21:14:26 INFO mapred.JobClient:
13/12/12 21:14:26 INFO mapred.JobClient:
13/12/12 21:14:26 INFO mapred.JobClient:
13/12/12 21:14:26 INFO mapred.JobClient:
13/12/12 21:14:26 INFO mapred.JobClient:
13/12/12 21:14:26 INFO mapred.JobClient:
13/12/12 21:14:26 INFO mapred.JobClient:
13/12/12 21:14:26 INFO mapred.JobClient:
13/12/12 21:14:26 INFO mapred.JobClient:
13/12/12 21:14:26 INFO mapred.JobClient:
13/12/12 21:14:26 INFO mapred.JobClient:

Map output materialized bytes=3143
Map input records=8
Reduce shuffle bytes=3143
Spilled Records=16
Map output bytes=238
Total committed heap usage (bytes)=4730576896
Map input bytes=185
Combine input records=0
SPLIT_RAW_BYTES=2520
Reduce input records=8
Reduce input groups=3
Combine output records=0
Reduce output records=3
Map output records=8

Map-Reduce Framework

43

28

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

2.3.5.4 Output

# hadoop fs -ls /secondary_sort_chapter/output/
Found 12 items
-rw-r--r-- 1 mahmoud staff
drwxr-xr-x - mahmoud staff
-rw-r--r-- 1 mahmoud staff
-rw-r--r-- 1 mahmoud staff
-rw-r--r-- 1 mahmoud staff
-rw-r--r-- 1 mahmoud staff
-rw-r--r-- 1 mahmoud staff
-rw-r--r-- 1 mahmoud staff
-rw-r--r-- 1 mahmoud staff
-rw-r--r-- 1 mahmoud staff
-rw-r--r-- 1 mahmoud staff
-rw-r--r-- 1 mahmoud staff

0 2013-12-12 21:14 /secondary_sort_chapter/output/_SUCCESS
0 2013-12-12 21:13 /secondary_sort_chapter/output/_logs
0 2013-12-12 21:13 /secondary_sort_chapter/output/part-00000
66 2013-12-12 21:13 /secondary_sort_chapter/output/part-00001
0 2013-12-12 21:13 /secondary_sort_chapter/output/part-00002
0 2013-12-12 21:13 /secondary_sort_chapter/output/part-00003
0 2013-12-12 21:14 /secondary_sort_chapter/output/part-00004
61 2013-12-12 21:14 /secondary_sort_chapter/output/part-00005
0 2013-12-12 21:14 /secondary_sort_chapter/output/part-00006
0 2013-12-12 21:14 /secondary_sort_chapter/output/part-00007
0 2013-12-12 21:14 /secondary_sort_chapter/output/part-00008
43 2013-12-12 21:14 /secondary_sort_chapter/output/part-00009

# hadoop fs -cat
GOOG
ILMN
IBM

/secondary_sort_chapter/output/part*

(2013-12-05,1057.34)(2013-12-06,1069.87)(2013-12-09,1078.14)
(2013-12-05,97.65)(2013-12-06,99.25)(2013-12-09,101.33)

(2013-12-06,177.67)(2013-12-09,177.46)

2.4 Secondary Sort using New Hadoop API

2.4.0.5

Implementation Classes using New API

Description
Deﬁnes a composite key
Implements sorting composite keys
Deﬁnes some useful date handling methods
Deﬁnes some utility functions

Class name
CompositeKey
CompositeKeyComparator
DateUtil
HadoopUtil
NaturalKeyGroupingComparator Deﬁnes how natural keys will be grouped together
NaturalKeyPartitioner
NaturalValue
SecondarySortDriver
SecondarySortMapper
SecondarySortReducer

Implements how natural keys will be partitioned
Deﬁnes a natural value
Submits a job to Hadoop
Deﬁnes map()
Deﬁnes reduce()

44

2.4.0.6

Input

... /secondary_sort_chapter_new_api/input/sample_input.txt

# hadoop fs -ls /secondary_sort_chapter_new_api/input/
Found 1 items
-rw-r--r--
# hadoop fs -cat /secondary_sort_chapter_new_api/input/sample_input.txt
ILMN,2013-12-05,97.65
GOOG,2013-12-09,1078.14
IBM,2013-12-09,177.46
ILMN,2013-12-09,101.33
ILMN,2013-12-06,99.25
GOOG,2013-12-06,1069.87
IBM,2013-12-06,177.67
GOOG,2013-12-05,1057.34

2.4.0.7 Running MapReduce Job

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

map 100% reduce 83%
map 100% reduce 100%

map 0% reduce 0%
map 100% reduce 0%
map 100% reduce 10%

# ./run.sh
...
13/12/14 21:18:25 INFO input.FileInputFormat: Total input paths to process : 1
...
13/12/14 21:18:25 INFO mapred.JobClient: Running job: job_201312142112_0002
13/12/14 21:18:26 INFO mapred.JobClient:
13/12/14 21:18:31 INFO mapred.JobClient:
13/12/14 21:18:39 INFO mapred.JobClient:
...
13/12/14 21:19:14 INFO mapred.JobClient:
13/12/14 21:19:15 INFO mapred.JobClient:
13/12/14 21:19:16 INFO mapred.JobClient: Job complete: job_201312142112_0002
...
13/12/14 21:19:16 INFO mapred.JobClient:
13/12/14 21:19:16 INFO mapred.JobClient:
13/12/14 21:19:16 INFO mapred.JobClient:
13/12/14 21:19:16 INFO mapred.JobClient:
13/12/14 21:19:16 INFO mapred.JobClient:
13/12/14 21:19:16 INFO mapred.JobClient:
13/12/14 21:19:16 INFO mapred.JobClient:
13/12/14 21:19:16 INFO mapred.JobClient:
13/12/14 21:19:16 INFO mapred.JobClient:
13/12/14 21:19:16 INFO mapred.JobClient:
13/12/14 21:19:16 INFO mapred.JobClient:
13/12/14 21:19:16 INFO mapred.JobClient:
13/12/14 21:19:16 INFO mapred.JobClient:
13/12/14 21:19:16 INFO mapred.JobClient:

Map output materialized bytes=314
Map input records=8
Reduce shuffle bytes=314
Spilled Records=16
Map output bytes=238
Total committed heap usage (bytes)=1034620928
Combine input records=0
SPLIT_RAW_BYTES=140
Reduce input records=8
Reduce input groups=3
Combine output records=0
Reduce output records=3
Map output records=8

Map-Reduce Framework

45

2.4.0.8 Output of MapReduce Job

# hadoop fs -cat /secondary_sort_chapter_new_api/output/part*
GOOG (2013-12-05,1057.34)(2013-12-06,1069.87)(2013-12-09,1078.14)
ILMN (2013-12-05,97.65)(2013-12-06,99.25)(2013-12-09,101.33)
IBM

(2013-12-06,177.67)(2013-12-09,177.46)

46

Chapter 3

Top 10 List

3.1

Introduction

Given a set of (key-as-string, value-as-integer) pairs, then ﬁnding a
Top-N ( where N > 0) list is a ”design pattern” (a ”design pattern” is a
language-independent reusable solution to a common problem, which enable
us to produce reusable code). For example, let key-as-string be a URL
and value-as-integer be the number of times that URL is visited, then
you might ask: what are the top-10 URLs for last week? This kind of a
question is common for this type of (key, value) pairs. For details on the
”top-10 list” design pattern refer to MapReduce Design Patterns book by
Donald Miner[16]. Finding ”top-10 list” falls into ”Filtering Pattern” (you
ﬁlter out data and ﬁnd top-10 list).

This chapter provides a complete MapReduce solution for Top-10 design pat-
tern and its associated implementations with Apache Hadoop (using classic
MapReduce’s map() and reduce() functions) and Apache Spark (using RDD’s
– Resilient Distributed Datasets). For this chapter we present 3 solutions:

• First Top-10 Solution in MapReduce/Hadoop. The assumption is that
all input keys are unique. For a given input {(K, V)} all K’s are unique.

• Second Top-10 Solution in Spark/Hadoop. The assumption is that all
input keys are unique. For a given input {(K, V)} all K’s are unique.

• Third Top-10 Solution in Spark/Hadoop. The assumption is that all

47

input keys are not unique. For a given input {(K, V)} all K’s are not
unique.

Our MapReduce solutions will generlize the ”top 10 list” and will be able
to ﬁnd ”top N list” (for N > 1). For example, we will be able to ﬁnd ”top 10
cats”, ”top 50 most visited web sites”, or ”top 100 search queries of a search
engine”.

The question for ”top N list” can be like:

1. What are the ”top 10 list” of cats?

2. What are the ”top 100 list” of web sites visited last month?

3. What are the ”top 20 list” of search queries from Google or Yahoo in

the last week?

4. What are the ”top 10 list” of liked items from Facebook yesterday?

5. What are the ”top 5 list” of cartoons of all time?

3.2 Top-N Formalized

Let N > 0, Let L be a List<Tuple2<T,Integer>>, where T can be any type,
L.size() = S, S > N, and elements of L be:

{(Ki, Vi), 1 ≤ i ≤ S}
where Ki has a type of T and Vi is an Integer type (this is the frequency of
Ki). Let sort(L) be (sort is done by using frequency as a key):

{(Aj, Bj), 1 ≤ j ≤ S, B1 ≥ B2 ≥ ... ≥ BS}

where (Aj, Bj) ∈ L. Then top-N of L is deﬁned as:

top-N(L) = {(Aj, Bj), 1 ≤ j ≤ N B1 ≥ B2 ≥ ... ≥ BN }

The easy way to implement top-N in Java is to use SortedMap and
TreeMap data structures and then keep adding all elements of L to topN,
but make sure to remove the ﬁrst element (an element with the smallest fre-
quency) of topN if topN.size() > N. The following code segment (POJO-
like) illustrates top-N algorithm for list L:

48

Listing 3.1: Top-N Algorithm

1 import scala.Tuple2;
2 import java.util.List;
3 import java.util.TreeMap;
4 import java.util.SortedMap;
5 import <your-package>.T;
6 ...
7 static SortedMap<Integer,T> topN(List<Tuple2<T,Integer>> L, int N) {
8

SortedMap<Integer, T> topN = new TreeMap< Integer, T>();
for (Tuple2<T,Integer> element : L) {

9

10

11

12

13

14

15

16

17

18

19
20 }

// element._1 is a type T
// element._2 is the frequency of type Integer
topN.put(element._2, element._1);
// keep only top N
if (topN.size() > N) {

// remove element with the smallest frequency
topN.remove(topN.firstKey());

}

}
return topN;

3.3 MapReduce Solution

Let cats be a relation of 3 attributes: (cat_id, cat_name, cat_weight) and
assume we have billions of cats (big data).

cats Table
Attribute Name Attribute Type
cat_id
cat_name
cat_weight

String
String
Double

Let N > 0 and suppose we want to ﬁnd ”top N list” of cats (based on
cat_weight). Before we delve into MapReduce solution, let’s see how we
can express ”top 10 list” of cats in SQL:

SELECT cat_id, cat_name, cat_weight

FROM cats

ORDER BY cat_weight DESC LIMIT 10;

The solution in SQL is very straightforward and will require sorting the
whole cats table. The question is why not use a relational database and SQL

49

for this. The short answer is most often our big data is not as structured
as relational databases and tables and quite often we do need to parse semi-
structured data such as log ﬁles or other type of data to make this happen.
And when your size of data is huge in relational databases, they become
non-responsive and do not scale well.

The MapReduce solution is pretty straightforward: each mapper will ﬁnd
a local ”top N list” (for N > 1) and then will pass it to a SINGLE reducer.
Then the single reducer will ﬁnd the ﬁnal ”top N list” from all local ”top
N list” passed from mappers. In general, in most of the MapReduce algo-
rithms, having a single reducer is problematic and will cause a performance
bottleneck (the reason for bottleneck is that one reducer in one server re-
ceives all data – which can be very big data volume – and all other cluster
nodes do nothing, so the entire pressure and load will be on a single node,
which can cause performance bottlenecks). Here, our single reducer will not
cause a performance problem. Here is how: let’s assume that we will have
1000 mappers, then each mapper will only generate 10 (key, value) pairs.
Therefore, our single reducer will only get 10,000 (10 × 1000) records (which
is not that much data at all to cause performance bottleneck!).

The Top-10 algorithm is presented below. Input is partitioned into smaller
chunks and each chunk is sent to a mapper. Each mapper creates a local top-
10 list and then emits the local top-10 to be sent to reducers. In emitting
mappers output, we use a single reducer key so that all mappers output will
be consumed by a single reducer.

To parameterize the ”top N list”, we just need to pass the N from the
driver (which launched the MapReduce job) to map() and reduce() func-
tions by using MapReduce Configuration1 object. The driver sets "top.n"
parameter and map() and reduce() read that parameter in their setup()
functions.

Here we will focus on ﬁnding ”top N list” of cats. The mapper class will

have the following structure:

Listing 3.1: Mapper Class Outline

// imports ...

1 org.apache.hadoop.conf.Configuration

50

Figure 3.1: Top-10 MapReduce Algorithm: for Unique Keys

51

public class TopN_Mapper {

// define data structures needed for finding local top-10
private SortedMap<Double, Text> top10cats = new TreeMap<Double, Text>()

;

private int N = 10; // default is top 10

// setup() function will be exeuted once() per mapper
setup(Context context) {

...

}

map(key, value) {

... process (key, value) pair

}

// cleanup() function will be exeuted once() per mapper
cleanup(Context context) {

...

}

}

Next, we deﬁne the setup() function:

Listing 3.2: setup() for Top N List

public class TopN_Mapper {

...
private SortedMap<Double, Text> top10cats = new TreeMap<Double, Text>()

;

private int N = 10; // default is top 10

/**
* setup() function will be exeuted once() per mapper
* Here we setup the "cats top N list" as top10cats
*/
setup(Context context) {

// "top.n" has to be set up by the driver of our job
Configuration conf = context.getConfiguration();
N = conf.get("top.n");

}

The map() ﬁnction accepts a chunck of input and generates a local top-10
list. We are using diﬀerent delimiters to optimize parsing input by mappers

52

and reducers (to avoid non-necessary String concatenations).

Listing 3.3: map() for Top N List
/**
* @param key is generated by MapReduce framework, ignored here
* @paran value as a String has the format:
* <cat-weight><,><cat-id><;><cat-name>
*/
map(key, value) {

String[] tokens = value.split(",");
// cat-weight = tokens[0];
// <cat-id><;><cat-name> = tokens[1]
Double weight = Double.parseDouble(tokens[0]);
top10cats.put(weight, value);

// keep only top N
if (top10cats.size() > N) {

// remove an element with the smallest frequency
top10cats.remove(top10cats.firstKey());

}

}

Each mapper accepts a partition of cats. After mapper ﬁnishes creating a
top-10 list as SortedMap<Double, Text>, the cleanup() method emits the
top-10 list. Note that we use a single key as NullWritable.get(), which
guarantees that all mappers’s output will be consumed by a single reducer.

Listing 3.4: cleanup() for Top N List
/**
* cleanup() function will be exeuted once at the end of each mapper
* Here er setup the cats top N list as top10cats
*/
cleanup(Context context) {

// now we emit top N from this mapper
for (String catAttributes : top10cats.values() ) {

context.write(NullWritable.get(), catAttributes);

}

}

The single reducer gets all local top-10 lists and create a single ﬁnal top-10

list.

53

Listing 3.5: reduce() for Top N List
/**
* @param key is null (single reducer)
* @paran values as a List of String and each element
* of the list has the format <cat-weight>,<cat-id>;<cat-name>
*/
reduce(key, values) {

SortedMap<Double, Text> finaltop10 = new TreeMap< Double, Text>();

// aggregate all local top-10 lists
for (Text catRecord : values) {

String[] tokens = catRecord.split(",");
Double weight = Double.parseDouble(tokens[0]);
finaltop10.put(weight, value);

if (finaltop10.size() > N) {

// remove an element with the smallest frequency
finaltop10.remove(finaltop10.firstKey());

}

}

// emit final top-10 list
for (Text text : finaltop10.values()) {

context.write(NullWritable.get(), text);

}

}

3.4

Implementation in Hadoop

The MapReduce/Hadoop implementation is comprised of the following classes:

Implementation Classes in Hadoop
Class Name Class Description
Dirver to submit job
TopN_Driver
Deﬁnes map()
TopN_Mapper
TopN_Reducer Deﬁnes reduce()

The TopN_Driver class reads N (for Top-N) from a command line and sets
it in the Hadoop’s Configuration object to be read by the map() function.

54

3.4.1

Input

# hadoop fs -cat /top10list/input/sample_input.txt
12,cat1,cat1
13,cat2,cat2
14,cat3,cat3
15,cat4,cat4
10,cat5,cat5
100,cat100,cat100
200,cat200,cat200
300,cat300,cat300
1,cat001,cat001
67,cat67,cat67
22,cat22,cat22
23,cat23,cat23
1000,cat1000,cat1000
2000,cat2000,cat2000

3.4.2 Sample Run 1: ﬁnd top 10 list

# cat run.sh
#/bin/bash
export HADOOP_HOME=/Users/mahmoud/zmp/zs/hadoop
export HADOOP_HOME_WARN_SUPPRESS=true

export JAVA_HOME=‘/usr/libexec/java_home‘
echo "JAVA_HOME=$JAVA_HOME"

PATH=.:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
PATH=$PATH:$HADOOP_HOME/bin
PATH=$PATH:$JAVA_HOME/bin
export PATH

CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-ant-1.0.3.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-core-1.0.3.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-examples-1.0.3.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-test-1.0.3.jar

55

CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-tools-1.0.3.jar

CLASSPATH=$CLASSPATH:$HADOOP_HOME/lib/log4j-1.2.15.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/lib/commons-cli-1.2.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/lib/commons-logging-1.1.1.jar
JAR=/Users/mahmoud/zmp/map_reduce_book/hadooptests/top10list/top10list.jar
export CLASSPATH=$CLASSPATH:$JAR
export HADOOP_CLASSPATH=$CLASSPATH

javac *.java
jar cvf $JAR *.class

$ INPUT="/top10list/input"
$ OUTPUT="/top10list/output"
$ HADOOP_HOME/bin/hadoop fs
$ HADOOP_HOME/bin/hadoop jar

-rmr

$OUTPUT

$JAR

TopN_Driver

$INPUT $OUTPUT

# ./run.sh
JAVA_HOME=/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
added manifest
adding: TopN_Driver.class(in = 3481) (out= 1660)(deflated 52%)
adding: TopN_Mapper.class(in = 3537) (out= 1505)(deflated 57%)
adding: TopN_Reducer.class(in = 3693) (out= 1599)(deflated 56%)
rmr: cannot remove /top10list/output: No such file or directory.
13/03/06 15:17:54 INFO TopN_Driver: inputDir=/top10list/input
13/03/06 15:17:54 INFO TopN_Driver: outputDir=/top10list/output
13/03/06 15:17:54 INFO TopN_Driver: top.n=10
13/03/06 15:17:54 INFO input.FileInputFormat: Total input paths to process : 1
...
13/03/06 15:17:55 INFO mapred.JobClient: Running job: job_201303061200_0022
13/03/06 15:17:56 INFO mapred.JobClient: map 0% reduce 0%
13/03/06 15:18:10 INFO mapred.JobClient: map 100% reduce 0%
13/03/06 15:18:22 INFO mapred.JobClient: map 100% reduce 100%
13/03/06 15:18:27 INFO mapred.JobClient: Job complete: job_201303061200_0022
...
13/03/06 15:18:27 INFO mapred.JobClient:
13/03/06 15:18:27 INFO mapred.JobClient:
13/03/06 15:18:27 INFO mapred.JobClient:

Map output materialized bytes=193
Map input records=14

Map-Reduce Framework

56

Reduce shuffle bytes=0

13/03/06 15:18:27 INFO mapred.JobClient:
...
13/03/06 15:18:27 INFO mapred.JobClient:
13/03/06 15:18:27 INFO mapred.JobClient:
13/03/06 15:18:27 INFO mapred.JobClient:
13/03/06 15:18:27 INFO mapred.JobClient:
13/03/06 15:18:27 INFO mapred.JobClient:
13/03/06 15:18:27 INFO TopN_Driver: run(): status=true
13/03/06 15:18:27 INFO TopN_Driver: returnStatus=0

Reduce input records=10
Reduce input groups=1
Combine output records=0
Reduce output records=10
Map output records=10

3.4.3 Output

# hadoop fs -cat /top10list/output/part*
14.0
15.0
22.0
23.0
67.0
100.0
200.0
300.0
1000.0 1000,cat1000,cat1000
2000.0 2000,cat2000,cat2000

14,cat3,cat3
15,cat4,cat4
22,cat22,cat22
23,cat23,cat23
67,cat67,cat67
100,cat100,cat100
200,cat200,cat200
300,cat300,cat300

3.4.4 Sample Run 2: ﬁnd top 5 list

The default returns ”top 10 list”, to get ”top 5 list”, we just need to pass
another parameter: this is how we can invoke our program:

$ INPUT="/top10list/input"
$ OUTPUT="/top10list/output"
$ $HADOOP_HOME/bin/hadoop jar $JAR TopN_Driver $INPUT $OUTPUT 5
$ hadoop fs -cat /top10list/output/*
100.0
200.0
300.0
1000.0 1000,cat1000,cat1000
2000.0 2000,cat2000,cat2000

100,cat100,cat100
200,cat200,cat200
300,cat300,cat300

57

3.5 Bottom 10

In previous sections, se showed that how to ﬁnd the ”top 10” list. To ﬁnd
the ”bottom 10”, we just need to change one line of code:

Replace the following

// find top-10
if (top10cats.size() > N) {

// remove the element with the smallest frequency
top10cats.remove(top10cats.firstKey());

}

With

// find bottom-10
if (top10cats.size() > N) {

// remove the element with the largest frequency
top10cats.remove(top10cats.lastKey());

}

3.6 Spark Implementation: Unique Keys

For this implementation, we assume that for all given input (K, V) pairs,
K’s are unique. For Top-10 design pattern, we provide Spark/Hadoop2 im-
plementation. Spark has a higher-level abstraction than classical MapRe-
duce/Hadoop. Spark provides a rich set of functional programming API,
which makes MapReduce programming easy. Spark can read/write data from
local ﬁle system as well as Hadoop’s HDFS. Spark uses the Hadoop-client
library to read/write from/to HDFS and other Hadoop-supported storage
systems. Typically, Spark programs can run faster than equivalent MapRe-
duce/Hadoop ones if you provide more RAM to the cluster nodes. Spark
provides StorageLevel class, which has ﬂags for controlling the storage of
an RDD. Some of these ﬂags are:

2Apache Spark is a fast and general-purpose cluster computing system. (source: http:

//spark.apache.org/)

58

• MEMORY_ONLY (use only memory for RDDs)

• DISK_ONLY (use only hard disk for RDDs)

• MEMORY_AND_DISK (use combination of memory and disk for RDDs).

Here, I am assuming that you have a ready Spark cluster running on top of
Hadoop (or you may run Spark on YARN without starting a Spark cluster).
To understand how to install Spark/Hadoop, you may look into:

• Apache Spark web site: http://spark.apache.org/

• Fast Data Processing with Spark book by Holden Karau (Packt Pub-

lishing)

3.6.1

Introduction

To understand Spark, we need to understand the concept of RDD (Resilient
Distributed Dataset). RDD is the basic abstraction in Spark, which repre-
sents an immutable, partitioned collection of elements that can be operated
on in parallel. Rather than working with diﬀerent types of input/output, you
work with an RDD, which can represent typed input/output. For example,
the following code snipit presents two RDD’s (lines and words):

1

2

3

4

5

6

7

8

9

// connect to Spark cluster by creating a JavaSparkContext object
JavaSparkContext ctx = new JavaSparkContext(...);

JavaRDD<String> lines = ctx.textFile(args[1], 1);

JavaRDD<String> words = lines.flatMap(new FlatMapFunction<String, String>() {

public Iterable<String> call(String s) {
return Arrays.asList(s.split(" "));

}

10

});

The following table explains the code:

59

Spark RDD’s

Line(s) Description
1

3

5-9

creates a Java Spark Context as JavaSparkContext, represents
the connection to a Spark cluster, and can be used to create
RDDs, accumulators and broadcast variables on that cluster.
Creates a new JavaRDD<String>, which represents a text
ﬁle as a set of lines (each line/record is a String object)
We create a new RDD (from an existing RDD) as JavaRDD<String>,
which represents a tokenized set of words. FlatMapFunction<T, R>
has a function type of T => Iterable<R>

Spark is very powerfull in creating new RDD’s from existing ones. For exam-
ple, below, we use lines to create a new RDD as JavaPairRDD<Integer,
String> as pairs.

JavaPairRDD<String,Integer> pairs = lines.map(new PairFunction<String, String, Integer>() {

public Tuple2<String,Integer> call(String s) {

String[] tokens = s.split(",");
return new Tuple2<String,Integer>(tokens[0], Integer.parseInt(tokens[1]));

}

});

1

2

3

4

5

6

Each item in JavaPairRDD<String,Integer> represents a Tuple2<String,Integer>,

Here we assume that each input record has two tokens: <String><,><Integer>.

3.6.2 What is an RDD?

In Spark, an RDD (Resilient Distributed Dataset) is the basic data abstrac-
tion. RDDs are used to represent a set of immutable objects in Spark.
For example, to represent a set of Strings, we can use JavaRDD<String>
and to to represent (key-as-string, value-as-integer) pairs, we can use
JavaPairRDD<String,Integer>. RDDs enable MapReduce opertions (such
as map and reduceByKey) to run in parallel (parallelism is achived by par-
titioning RDDs). Spark’s API enable us to implement custom RDDs. For
details on RDDs, refer to http://spark.apache.org/docs/.

3.6.3 Spark’s Function Classes

Java does not support anonymous or ﬁrst-class functions (some of these
are implemented in JDK8), so functions must be implemented by extend-

60

ing the Function3, Function24, etc. classes. Spark’s RDD methods like
collect() and countByKey() return Java collections data types, such as
java.util.List and java.util.Map. To represent (key-value) pairs, you
may use scala.Tuple2, which is a Java class and (key, value) can be created
by using new Tuple2<K, V>(key, value).

The main power of Spark is in Function Classes (represented in the follow-
ing table) used by Java API, where each class has a single abstract method,
call(), that must be implemented by a programmer.

Spark Java Class

Function Type

Function<T, R>
DoubleFunction<T>
PairFunction<T, K, V>
FlatMapFunction<T, R>
DoubleFlatMapFunction<T>
PairFlatMapFunction<T, K, V> T => Iterable<Tuple2<K, V>>
Function2<T1, T2, R>

T => R
T => Double
T => Tuple2<K, V>
T => Iterable<R>
T => Iterable<Double>

T1, T2 => R (function of two arguments)

3.6.4 Spark Solution for Top-10 Pattern

In Spark, you may write your whole job of processing big data in a single
driver. This is possible, since Spark oﬀers a rich high-level abstraction on
MapReduce paradigm. Before presenting Top-10 algorithm in Spark, let’s
review the Top-10 algorithm. Let’s assume that our input records will have
the following format

<Integer><,><String>

and the goal is to ﬁnd Top-10 list for a given input. First, we will partition
input into segments (let’s say, we partition our input into 1000 mappers –
each mapper will work on one segment of the partition independently):

class mapper :

setup(): initialize top10 SortedMap<Integer, String>

map(key, inputrecord):

3org.apache.spark.api.java.function.Function
4org.apache.spark.api.java.function.Function2

61

1

1

2

3

4

5

6

7

8

9

10

11

1

2

3

4

5

6

7

key is system generated and ignored here
insert inputrecord into top10 SortedMap
if length of top10 is greater than 10 {
truncate list to a length of 10

}

cleanup(): emit top10 as SortedMap<Integer, String>

Since Spark does not support classic setup() and cleanup() functions in the
mapper or reducer, we will utilize JavaPairRDD.mapFunctions() method to
achive the same functionality as MapReduce/Hadoop setup() and cleanup()
methods. By using Spark’s JavaPairRDD.mapFunctions() we achieve the
same functionality and having the ”setup()” code at the top of the mapPar-
titions() and ”cleanup()” at the bottom.

The job of a reducer is almost similar to the mapper:
it ﬁnds the top-10
from a given set of all top-10 generated by mappers. The reducer will get a
collection of SortedMap<Integer, String> (as an input) and will create a
single ﬁnal SortedMap<Integer, String> as an output.

class reducer:

setup(): initialize finaltop10 SortedMap<Integer, String>

reduce(key, List<SortedMap<Integer, String>>):

build finaltop10 from List<SortedMap<Integer, String>>
emit finaltop10

3.6.5 Complete Spark Solution for Top-10 Pattern

First, I will present all main steps and then will expand each step. We
use a single Java class (represented as Top10.java) for solving Top-10 in
Spark:

Listing 3.2: Top-10 Program in Spark

62

1 // STEP-0: import required classes
2 public class Top10 {
3

public static void main(String[] args) throws Exception {

// STEP-1: make sure we have two input parameters
// STEP-2: create a connection to the Spark master
// STEP-3: read input file from HDFS
// STEP-4: create set of Tuple2<Integer, String>
// STEP-5: create a local top-10 for each input partition
// STEP-6: collect all local top-10’s and create a final top-10 list
// STEP-7: output the final top-10 list
System.exit(0);

4

5

6

7

8

9

10

11

12
13 }

}

3.6.5.1 Top10 class: STEP-0

The following section shows the classes, which needs to be imported.

Listing 3.3: Top-10 Program in Spark: import required classes

1 // STEP-0: import required classes
2 import scala.Tuple2;
3 import org.apache.spark.api.java.JavaRDD;
4 import org.apache.spark.api.java.JavaPairRDD;
5 import org.apache.spark.api.java.JavaSparkContext;
6 import org.apache.spark.api.java.function.FlatMapFunction;
7 import org.apache.spark.api.java.function.Function2;
8 import org.apache.spark.api.java.function.PairFunction;
9
10 import java.util.Arrays;
11 import java.util.List;
12 import java.util.Map;
13 import java.util.TreeMap;
14 import java.util.SortedMap;
15 import java.util.Iterator;
16 import java.util.Collections;

3.6.5.2 Top10 class: STEP-1

In this step, we make sure we have two input parameters: Spark-Master and
HDFS Input File. Sample example for these two input parameters will be

args[0]: spark://myserver.mycompany.com:7077
args[1]: /top10/input/top10data.txt

63

1

2

3

4

5

6

7

1

2

3

4

5

6

7

1

2

3

Listing 3.4: Top-10 Program in Spark: handle input parameters

// STEP-1: make sure we have two input parameters
if (args.length < 2) {

System.err.println("Usage: Top10 <spark-master> <hdfs-file>");
System.exit(1);

}
System.out.println("args[0]: <spark-master>="+args[0]);
System.out.println("args[1]: <hdfs-file>="+args[1]);

3.6.5.3 Top10 class: STEP-2

In this step, we create a connection object (as JavaSparkContext) to a
Spark-Master. We will use the ctx object to create RDD’s.

Listing 3.5: Top-10 Program in Spark: connect to Spark Master

// STEP-2: create a connection to the Spark master
JavaSparkContext ctx = new JavaSparkContext(

args[0], // <spark-master>
"Top10",
System.getenv("SPARK_HOME"),
System.getenv("SPARK_EXAMPLES_JAR")

);

3.6.5.4 Top10 class: STEP-3

In this step, we read an ﬁle ﬁle from HDFS and create an RDD of JavaRDD<String>.

Listing 3.6: Top-10 Program in Spark: read input ﬁle from HDFS

// STEP-3: read input file from HDFS
// input record format: <string-key><,><integer-value>
JavaRDD<String> lines = ctx.textFile(args[1], 1);

3.6.5.5 Top10 class: STEP-4

In this step, we create a new RDD (JavaPairRDD<Integer, String>) from
an existing RDD (JavaRDD<String>). The PairFunction class has 3 argu-
ments: the ﬁrst argument (T) is an input and the last two parameters (K,
V) are output:

• Spark Java Class: PairFunction<T, K, V>

64

• Function Type: T => Tuple2<K, V>

Listing 3.7: Top-10 Program in Spark: create set of Tuple2

// STEP-4: create set of Tuple2<String,Integer>
// PairFunction<T, K, V>
// T => Tuple2<K, V>
JavaPairRDD<String,Integer> pairs =

lines.mapToPair(new PairFunction<

String,
String,
Integer

>() {

// input (T)
// K
// V

public Tuple2<String,Integer> call(String s) {
String[] tokens = s.split(","); // cat24,123
return new Tuple2<String,Integer>(tokens[0], Integer.parseInt(tokens[1]));

}
});

1

2

3

4

5

6

7

8

9

10

11

12

13

14

3.6.5.6 Top10 class: STEP-5

In this step, again, we create a new RDD (JavaRDD<SortedMap<Integer,
String>>) from an existing RDD (JavaPairRDD<String,Integer>). The
mapPartitions() is a very powerful method and enable us to acheive the se-
mantic of classic MapReduce/Hadoop methods (setup(), map(), and cleanup().
In this step, we create a local top-10 list from each partition.

Listing 3.8: Top-10 Program in Spark: create a local top-10 for each input

partition

1 // STEP-5: create a local top-10 for each input partition
2 JavaRDD<SortedMap<Integer, String>> partitions = pairs.mapPartitions(
3

new FlatMapFunction<Iterator<Tuple2<String,Integer>>, SortedMap<Integer, String>>() {
@Override
public Iterable<SortedMap<Integer, String>> call(Iterator<Tuple2<String,Integer>> iter) {

4

5

6

7

8

9

10

11

12

13

14

15

16

SortedMap<Integer, String> top10 = new TreeMap<Integer, String>();
while (iter.hasNext()) {

Tuple2<String,Integer> tuple = iter.next();
top10.put(tuple._2, tuple._1);
// keep only top N
if (top10.size() > 10) {

// remove the element with the smallest frequency
top10.remove(top10.firstKey());

}

}
return Collections.singletonList(top10);

}

17
18 });

65

How did we acheive the implementation of classic MapReduce/Hadoop
methods (setup(), map(), and cleanup()). Line 6 accomplishes the setup()
equivalent (creates and initializes a local top10 as SortedMap<Integer,
String>). Lines 7-14 implements the map() function, and ﬁnally the cleanup()
method is implemented by Line 16 (by returning the result of a local top-10).

3.6.5.7 Top10 class: STEP-6

This step iterates over all local top-10 lists created per partition and creates
a single ﬁnal top-10 list. To get all local top-10 lists, we use the collect()
method and then iterate over all local top-10 lists.

Listing 3.9: Top-10 Program in Spark: create the ﬁnal top-10 list

1 // STEP-6: collect all local top-10’s and create a final top-10 list
2 SortedMap<Integer, String> finaltop10 = new TreeMap<Integer, String>();
3 List<SortedMap<Integer, String>> alltop10 = partitions.collect();
4 for (SortedMap<Integer, String> localtop10 : alltop10) {
5

// weight = tuple._1
// catname = tuple._2
for (Map.Entry<Integer, String> entry : localtop10.entrySet()) {

System.out.println(entry.getKey() + "--" + entry.getValue());

//
finaltop10.put(entry.getKey(), entry.getValue());
// keep only top 10
if (finaltop10.size() > 10) {

// remove the element with the smallest frequency
finaltop10.remove(finaltop10.firstKey());

}

6

7

8

9

10

11

12

13

14

}

15
16 }

3.6.5.8 Top10 class: STEP-7

This step emits the ﬁnal top-10 list by iterating over the SortedMap<Integer,
String>.

Listing 3.10: Top-10 Program in Spark: emit the ﬁnal top-10 list

1 // STEP-7: output the final top-10 list
2 System.out.println("=== top-10 list ===");
3 for (Map.Entry<Integer, String> entry : finaltop10.entrySet()) {
4
5 }

System.out.println(entry.getKey() + "--" + entry.getValue());

66

3.6.6

Input

For our sample run, I have created a sample input ﬁle:

# hadoop fs -ls /top10/input/top10data.txt
Found 1 items
-rw-r--r--

3 hadoop,hadoop

161 2014-04-28 14:22 /top10/input/top10data.txt

# hadoop fs -cat /top10/input/top10data.txt
cat1,12
cat2,13
cat3,14
cat4,15
cat5,10
cat100,100
cat200,200
cat300,300
cat1001,1001
cat67,67
cat22,22
cat23,23
cat1000,1000
cat2000,2000
cat400,400
cat500,500

3.6.7 Sample Run : ﬁnd top-10 list

This sample is run on a 3-node cluster:
sparkserver300, where sparkserver100 is the master Spark node.

sparkserver100, sparkserver200,

3.6.7.1 Sample Run : The Script to run Top-10

# cat run_top10.sh
source /home/hadoop/conf/env_2.3.0.sh
export SPARK_HOME=/home/hadoop/spark-1.0.0
source /home/hadoop/spark_mahmoud_examples/spark_env_yarn.sh
source $SPARK_HOME/conf/spark-env.sh

67

# system jars:
CLASSPATH=$CLASSPATH:$HADOOP_HOME/etc/hadoop
jars=‘find $SPARK_HOME -name ’*.jar’‘
for j in $jars ; do

CLASSPATH=$CLASSPATH:$j

done

# app jar:
export CLASSPATH=/home/hadoop/spark_mahmoud_examples/mp.jar:$CLASSPATH
export SPARK_CLASSPATH=$CLASSPATH
export SPARK_MASTER=spark://sparkserver100:7077
OPTIONS="-Dsun.lang.ClassLoader.allowArraySyntax=true -Dspark.master=$SPARK_MASTER"
$JAVA_HOME/bin/java -cp $CLASSPATH $OPTIONS Top10 $SPARK_MASTER /top10/top10data.txt

3.6.7.2 Top-10 Run with Spark Cluster

Output id formatted to ﬁt the page style.

# ./run_top10.sh
hadoop@hnode01319:~/spark_mahmoud_examples# ./run_top10.sh
args[0]: <master>=spark://myserver100:7077
args[1]: <file>=/top10/top10data.txt
...
14/06/03 22:42:24 INFO scheduler.DAGScheduler: Completed ResultTask(0, 0)
14/06/03 22:42:24 INFO scheduler.TaskSchedulerImpl: Removed TaskSet 0.0,

whose tasks have all completed, from pool

14/06/03 22:42:24 INFO scheduler.DAGScheduler: Stage 0 (collect at Top10.java:69)

finished in 4.418 s

14/06/03 22:42:24 INFO spark.SparkContext: Job finished: collect at Top10.java:69,

took 4.521464436 s

value= 10
value= 1

key= cat10
key= cat1
key= cat10000 value= 10000
key= cat400
key= cat500
key= cat2
key= cat4
key= cat6
key= cat1200
key= cat10
key= cat11
key= cat12
key= cat13
key= cat50
key= cat51
key= cat45
key= cat46
key= cat200
key= cat234
14/06/03 22:42:24 INFO spark.SparkContext: Starting job: collect at Top10.java:116
14/06/03 22:42:24 INFO scheduler.DAGScheduler: Got job 1 (collect at Top10.java:116)

value= 400
value= 500
value= 2
value= 4
value= 6
value= 1200
value= 10
value= 11
value= 12
value= 13
value= 50
value= 51
value= 45
value= 46
value= 200
value= 234

with 1 output partitions (allowLocal=false)

14/06/03 22:42:24 INFO scheduler.DAGScheduler: Final stage: Stage 1(collect at Top10.java:116)
14/06/03 22:42:24 INFO scheduler.DAGScheduler: Parents of final stage: List()
14/06/03 22:42:24 INFO scheduler.DAGScheduler: Missing parents: List()
14/06/03 22:42:24 INFO scheduler.DAGScheduler: Submitting Stage 1

(MapPartitionsRDD[3] at mapPartitions at Top10.java:94), which has no missing parents

68

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

14/06/03 22:42:24 INFO scheduler.DAGScheduler: Submitting 1 missing tasks from Stage 1

(MapPartitionsRDD[3] at mapPartitions at Top10.java:94)

...
14/06/03 22:42:25 INFO scheduler.DAGScheduler: Stage 1

(collect at Top10.java:116) finished in 1.134 s
14/06/03 22:42:25 INFO scheduler.TaskSchedulerImpl:

Removed TaskSet 1.0, whose tasks have all completed, from pool

14/06/03 22:42:25 INFO spark.SparkContext: Job finished:

collect at Top10.java:116, took 1.15125893 s

45--cat45
46--cat46
50--cat50
51--cat51
200--cat200
234--cat234
400--cat400
500--cat500
1200--cat1200
10000--cat10000

3.7 What If for Top-N

In MapReduce/Hadoop implementation, we were able to parameterize N,
where we could ﬁnd Top-10, Top-20, or Top-100. How do we parameterize N
in Spark. It is easy to do this in Spark. We can make N as a global shared
data and then be able to access it from any cluster node. This is how we do
it:

import org.apache.spark.broadcast.Broadcast;
import org.apache.spark.api.java.JavaSparkContext;
...
int topN = <any-integer-number-greater-than-zero>;
...
JavaContextObject context = <create-acontext-object>;
...
final Broadcast<Integer> broadcastTopN = context.broadcast(topN);

RDD.map() {
...
final int topN = broadcastTopN.value();
// use topN
...

}

RDD.groupBy() {

...
final int topN = broadcastTopN.value();
// use topN

69

...

21

22

}

3.7.1 Shared Data Structures Deﬁnition and Usage

• Lines 1-2:

import required classes. The Broadcast class enable us
to deﬁne global shared data structures and then read them from any
cluster node within mappers, reducers, and transformers. The general
format to deﬁne a shared data structure of type T is:

T t = <create-data-structure-of-type-T>;
Broadcast<T> broadcastT = context.broadcast(t);

After a data structure (broadcastT is bradcasted, then it may be read
from any cluster node within mappers, reducers, and transformers.

• Line 4: deﬁne your top-N as top-10, top-20, or top-100

• Line 6: create an instance of JavaContextObject

• Line 8: deﬁne a global shared data structure for topN (which can be

any value)

• Line 12, 19: read and use a global shared data structure for topN (from
any cluster node). The general format to read a shared data structure
of type T is:

T t = broadcastT.value();

3.8 What If for Bottom-N

What if we want to ﬁnd Top-N or Bottom-N. This can be achieved by another
parameter, which can be shared among all cluster nodes. For this, we in-
troduce another shared variable, called direction, which can be in {"top",
"bottom"}. This is how we do it:

70

1

2

3

4

5

6

7

8

9

10

11

1

2

3

4

5

6

7

8

9

import org.apache.spark.broadcast.Broadcast;
import org.apache.spark.api.java.JavaSparkContext;
...
final int N = <any-integer-number-greater-than-zero>;
...
JavaContextObject context = <create-acontext-object>;
...
String direction = "top"; // or "bottom"
...
final Broadcast<Integer> broadcastN = context.broadcast(N);
final Broadcast<String> broadcastDirection = context.broadcast(direction);

Now, based on the value of broadcastDirection, we will either remove
the ﬁrst entry (when direction is equal to ”top”) or last entry (when direction
is equal to ”bottom”): this has to be done consistently to all code.

String direction = broadcastDirection.value();
if (direction.equals("top")) {

// remove element with the smallest frequency
finalN.remove(finalN.firstKey());

}
else {

// direction.equals("bottom")
// remove element with the largest frequency
finalN.remove(finalN.lastKey());

10

}

3.9 Spark Implementation : Non-Unique Keys

For this implementation, we assume that for all given (K, V) pairs, K’s are
not unique. Since our K’s are not unique, we have to do some extra steps
to make sure that our kyes are unique before applying the top-10 algorithm.
To undestand the solution for non-unique keys, I provide a simple example.
Let’s assume that we want to ﬁnd top-10 visited URLs for a web site. Further
assume that we have 3 seb servers (web-server-1. web-server-2, and web-
server-3) and each web server has collected URLs in this form:

(URL, count)

71

To further understand the non-unique keys concept, let’s assume that we
have only 7 URLs : {A, B, C, D, E, F, G} and the following are tallies of
URLs generated per web server:

(K,V) Per Web Server
Web Server 1 Web Server 2 Web Server 3
(A, 1)
(B, 1)
(C, 3)
(E, 1)
(F, 1)
(G, 2)

(A, 2)
(B, 2)
(C, 3)
(D, 2)
(E, 1)
(G, 2)

(A, 2)
(B, 2)
(C, 1)
(D, 2)
(E, 1)
(F, 1)
(G, 2)

Let’s assume that we want to get top-2 of all visited URLs. If we get local
top-2 per each web server and then get the top-2 of all three local top-2’s, the
result will not be correct. The reason is that URLs are not unique among all
web servers. To make a correct solution, ﬁrst we create unique URLs from
all input and then we partition unique URLs into M > 0 partitions. Next we
get the local top-2 per partition and ﬁnally we perform ﬁnal top-2 amng all
local top-2’s. For our example, the generated unique URLs will be:

Aggregated/Reduced (K,V) Pairs
(A, 5)
(B, 5)
(C, 7)
(D, 4)
(E, 3)
(F, 2)
(G, 6)

Now assume that we partition all unique URLs into two partitions:

(K,V) Per Partition
Partition-1 Partition-2

(A, 5)
(B, 4)
(C, 7)

(D, 4)
(E, 3)
(F, 2)
(G, 6)

72

To ﬁnd Top-2 of all data:

top-2(Partition-1) = { (C, 7), (A, 5) }
top-2(Partition-2) = { (G, 6), (D, 4) }
top-2(Partition-1, Partition-2) = { (C, 7), (G, 6) }

So the main point is that before ﬁnding Top-N of any set of (K,V) pairs, we
have to make sure that all K’s are unique.

For Top-10 design pattern, we provide Spark/Hadoop implementation with
the assumption that all K’s are non-unique. Our top-N algorithm (only main
steps) is presented below:

• MAIN-STEP-1: Make all your K’s unique. To make K’s unique, we
will map our input into JavaPairRDD<K, V> and then reduceByKey():
this will provide us unique K’s.

• MAIN-STEP-2: Partition all unique (K, V) pairs into M partitions.

• MAIN-STEP-3: Find Top-N for each partition (call this a local top-N)

• MAIN-STEP-4: Find Top-N from all local top-N’s

The Top-10 algorithm for non-unique keys is presented below.

3.9.1 Complete Spark Solution for Top-10 Pattern

First, I will present all high-level steps and then will expand each step. We
use a single Java class (represented as Top10NonUnique.java) for solving
Top-10 in Spark. Note that this solution is a general solution and it really
does not matter if all key’s are unique or not. One of the steps for this
solution is to make sure that all keys’s are unique.

Listing 3.11: Top10NonUnique Program in Spark

1 package org.dataalgorithms.chap03;
2 // STEP-0: import required classes and interfaces
3 /**
4

* Assumption: for all input (K, V), K’s are non-unique.
* This class implements Top-N design pattern for N > 0.
* The main assumption is that for all input (K, V)’s, K’s

5

6

73

Figure 3.2: Top-10 MapReduce Algorithm: for Non-Unique Keys

74

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

If we find duplicate K’s, then

Top-10 Design Pattern: Top Ten Structure

* are non-unique. It means that you may find entries like
* (A, 2), ..., (A, 5),....
* we will sum up the values for them and then create a unique
* K. If we have (A, 2) and (A, 5) then a unique entry will
* be created as (A, 7).
*
* This class may be used to find bottom-N as well (by
* just keeping N-smallest elements in the set.
*
*
*
*
*
*
*
*
*
*
* @author Mahmoud Parsian
*
*/

3. partition (K,V)’s into P partitions
4. Find top-N for each partition (we call this a local Top-N)
5. Find Top-N from all local Top-N’s

1. map(input) => (K, V)
2. reduce(K, List<V1, V2, ..., Vn>) => (K, V),

where V = V1+V2+...+Vn; now all K’s are unique

27
28 public class Top10NonUnique {
29

public static void main(String[] args) throws Exception {

handle input parameters
create a Java Spark Context object
broadcast the topN to all cluster nodes
create an RDD from input
partition RDD
map input (T) into (K,V) pair
reduce frequent K’s
create a local top-N
find a final top-N

// STEP-1:
// STEP-2:
// STEP-3:
// STEP-4:
// STEP-5:
// STEP-6:
// STEP-7:
// STEP-8:
// STEP-9:
// STEP-10: emit final top-N
System.exit(0);

30

31

32

33

34

35

36

37

38

39

40

}

41
42 }

3.9.1.1

Input

Sample input is provided. We use this HDFS input to print out output for
each step. As you can observe, the keys are non-unique. Before applying the
top-10 algorithm, unique keys will be generated.

1

2

3

4

5

6

7

8

9

# hadoop fs -ls /top10/top10input/
Found 3 items
-rw-r--r--
-rw-r--r--
-rw-r--r--

3 hadoop hadoop
3 hadoop hadoop
3 hadoop hadoop

24 2014-08-31 12:50 /top10/top10input/file1.txt
24 2014-08-31 12:50 /top10/top10input/file2.txt
28 2014-08-31 12:50 /top10/top10input/file3.txt

# hadoop fs -cat /top10/top10input/file1.txt
A,2
B,2

75

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

C,3
D,2
E,1
G,2

# hadoop fs -cat /top10/top10input/file2.txt
A,1
B,1
C,3
E,1
F,1
G,2

# hadoop fs -cat /top10/top10input/file3.txt
A,2
B,2
C,1
D,2
E,1
F,1
G,2

Listing 3.12: STEP-0: import required classes and interfaces

1 // STEP-0: import required classes and interfaces
2 import org.dataalgorithms.util.SparkUtil;
3
4 import scala.Tuple2;
5 import org.apache.spark.api.java.JavaRDD;
6 import org.apache.spark.api.java.JavaPairRDD;
7 import org.apache.spark.api.java.JavaSparkContext;
8 import org.apache.spark.api.java.function.FlatMapFunction;
9 import org.apache.spark.api.java.function.PairFunction;
10 import org.apache.spark.api.java.function.Function2;
11 import org.apache.spark.broadcast.Broadcast;
12
13 import java.util.List;
14 import java.util.Map;
15 import java.util.TreeMap;
16 import java.util.SortedMap;
17 import java.util.Iterator;
18 import java.util.Collections;

3.9.1.2 STEP-1: handle input parameters

Listing 3.13: STEP-1: handle input parameters

76

1 // STEP-1: handle input parameters
2 if (args.length < 3) {
// Spark master URL:
3
format:
//
//
example:
System.err.println("Usage: Top10 <spark-master-URL> <input-path> <topN>");
System.exit(1);

spark://<spark-master-host-name>:7077
spark://myserver00:7077

6

5

4

7
8 }
9 System.out.println("args[0]: <spark-master-URL>="+args[0]);
10 System.out.println("args[1]: <input-path>="+args[1]);
11 System.out.println("args[2]: <topN>="+args[2]);
12 final int N = Integer.parseInt(args[2]);

3.9.1.3 STEP-2: create a Java Spark Context object

Listing 3.14: STEP-2: create a Java Spark Context object

1 // STEP-2: create a Java Spark Context object
2 // args[0] denotes a Spark Master URL
3 JavaSparkContext ctx = SparkUtil.createJavaSparkContext(args[0], "Top10");

3.9.1.4 STEP-3: broadcast the topN to all cluster nodes

To broadcast or share objects and data structures among all cluster nodes,
you may use Spark’s Broadcast class.

Listing 3.15: STEP-3: broadcast the topN to all cluster nodes

1 // STEP-3: broadcast the topN to all cluster nodes
2 final Broadcast<Integer> topN = ctx.broadcast(N);
3 // now topN is available to be read from all cluster nodes

3.9.1.5 STEP-4: create an RDD from input

Input data is read from HDFS and the ﬁrst RDD is created.

Listing 3.16: STEP-4: create an RDD from input

1 // STEP-4: create an RDD from input
input record format:
2 //
3 //
4 JavaRDD<String> lines = ctx.textFile(args[1], 1);
5 lines.saveAsTextFile("/output/1");

<string-key><,><integer-value-count>

77

To debug STEP-4, the ﬁrst RDD is printed out:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

# hadoop fs -cat /output/1/part*
A,2
B,2
C,3
D,2
E,1
G,2
A,1
B,1
C,3
E,1
F,1
G,2
A,2
B,2
C,1
D,2
E,1
F,1
G,2

3.9.1.6 STEP-5: partition RDD

Partitioning RDD is an art and science. What is the right number of par-
titions? There is no magic bullet formula for calculating the number of
partitions. This does depend on the number of cluster nodes, the number of
cores per server, and the size of RAM available. My experience indicate that
you need to set this by trial and experience.

Listing 3.17: STEP-5: partition RDD

1 // STEP-5: partition RDD
2 // public JavaRDD<T> coalesce(int numPartitions)
3 // Return a new RDD that is reduced into numPartitions partitions.
4 JavaRDD<String> rdd = lines.coalesce(9);

3.9.1.7 STEP-6: map input(T) into (K,V) pair

it converts every input record into a (K,V)
This step does basic mapping:
pair, where K is a ”key such as URL” and V is a ”value such as count”. This
step will generate duplicate keys.

78

Listing 3.18: STEP-6: map input(T) into (K,V) pair

1 // STEP-6: map input(T) into (K,V) pair
2 // PairFunction<T, K, V>
3 // T => Tuple2<K, V>
4 JavaPairRDD<String,Integer> kv = rdd.mapToPair(new PairFunction<String,String,Integer>() {
5

public Tuple2<String,Integer> call(String s) {
String[] tokens = s.split(","); // url,789
return new Tuple2<String,Integer>(tokens[0], Integer.parseInt(tokens[1]));

6

7

}

8
9 });
10 kv.saveAsTextFile("/output/2");

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

# hadoop fs -cat /output/2/part*
(A,2)
(B,2)
(C,3)
(D,2)
(E,1)
(G,2)
(A,1)
(B,1)
(C,3)
(E,1)
(F,1)
(G,2)
(A,2)
(B,2)
(C,1)
(D,2)
(E,1)
(F,1)
(G,2)

3.9.1.8 STEP-7: reduce frequent Keys

Previos step (STEP-6) generated duplicate keys. This step creates unique
keys and aggregates the associated values. For example, if for a key K we
have:

Then, these will be aggregated/reduced into a (K,V) where

{(K, V1), (K, V2), ..., (K, Vn)}

V = (V1 + V2 + ... + Vn)

The reducer is implemented by JavaPairRDD.reduceByKey().

79

Listing 3.19: STEP-7: reduce frequent Keys

1 // STEP-7: reduce frequent K’s
2 JavaPairRDD<String, Integer> uniqueKeys =
3

kv.reduceByKey(new Function2<Integer, Integer, Integer>() {
public Integer call(Integer i1, Integer i2) {

4

5

return i1 + i2;

}

6
7 });
8 uniqueKeys.saveAsTextFile("/output/3");

1

2

3

4

5

6

7

8

# hadoop fs -cat /output/3/part*
(B,5)
(E,3)
(C,7)
(F,2)
(G,6)
(A,5)
(D,4)

3.9.1.9 STEP-8: create a local top-N

The goal of this step is to create a local top-10 per partition.

Listing 3.20: STEP-8: create a local top-N

1 // STEP-8: create a local top-N
2 JavaRDD<SortedMap<Integer, String>> partitions = uniqueKeys.mapPartitions(
3

new FlatMapFunction<Iterator<Tuple2<String,Integer>>, SortedMap<Integer, String>>() {
@Override
public Iterable<SortedMap<Integer, String>> call(Iterator<Tuple2<String,Integer>> iter) {

4

5

6

7

8

9

10

11

12

13

14

15

16

17

final int N = topN.value();
SortedMap<Integer, String> localTopN = new TreeMap<Integer, String>();
while (iter.hasNext()) {

Tuple2<String,Integer> tuple = iter.next();
localTopN.put(tuple._2, tuple._1);
// keep only top N
if (localTopN.size() > N) {

// remove element with the smallest frequency
localTopN.remove(localTopN.firstKey());

}

}
return Collections.singletonList(localTopN);

}

18
19 });
20 partitions.saveAsTextFile("/output/4");

1

2

hadoop@hnode01319:~# hadoop fs -ls /output/4/

80

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

Found 4 items
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--

3 hadoop hadoop
3 hadoop hadoop
3 hadoop hadoop
3 hadoop hadoop

0 2014-08-31 13:11 /output/4/_SUCCESS
11 2014-08-31 13:11 /output/4/part-00000
11 2014-08-31 13:11 /output/4/part-00001
11 2014-08-31 13:11 /output/4/part-00002

# hadoop fs -cat /output/4/part-00000
{3=E, 5=B}

# hadoop fs -cat /output/4/part-00001
{2=F, 7=C}

# hadoop fs -cat /output/4/part-00002
{5=A, 6=G}

# hadoop fs -cat /output/4/part*
{3=E, 5=B}
{2=F, 7=C}
{5=A, 6=G}

3.9.1.10 STEP-9: ﬁnd a ﬁnal top-N

This step accepts all local top-10’s and generates the ﬁnal top-10 list.

Listing 3.21: STEP-9: ﬁnd a ﬁnal top-N

1 // STEP-9: find a final top-N
2 SortedMap<Integer, String> finalTopN = new TreeMap<Integer, String>();
3 List<SortedMap<Integer, String>> allTopN = partitions.collect();
4 for (SortedMap<Integer, String> localTopN : allTopN) {
5

for (Map.Entry<Integer, String> entry : localTopN.entrySet()) {

// count = entry.getKey()
// url = entry.getValue()
finalTopN.put(entry.getKey(), entry.getValue());
// keep only top N
if (finalTopN.size() > N) {

finalTopN.remove(finalTopN.firstKey());

}

6

7

8

9

10

11

12

}

13
14 }

3.9.1.11 STEP-10: emit ﬁnal top-N

This step emits the ﬁnal output on the standard output device.

Listing 3.22: STEP-10: emit ﬁnal top-N

81

1 // STEP-10: emit final top-N
2 System.out.println("--- Top-N List ---");
3 System.out.println("------------------");
4 for (Map.Entry<Integer, String> entry : finalTopN.entrySet()) {
5
6 }

System.out.println("key="+ entry.getValue() +" value = " +entry.getKey());

1

2

3

4

--- Top-N List ---
------------------
key=G value=6
key=C value=7

3.9.1.12 Shell Script To Run Spark Program

Listing 3.23: Shell Script To Run Spark Program

1 # cat ./run_top10_nonunique.sh
2 #!/bin/bash
3 source /home/hadoop/conf/env_2.5.0.sh
4 export SPARK_HOME=/home/hadoop/spark-1.0.2
5 source /home/hadoop/spark_mahmoud_examples/spark_env_yarn.sh
6 source $SPARK_HOME/conf/spark-env.sh
7
8 # system jars:
9 CLASSPATH=$CLASSPATH:$HADOOP_HOME/etc/hadoop
10 jars=‘find $SPARK_HOME -name ’*.jar’‘
11 for j in $jars ; do
12
13 done
14
15 # app jar:
16 export CLASSPATH=/home/hadoop/spark_mahmoud_examples/mp.jar:$CLASSPATH
17 export SPARK_CLASSPATH=$CLASSPATH
18 export SPARK_MASTER=spark://myserver100:7077
19 OPTIONS="-Dsun.lang.ClassLoader.allowArraySyntax=true -Dspark.master=$SPARK_MASTER"
20 export INPUT=/top10/top10input
21 export topN=2
22 $JAVA_HOME/bin/java -cp $CLASSPATH $OPTIONS

CLASSPATH=$CLASSPATH:$j

Top10NonUnique $SPARK_MASTER $INPUT $topN

3.9.1.13 Sample Run

Output is trimmed and edited to ﬁt the page. For this run, the Spark cluster
had 3 server nodes: {myserver100, myserver200, myserver300}.

82

Listing 3.24: Sample Run

1 # ./run_top10_nonunique.sh
2 args[0]: <spark-master-URL>=spark://myserver100:7077
3 args[1]: <input-path>=/top10/top10input
4 args[2]: <topN>=2
5 ...
6 INFO : Total input paths to process : 3
7 INFO : Starting job: saveAsTextFile at Top10NonUnique.java:73
8 INFO : Got job 0 (saveAsTextFile at Top10NonUnique.java:73) with
9

3 output partitions (allowLocal=false)

Top10NonUnique.java:89)

at Top10NonUnique.java:92)

which has no missing parents

which has no missing parents

10 INFO : Final stage: Stage 0(saveAsTextFile at Top10NonUnique.java:73)
11 ...
12 INFO : Starting task 0.0:0 as TID 0 on executor 4: myserver100 (PROCESS_LOCAL)
13 INFO : Serialized task 0.0:0 as 13682 bytes in 4 ms
14 ...
15 INFO : Submitting Stage 1 (MappedRDD[5] at saveAsTextFile at Top10NonUnique.java:89),
16
17 INFO : Submitting 3 missing tasks from Stage 1 (MappedRDD[5] at saveAsTextFile at
18
19 INFO : Adding task set 1.0 with 3 tasks
20 INFO : Starting task 1.0:0 as TID 3 on executor 7: myserver300 (NODE_LOCAL)
21 INFO : Serialized task 1.0:0 as 14119 bytes in 1 ms
22 INFO : Starting task 1.0:2 as TID 4 on executor 5: myserver200 (NODE_LOCAL)
23 INFO : Serialized task 1.0:2 as 14119 bytes in 0 ms
24 INFO : Starting task 1.0:1 as TID 5 on executor 3: myserver100 (NODE_LOCAL)
25 INFO : Serialized task 1.0:1 as 14119 bytes in 1 ms
26 INFO : Completed ResultTask(1, 0)
27 ...
28 INFO : Submitting Stage 3 (MapPartitionsRDD[6] at reduceByKey at Top10NonUnique.java:92),
29
30 INFO : Submitting 3 missing tasks from Stage 3 (MapPartitionsRDD[6] at reduceByKey
31
32 INFO : Adding task set 3.0 with 3 tasks
33 INFO : Starting task 3.0:0 as TID 6 on executor 1: myserver300 (NODE_LOCAL)
34 INFO : Serialized task 3.0:0 as 2537 bytes in 1 ms
35 INFO : Starting task 3.0:1 as TID 7 on executor 4: myserver100 (NODE_LOCAL)
36 INFO : Serialized task 3.0:1 as 2537 bytes in 1 ms
37 INFO : Starting task 3.0:2 as TID 8 on executor 8: myserver200 (NODE_LOCAL)
38 INFO : Serialized task 3.0:2 as 2537 bytes in 0 ms
39 INFO : Finished TID 7 in 109 ms on myserver100 (progress: 1/3)
40 ...
41 INFO : Completed ResultTask(4, 0)
42 INFO : Finished TID 12 in 244 ms on myserver100 (progress: 1/3)
43 INFO : Completed ResultTask(4, 2)
44 INFO : Finished TID 14 in 304 ms on myserver200 (progress: 2/3)
45 INFO : Completed ResultTask(4, 1)
46 INFO : Finished TID 13 in 362 ms on myserver100 (progress: 3/3)
47 ...
48 INFO : Adding task set 6.0 with 3 tasks
49 ...
50 INFO : Completed ResultTask(6, 1)
51 INFO : Finished TID 16 in 60 ms on myserver300 (progress: 3/3)
52 INFO : Removed TaskSet 6.0, whose tasks have all completed, from pool
53 INFO : Stage 6 (collect at Top10NonUnique.java:121) finished in 0.062 s
54 INFO : Job finished: collect at Top10NonUnique.java:121, took 0.076470196 s
55 --- Top-N List ---
56 ------------------
57 key=G value=6
58 key=C value=7

83

Chapter 4

Left Outer Join in MapReduce

4.1

Introduction

The purpose of the is chapter is to show how to implement a Left Outer
Join in MapReduce environment. To solve Left Outer Join, we provide
three distinct implementations in MapReduce/Hadoop and Spark/Hadoop:

• MapReduce/Hadoop solution using map() and reduce() functions

• Spark/Hadoop solution without using built-in JavaPairRDD.leftOuterJoin()

• Spark/Hadoop solution using built-in JavaPairRDD.leftOuterJoin()

Consider a company such as Amazon, which has over 200 millions of users
and possibly can do hundreds of millions of transactions per day. To show the
concept of Left Outer Join, assume we have two types of data: users and
transations: where users’ data has user’s ”location” (say location_id) in-
formation and transactions has ”user” (say user_id) information, but trans-
actions do not have direct information about user’s locations. Given users
and transactions:

users(user_id, location_id)
transactions(transaction_id, product_id, user_id, quantity, amount)

84

the goal is to ﬁnd the number of unique locations in which each product

has been sold.

What is a Left Outer Join? Let T1 (be a left table) and T2 (be a right
table) be two relations deﬁned as (where t1 are attributes of T1 and t2 are
attributes of T2):

T1 = (K, t1)
T2 = (K, t2)
Then the result of a left outer join for relations T1 and T2 on join key of K
contains all records of the ”left” table (T1), even if the join-condition does
not ﬁnd any matching record in the ”right” table (T2).
If the ON clause
with key K matches 0 (zero) records in T2 (for a given record in T1), the join
will still return a row in the result (for that record)— but with NULL in
each column from T2. A left outer join returns all the values from an inner
join plus all values in the left table that do not match to the right table.
Formally, we can express this as:

LeftOuterJoin(T1, T2, K) = {(k, t1, t2) where k ∈ T1.K and k ∈ T2.K}

∪
{(k, t1, null) where k ∈ T1.K and k (cid:54)∈ T2.K}

In SQL, we can express Left Outer Join as (where K is the column where
T1 and T2 are joined on):

SELECT field_1, field_2, ...

FROM T1 LEFT OUTER JOIN T2

ON T1.K = T2.K;

Left Outer Join can be visually expressed as (the colored part is included
and the part with white color is excluded):

Consider the following values for our users and transactions (note that
these values are just examples to demonstrate the concept of Left Outer
Join in MapReduce environment):

85

Figure 4.1: Left Out Join Illustration

86

Users Table

user_id
u1
u2
u3
u4
u5

location_id
UT
GA
CA
CA
GA

transaction_id
t1
t2
t3
t4
t5
t6
t7
t8

Transactions Table
user_id
u1
u2
u1
u2
u4
u1
u1
u5

product_id
p3
p1
p1
p2
p4
p1
p4
p4

quantity
1
1
1
1
1
1
1
2

amount
300
100
100
10
9
100
9
40

Here are some SQL queries to answer our questions:

• ﬁnd all products (and associated location) sold [Query-1]

mysql> SELECT product_id, location_id

-> FROM transactions LEFT OUTER JOIN users
->

ON transactions.user_id = users.user_id;

+------------+-------------+
| product_id | location_id |
+------------+-------------+
|
| p3
|
| p1
|
| p1
|
| p2
|
| p4
|
| p1
|
| p4
| p4
|
+------------+-------------+
8 rows in set (0.00 sec)

| UT
| GA
| UT
| GA
| CA
| UT
| UT
| GA

87

• ﬁnd all products (and associated location counts) sold [Query-2]

mysql> SELECT product_id, count(location_id)

-> FROM transactions LEFT OUTER JOIN users
->
->

ON transactions.user_id = users.user_id
group by product_id;

+------------+--------------------+
| product_id | count(location_id) |
+------------+--------------------+
3 |
| p1
1 |
| p2
| p3
1 |
3 |
| p4
+------------+--------------------+
4 rows in set (0.00 sec)

|
|
|
|

• ﬁnd all products (and unique location counts) sold [Query-3]

mysql> SELECT product_id, count(distinct location_id)

-> FROM transactions LEFT OUTER JOIN users
->
->

ON transactions.user_id = users.user_id
group by product_id;

+------------+-----------------------------+
| product_id | count(distinct location_id) |
+------------+-----------------------------+
2 |
| p1
1 |
| p2
1 |
| p3
| p4
3 |
+------------+-----------------------------+
4 rows in set (0.00 sec)

|
|
|
|

88

4.2

Implementation of Left Outer Join in MapRe-
duce

The desired output we are looking is provided by SQL Query-3, which ﬁnds
all number of distinct (unique) locations in which each product has been sold
for given all transactions. We present solution for Left Outer Join in two
steps:

• MapReduce Phase-1: ﬁnd all products (and associated locations) sold.

The answer to Phase-1 is using SQL Query-1.

• MapReduce Phase-2: ﬁnd all products (and associated unique location

counts) sold. The answer to Phase-2 is using SQL Query-3.

4.2.1 MapReduce Phase-1

This phase will perform ”left outer join” operation with a MapReduce job,
which will utilize two mappers (one for users and the other one for transac-
tions) and reducer will emit (Key,Value) with Key = product_id, and Value
= location_id. Using multiple mappers is enabled by the MultipleInputs1
class (note that if we had a single mapper, then we would have used Job.setMapperClass()):

Job job = new Job(...);
...
Path transactions = <hdfs-path-to-transactions-data>;
Path users = <hdfs-path-to-users-data>;

MultipleInputs.addInputPath(job,

transactions,
TextInputFormat.class,
TransactionMapper.class);

MultipleInputs.addInputPath(job,

users,
TextInputFormat.class,
UserMapper.class);

1 org.apache.hadoop.mapreduce.lib.input.MultipleInputs

89

Figure 4.2: Left Outer Join Data Flow – Phase I

The following Figures illustrates the working MapReduce ﬂow of Left
Outer Join algorithm, which consists of two MapReduce jobs (labeled as
Phase I and Phase II).

Transaction Mapper [VERSION-1] : the transaction map() reads (transaction_id,
product_id, user_id, quantity, amount) and emits (key=user_id, value=product_id).

User Mapper [VERSION-1] : the user map() reads (user_id, location_id)
and emits (key=user_id, value=location_id).

The reducer for Phase-1 [VERSION-1] , gets both user’s location_id and
product_id and emits (key=product_id, value=location_id). Now, the
question is how the reducer will identify location_id from product_id? In
Hadoop, the order of reducer values is undeﬁned. Therefore, the reducer

90

Figure 4.3: Left Outer Join Data Flow – Phase II

91

for a speciﬁc Key=user_id has no clue how to process the values. To rem-
edy this problem we modify Transaction and User mappers/reducers (call it
VERSION-2):

Transaction Mapper [VERSION-2] : the transaction map() reads (transaction_id,
product_id, user_id, quantity, amount) and emits (key=Pair(user_id,
2), value=Pair(”P”, product_id). By adding a number ”2” to the reducer
key, we will guarantee that product_id(s) arrive at the end. This will be
accomplished by ”secondary sorting” technique. We added ”P” to the value
to identify products. In Hadoop, for implementation of Pair(String, String),
we will use the PairOfStrings2 class.

4.2.1.1 Transaction Mapper [VERSION-2]

Listing 4.1: Transaction Mapper [VERSION-2]

1 /**
2 * @param key is framework generated, ignored here
3 * @param value is the transaction_id<TAB>product_id<TAB>user_id<TAB>quantity<TAB>amount
4 */
5 map(key, value) {
6

String[] tokens = StringUtil.split(value, "\t");
String productID = tokens[1];
String userID = tokens[2];
outputKey = Pair(userID, 2);
outputValue = Pair("P", productID);
emit(outputKey, outputValue);

7

8

9

10

11
12 }

User Mapper [VERSION-2] : the user map() reads (user_id, location_id)
and emits (key=Pair(user_id, 1), value=Pair(”L”, location_id)). By adding
a number ”1” to the reducer key, we will guarantee that location_id(s) ar-
rive ﬁrst. This will be accomplished by ”secondary sorting” technique. We
added ”L” to the value to identify locations.

2

edu.umd.cloud9.io.pair.PairOfStrings

(which

implements

WritableComparable<PairOfStrings>)

92

4.2.1.2 User Mapper [VERSION-2]

Listing 4.2: User Mapper [VERSION-2]

1 /**
2 * @param key is framework generated, ignored here
3 * @param value is the user_id<TAB>location_id
4 */
5 map(key, value) {
6

String[] tokens = StringUtil.split(value, "\t");
String userID = tokens[0];
String locationID = tokens[1];
outputKey = Pair(userID, 1); // make sure location shows before products
outputValue = Pair("L", locationID);
emit(outputKey, outputValue);

The reducer for Phase-1 [VERSION-2] , gets both Pair(”L”, location_id)
and Pair(”P”, product_id) and emits (key=product_id, value=location_id).
Note that since 1 < 2, it means that user’s location_id arrives ﬁrst.

4.2.1.3 The reducer for Phase-1 [VERSION-2]

Listing 4.3: The reducer for Phase-1 [VERSION-2]

1 /**
2 * @param key is user_id
3 * @param values is List<Pair<left, right>>, where
4 * values = List<{Pair<"L", locationID>, Pair<"P", productID1>, Pair<"P", productID2>, ...}
5 * NOTE that, the Pair<"L", locationID> arrives before all product pairs.
6 * The first value is location, if it’s not, then we don’t have a user record,
7 * so we’ll set the locationID as "undefined"
8 */
9 reduce(key, values) {
10

locationID = "undefined";
for (Pair<left, right> value: values) {

// the following if-stmt will be true
// once at the first iteration
if (value.left.equals("L")) {

locationID = value.right;

93

7

8

9

10

11
12 }

11

12

13

14

15

continue;

}

// here we have a product: value.left.equals("P")
productID = value.right;
emit(productID, locationID);

16

17

18

19

20

21

}

22
23 }

4.2.2 MapReduce Phase-2: Counting Unique Locations

This phase will use output of Phase-1 (which is a sequence of pairs of
(product_id, location_id) and generates pairs of (product_id, number_of_unique_locations).
The mapper for this phase is an identity mapper and the reducer will count
the number of unique locations (by using a Set data structure) per product.

4.2.2.1 Mapper Phase-2: Counting Unique Locations

Listing 4.4: Mapper Phase-2: Counting Unique Locations

1 /**
2 * @param key is product_id
3 * @param value is location_id
4 */
5 map(key, value) {
6
7 }

emit(key, value);

4.2.2.2 Reducer Phase-2: Counting Unique Locations

Listing 4.5: Reducer Phase-2: Counting Unique Locations

1 /**
2 * @param key is product_id
3 * @param values is List<location_id>
4 */
5 reduce(key, values) {

94

Set<String> set = new HashSet<String>();
for (String locationID : values) {

set.add(locationID);

}

int uniqueLocationsCount = set.size();
emit(key, uniqueLocationsCount);

6

7

8

9

10

11

12
13 }

4.2.3

Implementation Classes in Hadoop

Implementation Classes in Hadoop

Phase

Phase-1

Phase-2

Class Name
Class Description
LeftJoinDriver
Dirver to submit job for Phase-1
LeftJoinReducer
Left Join Reducer
LeftJoinTransactionMapper
Left Join transaction mapper
LeftJoinUserMapper
Left Join user mapper
How to partition natural keys
SecondarySortPartitioner
SecondarySortGroupComparator How to group by natural key
LocationCountDriver
LocationCountMapper
LocationCountReducer

Dirver to submit job for Phase-2
Deﬁne map() for location count
Deﬁne reduce() for location count

4.3 Sample Run

4.3.1

Input for Phase-1

# hadoop fs -cat /left_join/zbook/users/users.txt
u1 UT
u2 GA
u3 CA
u4 CA
u5 GA

# hadoop fs -cat /left_join/zbook/transactions/transactions.txt
t1 p3 u1 3 330

95

t2 p1 u2 1 400
t3 p1 u1 3 600
t4 p2 u2 10 1000
t5 p4 u4 9 90
t6 p1 u1 4 120
t7 p4 u1 8 160
t8 p4 u5 2 40

4.3.2

run Phase-1

# ./run_phase1_left_join.sh
...
13/12/29 21:17:48 INFO input.FileInputFormat: Total input paths to process : 1
...
13/12/29 21:17:48 INFO input.FileInputFormat: Total input paths to process : 1
13/12/29 21:17:49 INFO mapred.JobClient: Running job: job_201312291929_0004
13/12/29 21:17:50 INFO mapred.JobClient: map 0% reduce 0%
13/12/29 21:17:55 INFO mapred.JobClient: map 100% reduce 0%
13/12/29 21:18:03 INFO mapred.JobClient: map 100% reduce 6%
13/12/29 21:18:04 INFO mapred.JobClient: map 100% reduce 13%
...
13/12/29 21:18:39 INFO mapred.JobClient: map 100% reduce 86%
13/12/29 21:18:41 INFO mapred.JobClient: map 100% reduce 100%
13/12/29 21:18:41 INFO mapred.JobClient: Job complete: job_201312291929_0004
...
13/12/29 21:18:41 INFO mapred.JobClient:
13/12/29 21:18:41 INFO mapred.JobClient:
13/12/29 21:18:41 INFO mapred.JobClient:
...
13/12/29 21:18:41 INFO mapred.JobClient:
13/12/29 21:18:41 INFO mapred.JobClient:
13/12/29 21:18:41 INFO mapred.JobClient:
13/12/29 21:18:41 INFO mapred.JobClient:
13/12/29 21:18:41 INFO mapred.JobClient:

Reduce input records=13
Reduce input groups=5
Combine output records=0
Reduce output records=8
Map output records=13

Map output materialized bytes=328
Map input records=13

Map-Reduce Framework

96

4.3.3 View Output of Phase-1 (Input of Phase-2)

# hadoop fs -text /left_join/zbook/output/part*
p4 GA
p3 UT
p1 UT
p1 UT
p4 UT
p1 GA
p2 GA
p4 CA

4.3.4 Run Phase-2

# ./run_phase2_location_count.sh
...
13/12/29 21:19:28 INFO input.FileInputFormat: Total input paths to process : 10
13/12/29 21:19:28 INFO mapred.JobClient: Running job: job_201312291929_0005
13/12/29 21:19:29 INFO mapred.JobClient: map 0% reduce 0%
13/12/29 21:19:36 INFO mapred.JobClient: map 50% reduce 0%
...
13/12/29 21:20:22 INFO mapred.JobClient: map 100% reduce 86%
13/12/29 21:20:24 INFO mapred.JobClient: map 100% reduce 100%
13/12/29 21:20:25 INFO mapred.JobClient: Job complete: job_201312291929_0005
...
13/12/29 21:20:25 INFO mapred.JobClient:
13/12/29 21:20:25 INFO mapred.JobClient:
13/12/29 21:20:25 INFO mapred.JobClient:
...
13/12/29 21:20:25 INFO mapred.JobClient:
13/12/29 21:20:25 INFO mapred.JobClient:
13/12/29 21:20:25 INFO mapred.JobClient:
13/12/29 21:20:25 INFO mapred.JobClient:
13/12/29 21:20:25 INFO mapred.JobClient:

Reduce input records=8
Reduce input groups=4
Combine output records=0
Reduce output records=4
Map output records=8

Map output materialized bytes=664
Map input records=8

Map-Reduce Framework

97

4.3.5 View Output of Phase-2

# hadoop fs -cat /left_join/zbook/output2/part*
p1 2
p2 1
p3 1
p4 3

4.4 Spark Implementation

Since Spark provids a higher-level Java API than MapReduce/Hadoop API,
we will present the whole solution in a single Java class (called LeftOuterJoin),
which will include a series of map(), groupBy(), and reduce() functions. In
MapReduce/Hadoop implementation we used MultipleInputs class to pro-
cess two diﬀerent types of input by two diﬀerent mappers. Spark provides
a much richer API for mappers and reducers. Without a special plug-in
classes, you may have many diﬀerent types of mappers (by using map(),
flatMap(), and flatMapToPair() functions).
In Spark, instead of using
Hadoop’s MultipleInputs class, we will use JavaRDD.union() function to
return the union of two JavaRDDs (users RDD and transactions RDD), which
will be merged to create a new RDD. The JavaRDD.union() function is de-
ﬁned as:

JavaRDD<T> union(JavaRDD<T> other)
JavaPairRDD<T> union(JavaPairRDD<T> other)

Description: Return the union of this JavaRDD and another one.

Any identical elements will appear multiple
times (use .distinct() to eliminate them).

You can only apply the union() function to JavaRDD’s of the same type
(T). Therefore, we will create the same RDD type for users and transactions.
This is how we do it:

98

Figure 4.4: Union Data Flow

JavaPairRDD<String,Tuple2<String,String>> usersRDD = users.map(...);
JavaPairRDD<String,Tuple2<String,String>> transactionsRDD = transactions.map(...);

// here we perform a union() on usersRDD and transactionsRDD
JavaPairRDD<String,Tuple2<String,String>> allRDD = transactionsRDD.union(usersRDD);

The union() workﬂow is expressed in the following Figure.

To refresh our memory, here are the data for users and transactions (these
data will be used as input ﬁles for our sample run at the end of this chapter):

# hadoop fs -cat /data/leftouterjoins/users.txt
u1 UT
u2 GA
u3 CA
u4 CA
u5 GA

99

# hadoop fs -cat /data/leftouterjoins/transactions.txt
t1 p3 u1 3 330
t2 p1 u2 1 400
t3 p1 u1 3 600
t4 p2 u2 10 1000
t5 p4 u4 9 90
t6 p1 u1 4 120
t7 p4 u1 8 160
t8 p4 u5 2 40

This is how the algorithm works:

for users and transactions data we

generate (here T2 refers to Tuple2):

users => (userID, T2("L", location))
transactions => (userID, T2("P", product))

Next, we create a union of these data:

all = transactions.union(users);

= { (userID1, T2("L", location)),
(userID1, T2("P", P11)),
(userID1, T2("P", P12)),
...
(userID1, T2("P", P1n)),
...

}

where Pi is a productID

The next step is to group data by userID. This will generate:

{

(userID1, List<T2("L", L1), T2("P", P11), T2("P", P12), T2("P", P13), ...>),
(userID2, List<T2("L", L2), T2("P", P21), T2("P", P22), T2("P", P23), ...>),
...

100

}

where

Li is a locationID,
Pij is a productID.

4.4.1 Spark Program

First, I will provide a high-level solution in 10 steps, and then we will dissect
into each step with a proper working Spark code.

Listing 4.6: LeftOuterJoin High-Level Solution

1 // STEP-0: import required classes and interfaces
2 public class LeftOuterJoin {
3

public static void main(String[] args) throws Exception {

// STEP-1: Read Input Parameters
// STEP_2: Create JavaSparkContext object
// STEP-3: Create a JavaPairRDD for users
// STEP-4: Create a JavaPairRDD for transactions
// STEP-5: Create a union of RDD’s created by STEP-3 and STEP-4
// STEP-6: Create a JavaPairRDD(userID, List<T2>) by calling groupBy()
// STEP-7: Create a productLocationsRDD as JavaPairRDD<String,String>
// STEP-8: Find all locations for a product,
//
// STEP-9: Finalize output by changing "value" from List<String>
//
//
// STEP-10: Print the final result RDD
System.exit(0);

to Tuple2<Set<String>, Integer>, where you have unique
set of locations and their count.

result will be JavaPairRDD<String, List<String>>

4

5

6

7

8

9

10

11

12

13

14

15

16

17

}

18
19 }

4.4.2 STEP-0: Import Required Classes

We import required classes and interfaces from the JAR ﬁles provided by the
binary distributions of Spark framework. Spark provides two Java packages
(org.apache.spark.api.java and org.apache.spark.api.java.function)
for creating and manipulating RDDs.

Listing 4.7: STEP-0: import required classes and interfaces

101

1 // STEP-0: import required classes and interfaces
2 import scala.Tuple2;
3 import org.apache.spark.api.java.JavaRDD;
4 import org.apache.spark.api.java.JavaPairRDD;
5 import org.apache.spark.api.java.JavaSparkContext;
6 import org.apache.spark.api.java.function.Function;
7 import org.apache.spark.api.java.function.PairFlatMapFunction;
8 import org.apache.spark.api.java.function.FlatMapFunction;
9 import org.apache.spark.api.java.function.PairFunction;
10
11 import java.util.Set;
12 import java.util.HashSet;
13 import java.util.Arrays;
14 import java.util.List;
15 import java.util.ArrayList;
16 import java.util.Collections;

4.4.3 STEP-1: Read Input Parameters

We read 3 input parameters: ”spark master URL”, users data and transac-
tions data. Users and transaction data are provided as HDFS text ﬁles.

Listing 4.8: STEP-1: Read Input Parameters

if (args.length < 3) {

System.err.println("Usage: LeftOuterJoin <master> <users> <transactions>");
System.exit(1);

}

String sparkMaster = args[0]; // spark master URL
String usersInputFile = args[1]; // HDFS text file
String transactionsInputFile = args[2]; // HDFS text file
System.out.println("sparkMaster="+ sparkMaster);
System.out.println("users="+ usersInputFile);
System.out.println("transactions="+ transactionsInputFile);

1

2

3

4

5

6

7

8

9

10

11

The output of this step will be (myserver100 is the spark master server):

sparkMaster=spark://myserver100:7077
users=/data/leftouterjoins/users.txt
transactions=/data/leftouterjoins/transactions.txt

102

1

2

3

4

5

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

4.4.4 STEP-2: Create JavaSparkContext Object

A JavaSparkContext object is created by using spark master URL. This
object is used to create ﬁrst RDD.

Listing 4.9: STEP-2: Create JavaSparkContext Object

JavaSparkContext ctx = new JavaSparkContext(

sparkMaster,
"MyJavaWordCount",
System.getenv("SPARK_HOME"),
System.getenv("SPARK_EXAMPLES_JAR"));

4.4.5 STEP-3: Create a JavaPairRDD for Users

First, we create a users JavaRDD<String>, where RDD element is a sin-
gle record of text ﬁle (representing userID and locationID). Next, we use
JavaRDD<String>.mapToPair() function to create a new JavaPairRDD<String,Tuple2<String,String>>,
where key is a userID and value is a Tuple2(”L”, location). Later on we will
create Tuple2(”P”, product) pairs for transactions data. The tags ”L” and
”P” identify locations and products.

Listing 4.10: STEP-3: Create a JavaPairRDD for Users

JavaRDD<String> users = ctx.textFile(usersInputFile, 1);

// mapToPair
// <K2,V2> JavaPairRDD<K2,V2> mapToPair(PairFunction<T,K2,V2> f)
// Return a new RDD by applying a function to all elements of this RDD.
// PairFunction<T, K, V>
// T => Tuple2<K, V>
JavaPairRDD<String,Tuple2<String,String>> usersRDD =

//
users.mapToPair(new PairFunction<String, String, Tuple2<String,String>>() {

K

T

V

public Tuple2<String,Tuple2<String,String>> call(String s) {

String[] userRecord = s.split("\t");
Tuple2<String,String> location = new Tuple2<String,String>("L", userRecord[1]);
return new Tuple2<String,Tuple2<String,String>>(userRecord[0], location);

}
});

103

4.4.6 STEP-4: Create a JavaPairRDD for Transac-

tions

First, we create a transactions JavaRDD<String>, where RDD element is
a single record of text ﬁle (representing transaction record). Next, we use
JavaRDD<String>.mapToPair() function to create a new JavaPairRDD<String,Tuple2<String,String>>,
where key is a userID and value is a Tuple2(”P”, product). In previous step,
we created Tuple2(”L”, location) pairs for users. The tags ”L” and ”P”
identify locations and products.

Listing 4.11: STEP-4: Create a JavaPairRDD for Transactions

JavaRDD<String> transactions = ctx.textFile(transactionsInputFile, 1);

// mapToPair
// <K2,V2> JavaPairRDD<K2,V2> mapToPair(PairFunction<T,K2,V2> f)
// Return a new RDD by applying a function to all elements of this RDD.
// PairFunction<T, K, V>
// T => Tuple2<K, V>
JavaPairRDD<String,Tuple2<String,String>> transactionsRDD =

//

T
transactions.mapToPair(new PairFunction<String, String, Tuple2<String,String>>() {

V

K

public Tuple2<String,Tuple2<String,String>> call(String s) {

String[] transactionRecord = s.split("\t");
Tuple2<String,String> product = new Tuple2<String,String>("P", transactionRecord[1]);
return new Tuple2<String,Tuple2<String,String>>(transactionRecord[2], product);

}
});

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

4.4.7 STEP-5: Create a union of RDD’s created by

STEP-3 and STEP-4

This step creates union of two JavaPairRDD<String,Tuple2<String,String>>s.
the JavaPairRDD.union() requires that both RDD’s to have the same exact
types.

Listing 4.12: STEP-5: Create a union of RDD’s

1

2

// here we perform a union() on usersRDD and transactionsRDD
JavaPairRDD<String,Tuple2<String,String>> allRDD = transactionsRDD.union(usersRDD);

This step could have been implemented as (semantically equivalent – by

changing the order of union parameters):

104

Listing 4.13: STEP-5: Create a union of RDD’s

1

2

// here we perform a union() on usersRDD and transactionsRDD
JavaPairRDD<String,Tuple2<String,String>> allRDD = usersRDD.union(transactionsRDD);

So the result of union of two JavaPairRDDs will be the following (key,

value) pairs:

{

}

(userID, T2("L", location)),
...
(userID, T2("P", product))
...

1

2

3

4

5

6

7

8

9

10

4.4.8 STEP-6: Create a JavaPairRDD(userID, List(T2))

by calling groupBy()

Next, we group data (created in STEP-5) by userID. This step is accom-
plished by JavaPairRDD.groupByKey().

Listing 4.14: STEP-6: Create a JavaPairRDD

// group allRDD by userID
JavaPairRDD<String, Iterable<Tuple2<String,String>>>

groupedRDD = allRDD.groupByKey();
// now the groupedRDD entries will be as:
// <userIDi, List[T2("L", location),
//
//
//
//
// >

T2("P", Pi1),
T2("P", Pi2),
T2("P", Pi3), ...

]

The result of this step will be:

(userID1, List[T2("L", location1),

T2("P", P11),
T2("P", P12),
T2("P", P13), ...]),

105

(userID2, List[T2("L", location2),

T2("P", P21),
T2("P", P22),
T2("P", P23), ...]),

...

where Pij is a productID.

4.4.9 STEP-7: Create a productLocationsRDD as Java-

PairRDD(String,String)

In this step, the userIDs are dropped from RDDs. For a given RDD element:

(userID, List[T2("L", location),

T2("P", p1),
T2("P", p2),
T2("P", p3), ...])

we create JavaPairRDD<String,String> as:

(p1, location)
(p2, location)
(p3, location)
...

This step is accomplished by JavaPairRDD.flatMapToPair() function, which
we implement a PairFlatMapFunction.call() method. The PairFlatMapFunction
workd as:

PairFlatMapFunction<T, K, V>
T => Iterable<Tuple2<K, V>>

where in our example: T is an input and

106

we create (K, V) pairs as output:

T = Tuple2<String, Iterable<Tuple2<String,String>>>
K = String
V = String

Here is the complete implementation of PairFlatMapFunction.call()

method:

Listing 4.15: STEP-7: Create a productLocationsRDD

// PairFlatMapFunction<T, K, V>
// T => Iterable<Tuple2<K, V>>
JavaPairRDD<String,String> productLocationsRDD =

groupedRDD.flatMapToPair(new PairFlatMapFunction<

Tuple2<String, Iterable<Tuple2<String,String>>>,
String,
String>() {

// T
// K
// V

public Iterable<Tuple2<String,String>>

call(Tuple2<String, Iterable<Tuple2<String,String>>> s) {

// String userID = s._1;
Iterable<Tuple2<String,String>> pairs = s._2;

// NOT Needed

String location = "UNKNOWN";
List<String> products = new ArrayList<String>();
for (Tuple2<String,String> t2 : pairs) {

if (t2._1.equals("L")) {

location = t2._2;

}
else {

// t2._1.equals("P")
products.add(t2._2);

}

}

// now emit (K, V) pairs
List<Tuple2<String,String>> kvList =

new ArrayList<Tuple2<String,String>>();

for (String product : products) {

kvList.add(new Tuple2<String, String>(product, location));

}
// Note that edges must be reciprocal, that
// is every {source, destination} edge must have
// a corresponding {destination, source}.

return kvList;

}
});

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

107

4.4.10 STEP-8: Find all locations for a product

This step groups RDD pairs of (product, location) by grouping of products.
We use JavaPairRDD.groupByKey() to accomplish this step. This step does
some basic debugging too by calling JavaPairRDD.collect() function.

Listing 4.16: STEP-8: Find all locations for a product

// Find all locations for a product

JavaPairRDD<String, Iterable<String>> productByLocations =

productLocationsRDD.groupByKey();

// debug3
List<Tuple2<String, List<String>>> debug3 = productByLocations.collect();
System.out.println("--- debug3 begin ---");
for (Tuple2<String, Iterable<String>> t2 : debug3) {

System.out.println("debug3 t2._1="+t2._1);
System.out.println("debug3 t2._2="+t2._2);

}
System.out.println("--- debug3 end ---");

4.4.11 STEP-9: Finalize output by changing ”value”

STEP-8 produced a JavaPairRDD<String, List<String>> object, where
key is product (as a String) and value is a List<String>, which a list of
locations (but might have duplicates). To remove duplicate elements from a
vlue, we use a JavaPairRDD.mapValues() function. We implement this func-
tion by converting a List<String> to a Set<String>. Note that the keys are
not altered. Mapping values are implemented by a Function(T, R).call(),
where T is an input (as List<String>) and R is an output (as Tuple2<Set<String>, Integer>).

Listing 4.17: STEP-9: Finalize output

JavaPairRDD<String, Tuple2<Set<String>, Integer>> productByUniqueLocations =

productByLocations.mapValues(

new Function< Iterable<String>,
Tuple2<Set<String>, Integer>

// input
// output

>() {

public Tuple2<Set<String>, Integer> call(Iterable<String> s) {

Set<String> uniqueLocations = new HashSet<String>();
for (String location : s) {

uniqueLocations.add(location);

}
return new Tuple2<Set<String>, Integer>(uniqueLocations,

uniqueLocations.size());

}
});

108

1

2

3

4

5

6

7

8

9

10

11

12

1

2

3

4

5

6

7

8

9

10

11

12

13

14

4.4.12 STEP-10: Print the ﬁnal result RDD

The ﬁnal step emits the results by using JavaPairRDD.collect() method.

Listing 4.18: STEP-10: Print the ﬁnal result RDD

1

2

3

4

5

6

7

8

9

10

// debug4
System.out.println("=== Unique Locations and Counts ===");
List<Tuple2<String, Tuple2<Set<String>, Integer>>> debug4 =

productByUniqueLocations.collect();

System.out.println("--- debug4 begin ---");
for (Tuple2<String, Tuple2<Set<String>, Integer>> t2 : debug4) {

System.out.println("debug4 t2._1="+t2._1);
System.out.println("debug4 t2._2="+t2._2);

}
System.out.println("--- debug4 end ---");

4.4.13 Running Spark Solution

4.4.13.1 The Shell Script

# cat run_left_outer_join.sh
#!/bin/bash
source /home/hadoop/conf/env_2.3.0.sh
export SPARK_HOME=/home/hadoop/spark-1.0.0
source /home/hadoop/spark_mahmoud_examples/spark_env_yarn.sh
source $SPARK_HOME/conf/spark-env.sh

# system jars:
CLASSPATH=$CLASSPATH:$HADOOP_HOME/etc/hadoop

jars=‘find $SPARK_HOME -name ’*.jar’‘
for j in $jars ; do

CLASSPATH=$CLASSPATH:$j

done

# app jar:
export CLASSPATH=/home/hadoop/spark_mahmoud_examples/mp.jar:$CLASSPATH

109

export SPARK_CLASSPATH=$CLASSPATH
export SPARK_MASTER=spark://hnode01319.nextbiosystem.net:7077
#-Dsun.lang.ClassLoader.allowArraySyntax=true
USERS=/data/leftouterjoins/users.txt
TRANSACTIONS=/data/leftouterjoins/transactions.txt
OPTIONS="-Dsun.lang.ClassLoader.allowArraySyntax=true -Dspark.master=$SPARK_MASTER"
$JAVA_HOME/bin/java -cp $CLASSPATH $OPTIONS LeftOuterJoin $SPARK_MASTER $USERS $TRANSACTIONS

4.4.13.2 Running The Shell Script

Log output is trimmed to ﬁt the page.

# ./run_left_outer_join.sh
sparkMaster=spark://hnode01319.nextbiosystem.net:7077
users=/data/leftouterjoins/users.txt
transactions=/data/leftouterjoins/transactions.txt
...
14/06/03 17:52:01 INFO scheduler.DAGScheduler: Stage 0

(collect at LeftOuterJoin2.java:112) finished in 0.163 s

14/06/03 17:52:01 INFO spark.SparkContext: Job finished:
collect at LeftOuterJoin2.java:112, took 6.365762312 s

--- debug3 begin ---
debug3 t2._1=p2
debug3 t2._2=[GA]
debug3 t2._1=p4
debug3 t2._2=[GA, UT, CA]
debug3 t2._1=p1
debug3 t2._2=[GA, UT, UT]
debug3 t2._1=p3
debug3 t2._2=[UT]
--- debug3 end ---
=== Unique Locations and Counts ===
14/06/03 17:52:01 INFO spark.SparkContext: Starting job:

collect at LeftOuterJoin2.java:137

14/06/03 17:52:01 INFO spark.MapOutputTrackerMaster: Size

of output statuses for shuffle 1 is 156 bytes

...

110

14/06/03 17:52:01 INFO scheduler.DAGScheduler: Stage 3

(collect at LeftOuterJoin2.java:137) finished in 0.058 s

14/06/03 17:52:01 INFO spark.SparkContext: Job finished:
collect at LeftOuterJoin2.java:137, took 0.081830132 s

--- debug4 begin ---
debug4 t2._1=p2
debug4 t2._2=([GA],1)
debug4 t2._1=p4
debug4 t2._2=([UT, GA, CA],3)
debug4 t2._1=p1
debug4 t2._2=([UT, GA],2)
debug4 t2._1=p3
debug4 t2._2=([UT],1)
--- debug4 end ---
...
14/06/03 17:52:02 INFO scheduler.DAGScheduler: Stage 6

(saveAsTextFile at LeftOuterJoin2.java:144) finished in 1.060 s

14/06/03 17:52:02 INFO spark.SparkContext: Job finished: saveAsTextFile

at LeftOuterJoin2.java:144, took 1.169724354 s

4.5 Running Spark on YARN

In this example, we show how to submit Spark’s ApplicationMaster to Hadoop
YARN’s ResourceManager, and instruct Spark to run the LeftOuterJoin
program. Further, we can instruct our Spark program to save our ﬁnal re-
sult into an HDFS ﬁle. Saving ﬁle to HDFS is accomplished by adding
the following line after creating productByUniqueLocations RDD. Below,
/left/output is an HDFS output directory.

productByUniqueLocations.saveAsTextFile("/left/output");

4.5.1 Script to Run Spark on YARN

The script to run Spark on YARN is given below:

111

# cat leftjoin.sh
export SPARK_HOME=/usr/local/spark
export SPARK_ASSEMBLY_JAR=$SPARK_HOME/assembly/target/scala-2.10/spark-assembly-1.0.0-hadoop2.3.0.jar
export SPARK_LIBRARY_PATH=/usr/local/hadoop/lib/native
export JAVA_HOME=/usr/java/jdk6
export HADOOP_CONF_DIR=/usr/local/hadoop/conf
export YARN_CONF_DIR=/usr/local/hadoop/conf

# Submit Spark’s ApplicationMaster to YARN’s ResourceManager,
# and instruct Spark to run the LeftOuterJoin2 example
SPARK_JAR=$SPARK_ASSEMBLY_JAR \

$SPARK_HOME/bin/spark-class org.apache.spark.deploy.yarn.Client \
--jar $SPARK_HOME/tmp/mp.jar \
--class LeftOuterJoin \
--args yarn-standalone \
--args /left/users.txt \
--args /left/transactions.txt \
--num-workers 3 \
--master-memory 4g \
--worker-memory 2g \
--worker-cores 1

For details on Spark parameters (such as num-workers and worker-memory)
and environment variables, you may refer to Spark Summit Slides3. Most of
these parameters depend on the number of worker nodes, number of cores
per cluster node, and amount of RAM available. Optimal setting of these
parameters will require some trial and error and by trying diﬀerent size of
input data.

4.5.2 Running Script

Output is formatted to ﬁt the page.

3http://spark-summit.org/wp-content/uploads/2013/10/Spark-Ops-Final.

pptx

112

# ./nleftjoin.sh
14/05/28 16:49:31 INFO RMProxy: Connecting to ResourceManager at myserver100:8032
14/05/28 16:49:31 INFO Client: Got Cluster metric info from ApplicationsManager (ASM),

number of NodeManagers: 13

14/05/28 16:49:31 INFO Client: Queue info ... queueName: default, queueCurrentCapacity:

0.0, queueMaxCapacity: 1.0,

queueApplicationCount = 0, queueChildQueueCount = 0

14/05/28 16:49:31 INFO Client: Max mem capabililty of a single resource in this cluster 8192
14/05/28 16:49:31 INFO Client: Preparing Local resources
14/05/28 16:49:31 INFO Client: Uploading file:/usr/local/spark/tmp/mp.jar to

hdfs://myserver100:9000/user/hadoop/.sparkStaging/application_1401319796895_0008/mp.jar

14/05/28 16:49:32 INFO Client: Uploading file:

/usr/local/spark/tmp/assembly/target/scala-2.10/spark-assembly-1.0.0-hadoop2.3.0.jar
to hdfs://myserver100:9000/user/hadoop/.sparkStaging/

application_1401319796895_0008/spark-assembly-1.0.0-hadoop2.3.0.jar

14/05/28 16:49:33 INFO Client: Setting up the launch environment
14/05/28 16:49:33 INFO Client: Setting up container launch context
14/05/28 16:49:33 INFO Client: Command for starting the Spark ApplicationMaster:

$JAVA_HOME/bin/java -server -Xmx4096m -Djava.io.tmpdir=$PWD/tmp

org.apache.spark.deploy.yarn.ApplicationMaster

--class LeftOuterJoin2 --jar /usr/local/spark/tmp/mp.jar --args

’yarn-standalone’ --args ’/left/users.txt’

--args ’/left/transactions.txt’ --worker-memory 2048 --worker-cores 1
--num-workers 3 1> <LOG_DIR>/stdout 2> <LOG_DIR>/stderr
14/05/28 16:49:33 INFO Client: Submitting application to ASM
14/05/28 16:49:33 INFO YarnClientImpl: Submitted application application_1401319796895_0008
14/05/28 16:49:34 INFO Client: Application report from ASM:

application identifier: application_1401319796895_0008
appId: 8
clientToAMToken: null
appDiagnostics:
appMasterHost: N/A
appQueue: default
appMasterRpcPort: -1
appStartTime: 1401320973326
yarnAppState: ACCEPTED
distributedFinalState: UNDEFINED
appTrackingUrl: http://myserver100:50030/proxy/application_1401319796895_0008/

113

appUser: hadoop

...

14/05/28 16:49:50 INFO Client: Application report from ASM:

application identifier: application_1401319796895_0008
appId: 8
clientToAMToken: null
appDiagnostics:
appMasterHost: myserver400
appQueue: default
appMasterRpcPort: 0
appStartTime: 1401320973326
yarnAppState: FINISHED
distributedFinalState: SUCCEEDED
appTrackingUrl: http://myserver100:50030/proxy/application_1401319796895_0008/A
appUser: hadoop

4.5.3 Checking Expected Output

# hadoop fs -ls /left/output
Found 3 items
-rw-r--r--
-rw-r--r--
-rw-r--r--

2 hadoop supergroup
2 hadoop supergroup
2 hadoop supergroup

0 2014-05-28 16:49 /left/output/_SUCCESS
36 2014-05-28 16:49 /left/output/part-00000
32 2014-05-28 16:49 /left/output/part-00001

# hadoop fs -cat /left/output/part*
(p2,([GA],1))
(p4,([UT, GA, CA],3))
(p1,([UT, GA],2))
(p3,([UT],1))

4.6 Left Outer Join by Spark’s leftOuterJoin()

This section solves the left outer join by using Spark’s built in JavaPairRDD.leftOuterJoin()
method (note that MapReduce/Hadoop does not oﬀer higher level API such

114

as leftOuterJoin() method):

import scala.Tuple2;
import com.google.common.base.Optional;
import org.apache.spark.api.java.JavaPairRDD;

JavaPairRDD<K,Tuple2<V,Optional<W>>> leftOuterJoin(JavaPairRDD<K,W> other)

// Perform a left outer join of this and other. For each
// element (k, v) in this, the resulting RDD will either
// contain all pairs (k, (v, Some(w))) for w in other, or
// the pair (k, (v, None)) if no elements in other have key k.

Using Sparks’s JavaPairRDD.leftOuterJoin() method enable us

1. To avoid the costly JavaPairRDD.union() operation between users

and transactions

2. To avoid introducing custom ﬂags such as ”L” for location and ”P” for

products.

3. To avoid extra RDD transformations to separate custom ﬂags from

each other

Using JavaPairRDD.leftOuterJoin() method enable us to produce the
result eﬃciently. The transactionsRDD is the left table and usersRDD is the
right table.

JavaPairRDD<String,String> usersRDD = ...;
JavaPairRDD<String,String> transactionsRDD = ...; // (K=userID, V=product)
// perform left outer join by built-in leftOuterJoin()
JavaPairRDD<String, Tuple2<String,Optional<String>>> joined =

// (K=userID, V=location)

transactionsRDD.leftOuterJoin(usersRDD);

Now, the joined RDD contains:

115

(u4,(p4,Optional.of(CA)))
(u5,(p4,Optional.of(GA)))
(u2,(p1,Optional.of(GA)))
(u2,(p2,Optional.of(GA)))
(u1,(p3,Optional.of(UT)))
(u1,(p1,Optional.of(UT)))
(u1,(p1,Optional.of(UT)))
(u1,(p4,Optional.of(UT)))

Since, we are only interested in the products and unique localtions, in the
next step, we ignore userID’s (the key). This can be accomplished by another
JavaPairRDD.mapToPair() function. After ignoring userID’s, we generate:

(p4,CA)
(p4,GA)
(p1,GA)
(p2,GA)
(p3,UT)
(p1,UT)
(p1,UT)
(p4,UT)

which has the desired information to generate products and unique locations.

First, we present a high-level steps to show how to use Saprk’s built-in
JavaPairRDD.leftOuterJoin() method. Next, each step will be discussed
in detail.

4.6.1 High-Level Steps

Listing 4.19: High-Level Steps

1 // STEP-0: import required classes and interfaces
2 public class SparkLeftOuterJoin {
3

public static void main(String[] args) throws Exception {

116

// STEP-1: read input parameters
// STEP-2: create Spark’s context object
// STEP-3: create RDD for user’s data
// STEP-4: create (K=userID,V=location) pairs for users (the "right" table)
// STEP-5: create RDD for transaction’s data
// STEP-6: create (K=userID,V=product) pairs for transactions (the "left" table)
// STEP-7: use Spark’s built-in JavaPairRDD.leftOuterJoin() method
// STEP-8: create (product, location) pairs
// STEP-9: group (K=product, V=location) pairs by K
// STEP-10: create final output (K=product, V=Set<location>) pairs by K
System.exit(0);

4

5

6

7

8

9

10

11

12

13

14

}

15
16 }

4.6.2 STEP-0: import required classes and interfaces

An Optional4 represents immutable object that may contain a non-null
reference to another object (useful for left outer join, since the joined values
may contain null if the key is in left table but not in the right table).
SparkConf object is used to deﬁne Spark’s conﬁgurations and then we use
it to create an instance of JavaSparkContext, which will be used to create
RDDs.

Listing 4.20: STEP-0: import required classes and interfaces

1 // STEP-0: import required classes and interfaces
2 import scala.Tuple2;
3 import org.apache.spark.api.java.JavaRDD;
4 import org.apache.spark.api.java.JavaPairRDD;
5 import org.apache.spark.api.java.JavaSparkContext;
6 import org.apache.spark.api.java.function.Function;
7 import org.apache.spark.api.java.function.PairFunction;
8 import com.google.common.base.Optional;
9 import org.apache.spark.SparkConf;
10 import java.util.Set;
11 import java.util.HashSet;

4.6.3 STEP-1: read input parameters

This step reads the location of HDFS input ﬁles: users and transactions.
These input ﬁles will be used to create left table (transactionsRDD) and
right table (usersRDD).

4com.google.common.base.Optional<T> is an abstract class. For details, see https:

//code.google.com/p/guava-libraries/

117

1

2

3

4

5

6

7

8

9

10

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

Listing 4.21: STEP-1: read input parameters

// STEP-1: read input parameters
if (args.length < 2) {

System.err.println("Usage: LeftOuterJoin <users> <transactions>");
System.exit(1);

}

String usersInputFile = args[0];
String transactionsInputFile = args[1];
System.out.println("users="+ usersInputFile);
System.out.println("transactions="+ transactionsInputFile);

4.6.4 STEP-2: create Spark’s context object

This step creates an instance of JavaSparkContext object, which will be used
to create new RDDs. Note that I have hard-coded some host names (such as
value for key yarn.resourcemanager.hostname), but for your production
deployments, you should read these from a conﬁguration obect (such as an
XML ﬁle).

Listing 4.22: STEP-2: create Spark’s context object

// STEP-2: create Spark’s context object
JavaSparkContext ctx = createJavaSparkContext();

static JavaSparkContext createJavaSparkContext() throws Exception {

SparkConf conf = new SparkConf();
conf.set("yarn.resourcemanager.hostname", "server100");
conf.set("yarn.resourcemanager.scheduler.address", "server100:8030");
conf.set("yarn.resourcemanager.resource-tracker.address", "server100:8031");
conf.set("yarn.resourcemanager.address",
conf.set("mapreduce.framework.name", "yarn");
conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
conf.set("spark.executor.memory", "7g");
JavaSparkContext ctx = new JavaSparkContext("yarn-cluster", "SparkLeftOuterJoin", conf);
return ctx;

"server100:8032");

}

4.6.5 STEP-3: create RDD for user’s data

This step creates usersRDD, which is a set of (userID, location) pairs.
The usersRDD represents the ”right” table for the left outer join operation.

118

Listing 4.23: STEP-3: create RDD for user’s data

1

2

// STEP-3: create RDD for user’s data
JavaRDD<String> users = ctx.textFile(usersInputFile, 1);

4.6.6 STEP-4: Create usersRDD: The ”right” Table

This step create the right table represented as usersRDD, which contain
(K=userID,V=location) pairs from users input data.

Listing 4.24: STEP-4: create (K=userID,V=location) pairs for users

// STEP-4: create (K=userID,V=location) pairs for users
// <K2,V2> JavaPairRDD<K2,V2> mapToPair(PairFunction<T,K2,V2> f)
// Return a new RDD by applying a function to all elements of this RDD.
// PairFunction<T, K, V>
// T => Tuple2<K, V>
JavaPairRDD<String,String> usersRDD =

//
users.mapToPair(new PairFunction<String, String, String>() {

V

K

T

public Tuple2<String,String> call(String s) {

String[] userRecord = s.split("\t");
String userID = userRecord[0];
String location = userRecord[1];

return new Tuple2<String,String>(userID, location);

}
});

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

4.6.7 STEP-5: create transactionRDD for transaction’s

data

This step creates transactionRDD, which is a set of (userID, product)
pairs. The transactionRDD represents the ”left” table for the left outer join
operation.

Listing 4.25: STEP-5: create transactionRDD for transaction’s data

1

2

// STEP-5: create RDD for transaction’s data
JavaRDD<String> transactions = ctx.textFile(transactionsInputFile, 1);

119

4.6.8 STEP-6: Create transactionsRDD: The Left Ta-

ble

This step create the left table represented as transactionsRDD, which contain
(K=userID,V=product) pairs from transactions input data.

Listing 4.26: STEP-6: create (K=userID,V=product) pairs for transactions

// STEP-6: create (K=userID,V=product) pairs for transactions
// PairFunction<T, K, V>
// T => Tuple2<K, V>
// sample transaction input: t1
3
JavaPairRDD<String,String> transactionsRDD =

330

p3

u1

//
transactions.mapToPair(new PairFunction<String, String, String>() {

V

T

K

public Tuple2<String,String> call(String s) {

String[] transactionRecord = s.split("\t");
String userID = transactionRecord[2];
String product = transactionRecord[1];

return new Tuple2<String,String>(userID, product);

}
});

4.6.9 STEP-7: use Spark’s built-in JavaPairRDD.leftOuterJoin()

method

This is core step for performing the left outer join operation by using Spark’s
JavaPairRDD.leftOuterJoin() method.

Listing 4.27: STEP-7:
method

use Spark’s built-in JavaPairRDD.leftOuterJoin()

// STEP-7: use Spark’s built-in JavaPairRDD.leftOuterJoin() method
// JavaPairRDD<K,scala.Tuple2<V,Optional<W>>> leftOuterJoin(JavaPairRDD<K,W> other)
// Perform a left outer join of this and other. For each element (k, v) in this,
// the resulting RDD will either contain all pairs (k, (v, Some(w))) for w in
// other, or the pair (k, (v, None)) if no elements in other have key k.
//
// here we perform a transactionsRDD.leftOuterJoin(usersRDD)
JavaPairRDD<String, Tuple2<String,Optional<String>>> joined =

transactionsRDD.leftOuterJoin(usersRDD);

1

2

3

4

5

6

7

8

9

10

11

12

13

14

1

2

3

4

5

6

7

8

9

10

joined.saveAsTextFile("/output/1");

STEP-7 creates the following output (result of the left outer join opera-

tion):

120

#hadoop fs -cat /output/1/part*
(u4,(p4,Optional.of(CA)))
(u5,(p4,Optional.of(GA)))
(u2,(p1,Optional.of(GA)))
(u2,(p2,Optional.of(GA)))
(u1,(p3,Optional.of(UT)))
(u1,(p1,Optional.of(UT)))
(u1,(p1,Optional.of(UT)))
(u1,(p4,Optional.of(UT)))

4.6.10 STEP-8: create (product, location) pairs

This step builds another JavaPairRDD, which contains (K=product, V=location)
pairs. Note that we completely ignored the userIDs, since we are only inter-
ested in products and their unique user’s locations.

Listing 4.28: STEP-8: create (product, location) pairs

// STEP-8: create (product, location) pairs
JavaPairRDD<String,String> products =

joined.mapToPair(new PairFunction<

Tuple2<String, Tuple2<String,Optional<String>>>, // T
// K
String,
// V
String>

() {

public Tuple2<String,String> call(Tuple2<String, Tuple2<String,Optional<String>>> t) {

Tuple2<String,Optional<String>> value = t._2;

return new Tuple2<String,String>(value._1, value._2.get());

}
});
products.saveAsTextFile("/output/2");

STEP-8 creates the following output

#hadoop fs -cat /output/2/part*
(p4,CA)
(p4,GA)
(p1,GA)
(p2,GA)
(p3,UT)
(p1,UT)
(p1,UT)
(p4,UT)

121

1

2

3

4

5

6

7

8

9

10

11

12

13

4.6.11 STEP-9: group (K=product, V=location) pairs

by K

This step groups (K=product, V=location) pairs by K. The result will be
(K, V2) where V2 is a list of locations (will have duplicate locations).

Listing 4.29: STEP-9: group (K=product, V=location) pairs by K

1

2

3

// STEP-9: group (K=product, V=location) pairs by K
JavaPairRDD<String, Iterable<String>> productByLocations = products.groupByKey();
productByLocations.saveAsTextFile("/output/3");

STEP-9 creates the following output

# hadoop fs -cat /output/3/p*
(p1,[GA, UT, UT])
(p2,[GA])
(p3,[UT])
(p4,[CA, GA, UT])

4.6.12 STEP-10: create ﬁnal output (K=product, V=Set(location))

This ﬁnal step removes duplicate locations and creates (K,V2), where V2 is
a Tuple2<Set<location>, size>.

Listing 4.30: STEP-10: create ﬁnal output (K=product, V=Set¡location¿)

pairs by K

// STEP-10: create final output (K=product, V=Set<location>) pairs by K
JavaPairRDD<String, Tuple2<Set<String>, Integer>> productByUniqueLocations =

productByLocations.mapValues(new Function< Iterable<String>,

// input

Tuple2<Set<String>, Integer> // output

>() {

public Tuple2<Set<String>, Integer> call(Iterable<String> s) {

Set<String> uniqueLocations = new HashSet<String>();
for (String location : s) {

uniqueLocations.add(location);

}
return new Tuple2<Set<String>, Integer>(uniqueLocations, uniqueLocations.size());

}
});

productByUniqueLocations.saveAsTextFile("/output/4");

STEP-10 creates the following ﬁnal output

122

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

# hadoop fs -cat /output/4/p*
(p1,([UT, GA],2))
(p2,([GA],1))
(p3,([UT],1))
(p4,([UT, GA, CA],3))

4.6.13 Sample Run by YARN

4.6.13.1

Input

Input: Right Table

# hadoop fs -cat /data/leftouterjoins/users.txt
u1
u2
u3
u4
u5

UT
GA
CA
CA
GA

Input: Left Table

# hadoop fs -cat /data/leftouterjoins/transactions.txt
t1
t2
t3
t4
t5
t6
t7
t8

330
3
400
1
3
600
10 1000
90
9
120
4
160
8
40
2

u1
u2
u1
u2
u4
u1
u1
u5

p3
p1
p1
p2
p4
p1
p4
p4

4.6.13.2 Script

# cat ./run_left_outer_join_spark.sh
#!/bin/bash
export HADOOP_HOME=/usr/local/hadoop/hadoop-2.4.0
export SPARK_LIBRARY_PATH=$HADOOP_HOME/lib/native
export JAVA_HOME=/usr/java/jdk7
export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop

123

export YARN_CONF_DIR=$HADOOP_HOME/etc/hadoop
export SPARK_HOME=/home/hadoop/spark-1.0.0
export MY_JAR=/home/hadoop/spark_mahmoud_examples/mp.jar
export YARN_APPLICATION_CLASSPATH=$CLASSPATH:$HADOOP_HOME/etc/hadoop
USERS=/data/leftouterjoins/users.txt
TRANSACTIONS=/data/leftouterjoins/transactions.txt
$SPARK_HOME/bin/spark-submit --class SparkLeftOuterJoin \

--master yarn-cluster \
--num-executors 3 \
--driver-memory 1g \
--executor-memory 1g \
--executor-cores 10 \
$MY_JAR

$USERS $TRANSACTIONS

4.6.13.3 Generated HDFS Output

# hadoop fs -cat /output/1/p*
(u5,(p4,Optional.of(GA)))
(u2,(p1,Optional.of(GA)))
(u2,(p2,Optional.of(GA)))
(u1,(p3,Optional.of(UT)))
(u1,(p1,Optional.of(UT)))
(u1,(p1,Optional.of(UT)))
(u1,(p4,Optional.of(UT)))

# hadoop fs -cat /output/2/p*
(p4,CA)
(p4,GA)
(p1,GA)
(p2,GA)
(p3,UT)
(p1,UT)
(p1,UT)
(p4,UT)

# hadoop fs -cat /output/3/p*
(p1,[GA, UT, UT])
(p2,[GA])

124

(p3,[UT])
(p4,[CA, GA, UT])

# hadoop fs -cat /output/4/p*
(p1,([UT, GA],2))
(p2,([GA],1))
(p3,([UT],1))
(p4,([UT, GA, CA],3))

125

Chapter 5

Order Inversion Pattern

5.1

Introduction

The main focus of this chapter is to discuss the order inversion (OI) pattern,
which can be used in solving some problems using MapReduce framework.
The OI pattern enables us to control the order of values received at a re-
ducer (some computations require ordered data). Typically, the OI pattern
happens during data analysis phase. In Hadoop, the order of values arriving
at a reducer is undeﬁned (there is no order unless, we exploit the sorting
phase of MapReduce to push data needed for calculations to the reducer).
The OI pattern works for pairs patterns, which uses simpler data structures
and requires less reducer memory (due to the fact that there is no additional
sorting and ordering of reducer values in the reducer phase).

To understand the OI pattern, we start with a simple example. Consider a
reducer with composite key = (K1, K2) and furthermore assume that K1 is
the natural key component of the composite key. Let this reducer to receive
following values (there is no ordering between these values):

V1, V2, ..., Vn

With implementation of the OI pattern, it is possible to sort and clas-
sify the values arriving at reducer with key = (K1, K2). The sole purpose

126

of using the OI pattern is to properly sequence data presented to the re-
ducer). Further assume that, K1 is a ﬁxed part of the composite key and
K2 has only 3 (this can be any number) distinct values {K2a, K2b, K2c},
which generated the following values (note that we have to send the keys
{(K1, K2a), (K1, K2b), (K1, K2c)} to the same reducer)

Keys and Values for Natural Key K1
Composite Key Values...
(K1, K2a)
(K1, K2b)
(K1, K2c)

{A1, A2, ..., Am}
{B1, B2, ..., Bp}
{C1, C2, ..., Cq}

where

• m + p + q = n

• Sort Order

K2a < K2b < K2c (ascending order)
OR
K2a > K2b > K2c (descending order)

• Ai, Bj, Ck ∈ {V1, V2, ..., Vn}

With proper implementation of the OI pattern, we will make the reducer

values to appear in order

A1, A2, ..., Am, B1, B2, ..., Bp, C1, C2, ..., Cq

This ordering and sequencing of reducer values will enable us to do some
calculations and computations ﬁrst on Ai, then on Bj and ﬁnally on Ck.
Note that buﬀering values are not needed in memory. The main question is
how to produce the desired behavior? The answer lies in deﬁning a ”custom
partitioner,” which only pays attention to the left component (K1 — called
the natural reducer key) of the composite key (K1, K2). That is, the custom
partitioner must partition based on the hash of the left key (K1) only.

127

5.2 Example of Order Inversion Pattern

The simple example to demonstrate the OI pattern is to compute relative
frequecies of words for a given set of documents. The goal is to build a
N × N matrix (call this matrix M ), where N = |V | (the vocabulary size all
given documents) and each cell Mij contains the number of times word Wi
co-occurs with word Wj within a speciﬁc context. For simplicity, we deﬁne
this context as the neighbors of Wi. For example, given the following speciﬁc
words:

W1, W2, W3, W4, W5, W6

If we deﬁne the neighborhood of a word as two words before and two words
after that word, then we can say that

Neighborhood Table
Word Neighbors ±2
W2, W3
W1
W1, W3, W4
W2
W1, W2, W4, W5
W3
W2, W3, W5, W6
W4
W3, W4, W6
W5
W4, W5
W6

For our example, computing relative frequencies requires marginal counts.
But marginal counts cannot be computed until you see all counts. Therefore,
we do need to make the marginal counts to arrive at the reducer before the
joint counts. It is possible to buﬀer these values in memory, but it might not
scale up, if these can not ﬁt in memory. Note that for computing relative
frequencies, we will not use absolute count of words. According to Jimmy Lin
and Chris Dyer[15]: ”the drawback of absolute counts is that it doesnt take
into account the fact that some words appear more frequently than others.
Word Wi may co-occur frequently with Wj simply because one of the words
is very common. A simple remedy is to convert absolute counts into relative
frequencies, f (Wj|Wi). That is, what proportion of the time does Wj appear
in the context of Wi?” This can be computed using the following equation:

128

f (Wj|Wi) =

N (Wi,Wj)
(cid:80)
N (Wi,w)
w

Here, N (a, b) indicates the number of times a particular co-occurring
word pair is observed in the corpus (a given set of all documents as input).
Therefore, we need the count of the joint event (word co-occurrence), divided
by what is known as the marginal (the sum of the counts of the conditioning
variable co-occurring with anything else).

5.3 MapReduce for Order Inversion Pattern

Following our example of computing relative frequencies for a given set of
documents, we do need to generate two sequence of data: the ﬁrst sequence
will be total neighborhood counts (the total number of co-ocurrences of a
word) for the word (let’s denote this by composite Key = (W, ∗) — W
denotes the word) and the second sequence will be the counts of that word
against other speciﬁc words (let’s denote this by composite Key = (W, W2)):
therefore, a reducer will receive the following set of (key,value) pairs in order:

A Reducer (key-value) Pairs in Order

Values as Integer Numbers...
Key
A1, A2, ..., Am
(W, ∗)
(W, W1) B1, B2, ..., Bp
(W, W2) C1, C2, ..., Cq
...
...

A concrete example will be:

A Reducer (key-value) Pairs in Order
Key
(dog, ∗)
(dog, bite)
(dog, best)
...

Values...
100, 129, 500, ...
2, 1, 1, 1
1, 1, 1, 1, 1
...

Now, we want to discuss the relative term co-occurrence and the OI design
pattern. For this, we need to compute the co-occurrence matrix, by using
the relative frequencies of each pair, instead of the absolute value. Therefore,

129

we need to count the number of times each pair (Wi, Wj) occurs divided by
the number of total pairs with Wi (marginal). To complete our MapRe-
duce solution, we will provide a map(), reduce(), and a custom partitioner
(OrderInversionPartitioner class), which apply the partitioner only ac-
cording to the ﬁrst element in the PairOfWords1, sending all data regarding
the same word to the same reducer. Also, we use PairOfWords to represent
a composite key (composed of two words).

5.3.1 Custom Partitioner

Hadoop provides a plugin architecture to plug a custom partitioner:

Listing 5.1: Custom Partitioner: OrderInversionPartitioner

1 ...
2 import org.apache.hadoop.mapreduce.Job;
3 import org.apache.hadoop.conf.Configuration;
4 ...
5
6 public class RelativeFrequencyDriver {
7

8

9

10

11

12

public static void main(String[] args) throws Exception {

Job job = Job.getInstance(new Configuration());
...
job.setPartitionerClass(OrderInversionPartitioner.class);
...

}

13
14 }

Hadoop provides a proper API to plug-in a custom partitioner:

job.setPartitionerClass(OrderInversionPartitioner.class);

5.3.1.1 Custom Partitioner Implementation in Hadoop

The custom partitioner must ensure that all pairs with the same left word
(called the natural key) are sent to the same reducer. For example, the
composite keys {(man, tall), (man, strong), (man, moon), ...} are
assigned to the same reducer. To send theses keys to the same reducer, we

1 We will use PairOfWords class for representing a pair of words (Wi, Wj).
The method PairOfWords.getLeftElement((Wi, Wj)) returns Wi and the method
PairOfWords.getRightElement((Wi, Wj)) returns Wj

130

must deﬁne a custom partitioner that only pays attention to the left word (in
our example, the left word is man). That is, the partitioner should partition
based on the hash of the left word (so called the natural key) only.

Listing 5.2: Custom Partitioner Implementation: OrderInversionPartitioner

1 import org.apache.hadoop.io.IntWritable;
2 import org.apache.hadoop.mapreduce.Partitioner;
3
4 public class OrderInversionPartitioner
5

extends Partitioner<PairOfWords, IntWritable> {

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

@Override
public int getPartition(PairOfWords key,

IntWritable value,
int numberOfPartitions) {

// key = (leftWord, rightWord)
String leftWord = key.getLeftElement();
return Math.abs(hash(leftWord) % numberOfPartitions);

}

// adapted from String.hashCode()
private static long hash(String str) {
long h = 1125899906842597L; // prime
int length = str.length();
for (int i = 0; i < length; i++) {

h = 31*h + str.charAt(i);

}
return h;

}

24
25 }

5.3.2 Relative Frequency Mapper

The mapper class emits relative frequencies of a word’s neighbors (2 words
before and 2 words after). For example, if a mapper receives the following:

w1 w2 w3 w4 w5 w6

Then it will emit the following (key, value) pairs:

131

Mapper Generated (key-value) Pairs
Key
(w1, w2)
(w1, w3)
(w1, *)
(w2, w1)
(w2, w3)
(w2, w4)
(w2, *)
(w3, w1)
(w3, w2)
(w3, w4)
(w3, w5)
(w3, *)
(w4, w2)
(w4, w3)
(w4, w5)
(w4, w6)
(w4, *)
(w5, w3)
(w5, w4)
(w5, w6)
(w5, *)
(w6, w4)
(w6, w5)
(w6, *)

Value
1
1
2
1
1
1
3
1
1
1
1
4
1
1
1
1
4
1
1
1
3
1
1
2

The mapper algorithm is presented below:

Listing 5.3: Mapper Class: RelativeFrequencyMapper

1 public class RelativeFrequencyMapper ... {
2

3

4

5

6

7

8

9

10

11

private int neighborWindow = 2;
private PairOfWords pair = new PairOfWords();

public void setup(Context context) {

// driver will set "neighbor.window"
neighborWindow = context.getConfiguration().getInt("neighbor.window", 2);

}

// key is system generated, ignored here

132

// value is a String (set of words)
public void map(Object key, String value) {

String[] tokens = StringUtils.split(value, " ");
if (tokens.length < 2) {

return;

}

for (int i = 0; i < tokens.length; i++) {

String word = tokens[i];
pair.setWord(word);
int start = (i - neighborWindow < 0) ? 0 : i - neighborWindow;
int end = (i + neighborWindow >= tokens.length) ? tokens.length - 1 : i + neighborWindow;
for (int j = start; j <= end; j++) {

if (i == j) {

continue;

}
pair.setNeighbor(tokens[j]);
emit(pair, 1);

}
pair.setNeighbor("*");
int totalCount = end - start;
emit(pair, totalCount);

}

}

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 }

5.3.3 Relative Frequency Reducer

Since we have a custome partitioner and implementation of the OI pattern,
the values received by a reducer will be based on the natural key of the keys
generated by all mappers. For the example presented for the mapper phase,
we will have 6 reducers with the following (key, value) input pairs:

Input to Reducers

Key
(w1, *),(w1, w2),(w1, w3)
(w2, *),(w2, w1),(w2, w3),(w2, w4)
(w3, *),(w3, w1),(w3, w2),(w3, w4),(w3, w5)
(w4, *),(w4, w2),(w4, w3),(w4, w5),(w4, w6)
(w5, *),(w5, w3),(w5, w4),(w5, w6)
(w6, *),(w6, w4),(w6, w5)

Value
2,1,1
3,1,1,1
4,1,1,1,1
4,1,1,1,1
3,1,1,1
2,1,1

The reducer algorithm is presented below.

133

Listing 5.4: Reducer Class: RelativeFrequencyReducer

1 public class RelativeFrequencyReducer ... {
2

private double totalCount = 0;
private String currentWord = "NOT_DEFINED";

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

protected void reduce(PairOfWords key, Iterable<Integer> values) {

if (key.getRight().equals("*")) {

if (key.getLeft().equals(currentWord)) {

totalCount += getTotalCount(values);

}
else {

currentWord = key.getLeft();
totalCount = getTotalCount(values);

}

}
else {

int count = getTotalCount(values);
double relativeCount = count / totalCount;
emit(key, relativeCount);

}

}

private int getTotalCount(Iterable<Integer> values) {

int count = 0;
for (Integer value : values) {
count += value.get();

}
return count;

}

29
30 }

5.3.4

Implementation Classes in Hadoop

Implementation Classes in Hadoop

Class Name
RelativeFrequencyDriver
RelativeFrequencyMapper
RelativeFrequencyReducer
RelativeFrequencyCombiner Deﬁnes combine()
OrderInversionPartitioner Custom partitioner:

Class Description
Dirver to submit job
Deﬁnes map()
Deﬁnes reduce()

PairOfWords

How to partition natural keys
Represents pair of words (Word1, Word2)

134

5.4 Sample Run

5.4.1

Input

/order_inversion/input/sample_input.txt

# hadoop fs -cat
java is a great language
java is a programming language
java is green fun language
java is great
programming with java is fun

5.4.2 Running MapReduce Job

# ./run.sh
...
added manifest
adding: OrderInversionPartitioner.class(in = 1005) (out= 590)(deflated 41%)
adding: PairOfWords$Comparator.class(in = 933) (out= 603)(deflated 35%)
adding: PairOfWords.class(in = 2932) (out= 1285)(deflated 56%)
adding: RelativeFrequencyCombiner.class(in = 1518) (out= 681)(deflated 55%)
adding: RelativeFrequencyDriver.class(in = 3121) (out= 1534)(deflated 50%)
adding: RelativeFrequencyMapper.class(in = 2900) (out= 1256)(deflated 56%)
adding: RelativeFrequencyReducer.class(in = 2208) (out= 1026)(deflated 53%)
Deleted hdfs://localhost:9000/lib/order_inversion.jar
Deleted hdfs://localhost:9000/order_inversion/output
...
14/01/04 14:56:56 INFO input.FileInputFormat: Total input paths to process : 1
...
14/01/04 14:56:57 INFO mapred.JobClient: Running job: job_201401041453_0002
14/01/04 14:56:58 INFO mapred.JobClient:
14/01/04 14:57:03 INFO mapred.JobClient:
14/01/04 14:57:11 INFO mapred.JobClient:
14/01/04 14:57:12 INFO mapred.JobClient:
14/01/04 14:57:19 INFO mapred.JobClient:
14/01/04 14:57:21 INFO mapred.JobClient:
14/01/04 14:57:21 INFO mapred.JobClient: Job complete: job_201401041453_0002
...
14/01/04 14:57:21 INFO mapred.JobClient:
14/01/04 14:57:21 INFO mapred.JobClient:
14/01/04 14:57:21 INFO mapred.JobClient:
14/01/04 14:57:21 INFO mapred.JobClient:
14/01/04 14:57:21 INFO mapred.JobClient:
14/01/04 14:57:21 INFO mapred.JobClient:
14/01/04 14:57:21 INFO mapred.JobClient:
14/01/04 14:57:21 INFO mapred.JobClient:
14/01/04 14:57:21 INFO mapred.JobClient:
14/01/04 14:57:21 INFO mapred.JobClient:
14/01/04 14:57:21 INFO mapred.JobClient:
14/01/04 14:57:21 INFO mapred.JobClient:
14/01/04 14:57:21 INFO mapred.JobClient:
14/01/04 14:57:21 INFO mapred.JobClient:
14/01/04 14:57:21 INFO RelativeFrequencyDriver: Job Finished in milliseconds: 24869

Map output materialized bytes=906
Map input records=5
Reduce shuffle bytes=906
Spilled Records=106
Map output bytes=1154
Total committed heap usage (bytes)=439619584
Combine input records=85
SPLIT_RAW_BYTES=125
Reduce input records=53
Reduce input groups=53
Combine output records=53
Reduce output records=44
Map output records=85

map 0% reduce 0%
map 100% reduce 0%
map 100% reduce 22%
map 100% reduce 66%
map 100% reduce 77%
map 100% reduce 100%

Map-Reduce Framework

5.4.3 Generated Output

# hadoop fs -cat /order_inversion/output/part*
(great, a)
(great, is)

0.4

0.2

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

1
2
3

135

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

0.2

0.2
0.3333333333333333

0.3333333333333333

0.3333333333333333

0.2

0.2

0.2

0.2

0.2

0.2

0.25

0.125

0.25

0.25

0.25

0.14285714285714285

0.14285714285714285

0.14285714285714285
0.07142857142857142

0.35714285714285715

0.07142857142857142

0.07142857142857142

0.16666666666666666

0.08333333333333333

0.08333333333333333
0.08333333333333333

0.4166666666666667

0.08333333333333333

0.08333333333333333
0.3333333333333333

0.2

0.4

0.2

0.25

0.25

0.125

(great, java)
(great, language)
(with, is)
(with, java)
(with, programming)
(fun, green)
(fun, is)
(fun, java)
(fun, language)
(programming, a)
(programming, is)
(programming, java)
(programming, language)
(programming, with)
(a, great)
(a, is)
(a, java)
(a, language)
(a, programming)
(green, fun)
(green, is)
(green, java)
(green, language)
(is, a)
(is, fun)
(is, great)
(is, green)
(is, java)
(is, programming)
(is, with)
(java, a)
(java, fun)
(java, great)
(java, green)
(java, is)
(java, programming)
(java, with)
(language, a)
(language, fun)
(language, great)
(language, green)
(language, programming)

0.25

0.16666666666666666

0.16666666666666666
0.16666666666666666

0.16666666666666666

136

Chapter 6

Moving Average

6.1

Introduction

The purpose of this chapter is to present ”moving average” solution in
MapReduce/Hadoop. Before presenting a MapReduce solution, we will look
at the basic concepts of ”moving average”. To understand ”moving average”
concept, we do need to understand time series data. Time series data are
quantities that represent the values taken by a variable over a period of time
such as a second, minute, hour, day, week, month, quarter, or year. Semifor-
mally, we can represent a time series data as a sequence of triplets:

(k, t, v)

Where k is a key (such as a stock symbol), t is a time (in hours, minutes, or
seconds), and v is the associated value (such as value of a stock at a point t.
Typically, time series data occurs wherever the same measurements are
recorded on a regular period of time basis. For example, closing price of a
company stock is a time series data over minutes, hours, or days. Mean (or
average) of time series data (observations equally spaced in time such as per
hour, per day) from several consecutive periods is called ”moving average.”
Why do we call it ”moving”? It is called ”moving” because it is continually
recomputed as new time series data becomes available, and it progresses by
dropping the earliest value and adding the latest value.

137

6.1.1 Example-1: Time Series Data

Consider the following data for closing stock price of a company called MY-
STOCK (note that this is a fake stock symbol):

Time Series
1
2
3
4
5
6
7
...

Time Series Data
Date
2013-10-01
2013-10-02
2013-10-03
2013-10-04
2013-10-07
2013-10-08
2013-10-09
...

Closing Price
10
18
20
30
24
33
27
...

For moving averages of 3-days we’ll have as output:

Time Series
1
2
3
4
5
6
7

Moving Average How Calculated

Moving Average Calclulation
Date
2013-10-01
2013-10-02
2013-10-03
2013-10-04
2013-10-07
2013-10-08
2013-10-09

10.00
14.00
16.00
22.66
24.66
29.00
28.00

= (10)/(1)
= (10+18)/(2)
= (10+18+20)/(3)
= (18+20+30)/(3)
= (20+30+24)/(3)
= (30+24+33)/(3)
= (24+33+27)/(3)

6.1.2 Example-2: Time Series Data

Another example will be the ”Moving Average,” which calculates the mov-
ing average of unique visitors for diﬀerent URLs for each date in a speciﬁc
timeframe. We may use the following input:

138

Time Series Data

Date
2013-10-01
2013-10-02
2013-10-03
2013-10-04
2013-10-05
2013-10-01
2013-10-02
2013-10-03
2013-10-04

Unique Visitors
400
200
300
700
800
10
20
30
70

URL
URL1
URL1
URL1
URL1
URL1
URL2
URL2
URL2
URL2

For moving averages of 3 days we’ll have as output:

Time Series Data

URL
URL1
URL1
URL1
URL1
URL1
URL2
URL2
URL2
URL2

Date
2013-10-01
2013-10-02
2013-10-03
2013-10-04
2013-10-05
2013-10-01
2013-10-02
2013-10-03
2013-10-04

Moving Average of 3 Days
400
300
300
400
600
10
15
20
40

6.2 Formal Deﬁnition

Let A be a sequence of an ordered set of objects:

We may express A as:

A = (a1, a2, a3, ..., aN )

{ai}N
i=1

Then an n-moving average is a new sequence {si}N −n+1

i=1

deﬁned from

139

the ai by taking the arithmetic mean of subsequences of n terms,

si =

1
n

i+n−1
(cid:88)

j=i

aj

So the sequences Sn giving n-moving averages are

S2 = 1
S3 = 1
S4 = 1
...

2 p(a1 + a2), (a2 + a3), ..., (an−1 + an)q
3 p(a1 + a2 + a3), (a2 + a3 + a4), ..., (an−2 + an−1 + an)q
4 p(a1 + a2 + a3 + a4), (a2 + a3 + a4 + a5), ..., (an−3 + an−2 + an−1 + an)q

6.3 Moving Average by POJO

For solving moving average, we prodide two POJO solutions:

• First solution: using java.util.Queue

• Second Solution : using array and simulating queue

In both solutions, we take a window (as a queue data structure) and ﬁll
it in a First-In-First-Out (FIFO) manner with time series data points until
we have N points in it (averge/mean of these N points will be the moving
average).

6.3.1 First solution: using Queue

This solution uses a queue data structure implemented by java.util.Queue.
At any time, we make sure that we keep only the required items (the size of
moving average window size) in the queue.

Listing 6.1: SimpleMovingAverage Class

1 import java.util.Queue;
2 import java.util.LinkedList;
3 public class SimpleMovingAverage {
4

5

private double sum = 0.0;

140

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

private final int period;
private final Queue<Double> window = new LinkedList<Double>();

public SimpleMovingAverage(int period) {

if (period < 1) {

throw new IllegalArgumentException("period must be > 0");

}
this.period = period;

}

public void addNewNumber(double number) {

sum += number;
window.add(number);
if (window.size() > period) {

sum -= window.remove();

}

}

public double getMovingAverage() {

if (window.isEmpty()) {

throw new IllegalArgumentException("average is undefined");

}
return sum / window.size();

}

29
30 }

6.3.2 Second Solution : using Array

This solution uses a simple array (called window) and simulates enqueue and
dequeue operations. This solution is more eﬃcient but less intuitive.

Listing 6.2: SimpleMovingAverageUsingArray Class

1 public class SimpleMovingAverageUsingArray {
2

3

4

5

6

7

8

9

10

private double sum = 0.0;
private final int period;
private double[] window = null;
private int pointer = 0;
private int size = 0;

public SimpleMovingAverageUsingArray(int period) {

if (period < 1) {

141

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

throw new IllegalArgumentException("period must be > 0");

}
this.period = period;
window = new double[period];

}

public void addNewNumber(double number) {

sum += number;
if (size < period) {

window[pointer++] = number;
size++;

}
else {

// size = period (size cannot be > period)
pointer = pointer % period;
sum -= window[pointer];
window[pointer++] = number;

}

}

public double getMovingAverage() {

if (size == 0) {

throw new IllegalArgumentException("average is undefined");

}
return sum / size;

}

36
37 }

6.3.3 Testing of Moving Average

The following is a program for testing ”moving average” using SimpleMovin-
gAverage class. The program is tested by two window sizes {3, 4}.

Listing 6.3: Test SimpleMovingAverage

1 import org.apache.log4j.Logger;
2 public class TestSimpleMovingAverage {
3

private static final Logger THE_LOGGER =

4

5

6

7

Logger.getLogger(TestSimpleMovingAverage.class);

public static void main(String[] args) {

// time series
double[] testData = {10, 18, 20, 30, 24, 33, 27};

4

7

5

1

2

3

6

142

int[] allWindowSizes = {3, 4};
for (int windowSize : allWindowSizes) {

SimpleMovingAverage sma = new SimpleMovingAverage(windowSize);
THE_LOGGER.info("windowSize = " + windowSize);
for (double x : testData) {
sma.addNewNumber(x);
THE_LOGGER.info("Next number = " + x + ", SMA = " + sma.getMovingAverage());

}
THE_LOGGER.info("---");

}

8

9

10

11

12

13

14

15

16

17

}

18
19 }

6.3.4 Sample Run

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

# javac SimpleMovingAverage.java
# javac TestSimpleMovingAverage.java
# java TestSimpleMovingAverage
13/10/10 22:24:08 INFO TestSimpleMovingAverage: windowSize = 3
13/10/10 22:24:08 INFO TestSimpleMovingAverage: Next number = 10.0, SMA = 10.00
13/10/10 22:24:08 INFO TestSimpleMovingAverage: Next number = 18.0, SMA = 14.00
13/10/10 22:24:08 INFO TestSimpleMovingAverage: Next number = 20.0, SMA = 16.00
13/10/10 22:24:08 INFO TestSimpleMovingAverage: Next number = 30.0, SMA = 22.66
13/10/10 22:24:08 INFO TestSimpleMovingAverage: Next number = 24.0, SMA = 24.66
13/10/10 22:24:08 INFO TestSimpleMovingAverage: Next number = 33.0, SMA = 29.00
13/10/10 22:24:08 INFO TestSimpleMovingAverage: Next number = 27.0, SMA = 28.00
13/10/10 22:24:08 INFO TestSimpleMovingAverage: ------
13/10/10 22:24:08 INFO TestSimpleMovingAverage: windowSize = 4
13/10/10 22:24:08 INFO TestSimpleMovingAverage: Next number = 10.0, SMA = 10.00
13/10/10 22:24:08 INFO TestSimpleMovingAverage: Next number = 18.0, SMA = 14.00
13/10/10 22:24:08 INFO TestSimpleMovingAverage: Next number = 20.0, SMA = 16.00
13/10/10 22:24:08 INFO TestSimpleMovingAverage: Next number = 30.0, SMA = 19.50
13/10/10 22:24:08 INFO TestSimpleMovingAverage: Next number = 24.0, SMA = 23.00
13/10/10 22:24:08 INFO TestSimpleMovingAverage: Next number = 33.0, SMA = 26.75
13/10/10 22:24:08 INFO TestSimpleMovingAverage: Next number = 27.0, SMA = 28.50
13/10/10 22:24:08 INFO TestSimpleMovingAverage: ------

6.4 MapReduce Solution

Now that we understand the concept of a moving average for time series
data, we will focus on MapReduce solution for ”moving average” problem.
Implementation will be provided by using Apache Hadoop. We will see that
MapReduce is a very powerful framework for solving moving averge for a lot

143

of time series data (such as stocks for over long period of time). Calculation
of ”moving average” will be done in the reduce() function, where we have
all required data for a speciﬁc time series.

6.4.1

Input

The input to our MapReduce will have the following format:

<name-as-string><,><date-as-timestamp><,><value-as-double>

A sample example is of stock prices is provided for three stock symbols
(GOOG, AAPL, and IBM). Here we listed stock prices for few companies:
the ﬁrst column is the stock symbol, the next ﬁeld is the timestamp, and the
last ﬁeld is the adjusted closed price of the stock on that day – provided by
timestamp):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

GOOG,2004-11-04,184.70
GOOG,2004-11-03,191.67
GOOG,2004-11-02,194.87
AAPL,2013-10-09,486.59
AAPL,2013-10-08,480.94
AAPL,2013-10-07,487.75
AAPL,2013-10-04,483.03
AAPL,2013-10-03,483.41
IBM,2013-09-30,185.18
IBM,2013-09-27,186.92
IBM,2013-09-26,190.22
IBM,2013-09-25,189.47
GOOG,2013-07-19,896.60
GOOG,2013-07-18,910.68
GOOG,2013-07-17,918.55

6.4.2 Output

The output to our MapReduce will have the following format:

<name-as-string><,><date-as-timestamp><,><moving-averge-as-double>

A sample example of output is provided below:

Name: GOOG, Date: 2013-07-17
Name: GOOG, Date: 2013-07-18
Name: GOOG, Date: 2013-07-19

Moving Average: 912.52
Moving Average: 912.01
Moving Average: 916.39

144

By knowing the moving average algorithm, we just need to group data
based on the stock symbol, and then sort the values based on the timestamp
and then ﬁnally apply the moving average algorithm. There are at least two
ways to sort our time series data:

• Option-1 : Sort the time series data in memory (RAM) per reducer
key. This option has one problem: if you do not have enough RAM for
your reducer’s sort operation, then this option will not work.

• Option-2 : Let the MapReduce framework to do the sorting for the
time series data (one of the main features of a MapReduce framework
is sorting a grouping and Hadoop does a pretty good job on this). This
option is much more scalable than Option-1 and sorting is performed
by the sort() and shuﬄe() functions of MapReduce Framework. Using
this option, we do need to alter key-value pairs and write some plugin
classes to perform secondary sorting.

We will provide solutions to both options.

6.4.3 MapReduce Solution: Option-1: sort in RAM

The mapper accepts a row of input as

<name-as-string><,><timestamp><,><value-as-double>

and emits key-value pairs, where key is the <name-as-string> and value is
<timestamp><,><value-as-double>. The reducer will receive key-values,
where key is the <name-as-string> and values will be a un-ordered list of
<timestamp><,><value-as-double>.

6.4.3.1 Time Series Data

Time series data is represented as a TimeSeriesData object, which is il-
lustrated beow. This class implements Writable (since these objects will
persist in Hadoop) and Comparable<TimeSeriesData> (since we will do in
memeory sorting on these objetcs).

Listing 6.4: TimeSeriesData Class

145

1 import org.apache.hadoop.io.Writable;
2 ...
3 /**
4 *
5 * TimeSeriesData represents a pair of
6 * (time-series-timestamp, time-series-value).
7 *
8 */
9 public class TimeSeriesData
10

implements Writable, Comparable<TimeSeriesData> {

11

12

13

14

15

16

17

18

19

20

21

22
23 }

private long timestamp;
private double value;

public static TimeSeriesData copy(TimeSeriesData tsd) {
return new TimeSeriesData(tsd.timestamp, tsd.value);

}

public TimeSeriesData(long timestamp, double value) {

set(timestamp, value);

}
...

6.4.3.2 The Mapper Function

Listing 6.5: The Mapper Function

1 /**
2 * @param key is the <name-as-string>
3 * @param value is the <timestamp><,><value-as-double>
4 */
5 map(key, value) {
6

TimeSeriesData timeseries = new TimeSeriesData(value.timestamp, value.value-as-double);
emit(key, timeseries);

7
8 }

6.4.3.3 The Reducer Function

146

Listing 6.6: The Reducer Function

1 public class MovingAverageSortInRAM_Reducer {
2

private int windowSize = 4; //default

/**

* called once at the start of the reducer task
*/

setup() {

// "moving.average.window.size" will be set at the driver
// configuration is MRF’s configuration object
windowSize = configuration.get("moving.average.window.size");

}

/**

* @param key is the <name-as-string>
* @param value is a List<TimeSeriesData>
* where TimeSeriesData represents a pair of (timestamp, value)
*/

reduce(key, values) {

List<TimeSeriesData> sortedTimeSeries = sort(values);

// call movingAverge(sortedTimeSeries, windowSize) and emit output(s)
// apply moving average algorithm to sortedTimeSeries
double sum = 0.0;
// calculate prefix sum
for (int i=0; i < windowSize-1; i++) {

sum += sortedTimeSeries.get(i).getValue();

}

// now we have enough timeseries data to calculate moving average
for (int i = windowSize-1; i < sortedTimeSeries.size(); i++) {

sum += sortedTimeSeries.get(i).getValue();
double movingAverage = sum / windowSize;
long timestamp = sortedTimeSeries.get(i).getTimestamp();
Text outputValue = timestamp+ "," + movingAverage;
// send output to distributed file system
emit(key, outputValue);

// prepare for next iteration
sum -= sortedTimeSeries.get(i-windowSize+1).getValue();

}

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 }

147

6.4.4 Hadoop Implementation: sort in RAM

Our Hadoop implementation is comprised of the following classes:

Class name
SortInMemory_MovingAverageDriver
SortInMemory_MovingAverageMapper
SortInMemory_MovingAverageReducer Deﬁnes reduce()
TimeSeriesData

Description
A driver program to submit Hadoop jobs
Deﬁnes map()

Represents a time series data point
expressed as a pair of (timestamp, double)
Provides basic Date conversion utilities
Provides basic Hadoop utilities

DateUtil
HadoopUtil

6.4.5 Sample Run

mahmoud@Mahmouds-MacBook:~/zmp/map_reduce_book/hadooptests/moving_average/sort_in_memory# hadoop fs -cat /moving_average/sort_in_memory/input/*
GOOG,2004-11-04,184.70
GOOG,2004-11-03,191.67
GOOG,2004-11-02,194.87
AAPL,2013-10-09,486.59
AAPL,2013-10-08,480.94
AAPL,2013-10-07,487.75
AAPL,2013-10-04,483.03
AAPL,2013-10-03,483.41
IBM,2013-09-30,185.18
IBM,2013-09-27,186.92
IBM,2013-09-26,190.22
IBM,2013-09-25,189.47
GOOG,2013-07-19,896.60
GOOG,2013-07-18,910.68
GOOG,2013-07-17,918.55

#/bin/bash

148

export HADOOP_HOME=/Users/mahmoud/zmp/zs/hadoop
export HADOOP_HOME_WARN_SUPPRESS=true

export JAVA_HOME=‘/usr/libexec/java_home‘
echo "JAVA_HOME=$JAVA_HOME"

PATH=.:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
export PATH=$PATH:$HADOOP_HOME/bin:$JAVA_HOME/bin

CLASSPATH=.:$HADOOP_HOME/conf
HADOOP_JAR_FILES=‘find $HADOOP_HOME -name ’hadoop*.jar’‘
for hadoopjarfile in $HADOOP_JAR_FILES ; do

CLASSPATH=$CLASSPATH:$hadoopjarfile

done

export TESTS=/Users/mahmoud/zmp/map_reduce_book/hadooptests
LIB_DIR=$TESTS/lib
JAR_FILES=‘find $LIB_DIR -name ’*.jar’‘
for jarfile in $JAR_FILES ; do

CLASSPATH=$CLASSPATH:$jarfile

done

export JAR=$TESTS/moving_average/sort_in_memory/sort_in_memory.jar
export CLASSPATH=$CLASSPATH:$JAR
export HADOOP_CLASSPATH=$CLASSPATH

javac *.java
jar cvf $JAR *.class
$HADOOP_HOME/bin/hadoop fs -rm /lib/sort_in_memory.jar
$HADOOP_HOME/bin/hadoop fs -put $JAR /lib/
export INPUT=/moving_average/sort_in_memory/input
export OUTPUT=/moving_average/sort_in_memory/output
$HADOOP_HOME/bin/hadoop fs -rmr $OUTPUT
export driver=SortInMemory_MovingAverageDriver
export WINDOW_SIZE=2
$HADOOP_HOME/bin/hadoop jar $JAR $driver $WINDOW_SIZE $INPUT $OUTPUT

149

mahmoud@Mahmouds-MacBook:~/zmp/map_reduce_book/hadooptests/moving_average/sort_in_memory# ./run.sh
...
Deleted hdfs://localhost:9000/moving_average/sort_in_memory/output
args[0]: <window_size>=2
args[1]: <input>=/moving_average/sort_in_memory/input
args[2]: <output>=/moving_average/sort_in_memory/output
...
14/05/12 15:07:03 INFO mapred.JobClient: Running job: job_201405121349_0009
14/05/12 15:07:04 INFO mapred.JobClient: map 0% reduce 0%
14/05/12 15:07:09 INFO mapred.JobClient: map 100% reduce 0%
14/05/12 15:07:17 INFO mapred.JobClient: map 100% reduce 3%
...
14/05/12 15:07:53 INFO mapred.JobClient: map 100% reduce 86%
14/05/12 15:07:54 INFO mapred.JobClient: map 100% reduce 100%
14/05/12 15:07:55 INFO mapred.JobClient: Job complete: job_201405121349_0009
...
14/05/12 15:07:55 INFO mapred.JobClient:
14/05/12 15:07:55 INFO mapred.JobClient:
14/05/12 15:07:55 INFO mapred.JobClient:
14/05/12 15:07:55 INFO mapred.JobClient:
14/05/12 15:07:55 INFO mapred.JobClient:
14/05/12 15:07:55 INFO mapred.JobClient:
14/05/12 15:07:55 INFO mapred.JobClient:
14/05/12 15:07:55 INFO mapred.JobClient:
14/05/12 15:07:55 INFO mapred.JobClient:
14/05/12 15:07:55 INFO mapred.JobClient:
14/05/12 15:07:55 INFO mapred.JobClient:
14/05/12 15:07:55 INFO mapred.JobClient:
14/05/12 15:07:55 INFO mapred.JobClient:
14/05/12 15:07:55 INFO mapred.JobClient:

Map output materialized bytes=401
Map input records=15
Reduce shuffle bytes=401
Spilled Records=30
Map output bytes=311
Total committed heap usage (bytes)=1034620928
Combine input records=0
SPLIT_RAW_BYTES=133
Reduce input records=15
Reduce input groups=3
Combine output records=0
Reduce output records=12
Map output records=15

Map-Reduce Framework

# hadoop fs -cat /moving_average/sort_in_memory/output/part*
GOOG 2004-11-03,193.26999999999998
GOOG 2004-11-04,188.18499999999997
GOOG 2013-07-17,551.625

150

GOOG 2013-07-18,914.615
GOOG 2013-07-19,903.6400000000001
AAPL 2013-10-04,483.22
AAPL 2013-10-07,485.39
AAPL 2013-10-08,484.345
AAPL 2013-10-09,483.765
IBM 2013-09-26,189.845
IBM 2013-09-27,188.57
IBM 2013-09-30,186.05

6.4.6 MapReduce Solution: Option-2: Sort by MR

Framework

In previous sections, we showed that how to solve moving average problem
using MapReduce framework for lots of time series data by grouping by name
and then sorting (by timestamp) time series values in memory. There is
a problem with sorting data in memory:
if you have a lot of data, then it
might not ﬁt in memory (unless you have a lot of RAM in all cluster nodes,
which is not the case to date, since memory is not as cheap as hard disks).
In this section, we will show how to use MRF (MapReduce Framework) to
do sorting of data without sorting in memory. When MRF does sorting by
shuﬄing, it is called as ”secondary sorting.” For example, in Hadoop, we can
sort the data by the shuffle phase of MapReduce framework. The question
is how this ”secondary sorting” will be accomplished. We do need to write
some additional plug-in custom Java classes, which will be plugged-in to the
MapReuce’s framework.

How do we plug-in the custom Java classes to accomplish sorting by MRF?
We set these classes in the driver class:

Listing 6.7: The SortByMRF˙MovingAverageDriver Class

1 import ...
2 /**
3

* MapReduce job for moving averages of time series data by
* using MapReduce’s "secondary sort" (sort by shuffle function).
*/

4

5

151

6 public class SortByMRF_MovingAverageDriver {
7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

public static void main(String[] args) throws Exception {

Configuration conf = new Configuration();
JobConf jobconf = new JobConf(conf, SortByMRF_MovingAverageDriver.class);
...

// the following 3 setting are needed for "secondary sorting"
// Partitioner decides which mapper output goes to which reducer
// based on mapper output key. In general, different key is in
// different group (Iterator at the reducer side). But sometimes,
// we want different key in the same group. This is the time for
// Output Value Grouping Comparator, which is used to group mapper
// output (similar to group by condition in SQL). The Output Key
// Comparator is used during sort stage for the mapper output key.
jobconf.setPartitionerClass(NaturalKeyPartitioner.class);
jobconf.setOutputKeyComparatorClass(CompositeKeyComparator.class);
jobconf.setOutputValueGroupingComparator(NaturalKeyGroupingComparator.class);

JobClient.runJob(jobconf);

}

26
27 }

To implement ”secondary sort” for moving average, we need to make the
mapper’s output key as a composite of the natural key (name-as-string) and
the natural value (timeseries-timestamp). The following diagram ( 6.1) illus-
trates the natural and composite keys needed.

The custom CompositeKey (comprised of "name" and "timestamp") is

deﬁned as:

Listing 6.8: CompositeKey Class Deﬁnition

1 import org.apache.hadoop.io.WritableComparable;
2 ...
3 public class CompositeKey
4

implements WritableComparable<CompositeKey> {
// composite key is a pair (name, timestamp)
private String name;
private long timestamp;
...

5

6

7

8
9 }

152

Figure 6.1: Composite and Natural Keys

153

The CompositeKey class has to implement WritableComparable inter-
face, since these objects will persist in HDFS. Therefore, the custom CompositeKey
class gives Hadoop the needed information during the shuﬄe to perform a
sort on two ﬁelds ("name" and "timestamp") rather than the ("name") only.
But how the CompositeKey objects will be sorted? We do need to provide a
class that provides comparsion of CompositeKey objects. This comparison
is accomplished by the CompositeKeyComparator class (the main function
of this class is to provide the compare() method):

Listing 6.9: CompositeKeyComparator Class

1 import org.apache.hadoop.io.WritableComparable;
2 import org.apache.hadoop.io.WritableComparator;
3 public class CompositeKeyComparator extends WritableComparator {
4

protected CompositeKeyComparator() {
super(CompositeKey.class, true);

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

}

@Override
public int compare(WritableComparable w1, WritableComparable w2) {

CompositeKey key1 = (CompositeKey) w1;
CompositeKey key2 = (CompositeKey) w2;

int comparison = key1.getName().compareTo(key2.getName());
if (comparison == 0) {

// names are equal here
if (key1.getTimestamp() == key2.getTimestamp()) {

return 0;

}
else if (key1.getTimestamp() < key2.getTimestamp()) {

return -1;

}
else {

return 1;

}

}
else {

return comparison;

}

}

29
30 }

WritableComparator is a Comparator for WritableComparable(s). This

154

base implemenation uses the natural ordering. To deﬁne alternate orderings,
we had to override compare(WritableComparable,WritableComparable)
method. So sorting of the CompositeKey (the combination of the natural
key — name — and the natural value — timestamp —) objects is provided
by the custom CompositeKeyComparator class.

Now that we know how the composite keys will be sorted, the next ques-
tion is how will data arrive to reducers? This will be done by another cus-
tom class: NaturalKeyPartitioner, which implements the Partitioner1
interface, which partitions the key space generated by all mappers. Even
though all keys are sorted by the whole CompositeKey (comprised of name
and timestamp), but in partitioning we will use only by the name and the
reason is that we want all the sorted values with the same name to go to a
single reducer.

Here is the code for our custom partitioner called NaturalKeyPartitioner:

Listing 6.10: CompositeKey Class Deﬁnition

1 import org.apache.hadoop.mapred.JobConf;
2 import org.apache.hadoop.mapred.Partitioner;
3 public class NaturalKeyPartitioner implements
4

Partitioner<CompositeKey, TimeSeriesData> {

5

6

7

8

9

10

11

12

13

14

15

16

17

@Override
public int getPartition(CompositeKey key,

TimeSeriesData value,
int numberOfPartitions) {
return Math.abs((int) (hash(key.getName()) % numberOfPartitions));

}

@Override
public void configure(JobConf jobconf) {
}

/**

1 org.apache.hadoop.mapred.Partitioner. The Partitioner controls the parti-
tioning of the keys of the intermediate map-outputs. The key (or a subset of the key) is
used to derive the partition, typically by a hash function. The total number of par-
titions is the same as the number of reduce tasks for the job. Hence this controls
which of the m reduce tasks the intermediate key (and hence the record) is sent for
reduction. (source: http://hadoop.apache.org/docs/current/api/index.html?org/
apache/hadoop/mapred//class-usePartitioner.html)

155

18

19

20

21

22

23

24

25

26

* adapted from String.hashCode()
*/

static long hash(String str) {

long h = 1125899906842597L; // prime
int length = str.length();
for (int i = 0; i < length; i++) {

h = 31*h + str.charAt(i);

}
return h;

}

27
28 }

The last piece of a plug-in class is NaturalKeyGroupingComparator, which
is used during Hadoop’s shuﬄe phase to group composite keys by the natural
part of their key (in our example, the ﬁrst components of composite key is
the name component.

Listing 6.11: NaturalKeyGroupingComparator Class Deﬁnition

1 import org.apache.hadoop.io.WritableComparable;
2 import org.apache.hadoop.io.WritableComparator;
3 /**
4 *
5 * NaturalKeyGroupingComparator
6 *
7 * This class is used during Hadoop’s shuffle phase to
8 * group composite key’s by the natural of their key.
9 * The natural key for time series data is the "name".
10 *
11 */
12 public class NaturalKeyGroupingComparator extends WritableComparator {
13

protected NaturalKeyGroupingComparator() {

14

15

16

17

18

19

20

21

22

super(CompositeKey.class, true);

}

@Override
public int compare(WritableComparable w1, WritableComparable w2) {

CompositeKey key1 = (CompositeKey) w1;
CompositeKey key2 = (CompositeKey) w2;
// natural keys are: key1.getName() and key2.getName()
return key1.getName().compareTo(key2.getName());

23
24 }

}

156

The following classes are used to implement ”moving average” by sorting
reducer’s values by using the MapReducer’s framework.

Class name
MovingAverage
SortByMRF_MovingAverageDriver
SortByMRF_MovingAverageMapper
SortByMRF_MovingAverageReducer Deﬁnes reduce()
TimeSeriesData

Description
A simple moving average algorithm
A driver program to submit Hadoop jobs
Deﬁnes map()

Represents a time series data point
expressed as a pair of (timestamp, double)
Deﬁnes a custom composite key
of (string, timestamp)
deﬁnes sorting order for CompositeKey
partitions the data output from the map phase
before it is sent through the shuﬄe phase.
this class is used during Hadoop’s
shuﬄe phase to group composite Key’s
by the ﬁrst part (natural) of their key.
Provides basic Date conversion utilities
Provides basic Hadoop utilities

CompositeKey

CompositeKeyComparator
NaturalKeyPartitioner

NaturalKeyGroupingComparator

DateUtil
HadoopUtil

6.5 Sample Run

6.5.0.1 HDFS Input

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# hadoop fs -cat /moving_average/sort_by_mrf/input/*
GOOG,2004-11-04,184.70
GOOG,2004-11-03,191.67
GOOG,2004-11-02,194.87
AAPL,2013-10-09,486.59
AAPL,2013-10-08,480.94
AAPL,2013-10-07,487.75
AAPL,2013-10-04,483.03
AAPL,2013-10-03,483.41
IBM,2013-09-30,185.18
IBM,2013-09-27,186.92
IBM,2013-09-26,190.22
IBM,2013-09-25,189.47
GOOG,2013-07-19,896.60
GOOG,2013-07-18,910.68
GOOG,2013-07-17,918.55

157

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

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

6.5.0.2 Sample Script

# cat run.sh
#/bin/bash
export HADOOP_HOME=/Users/mahmoud/zmp/zs/hadoop
export HADOOP_HOME_WARN_SUPPRESS=true

export JAVA_HOME=‘/usr/libexec/java_home‘
echo "JAVA_HOME=$JAVA_HOME"

PATH=.:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
export PATH=$PATH:$HADOOP_HOME/bin:$JAVA_HOME/bin

#CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
CLASSPATH=.:$HADOOP_HOME/conf
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-ant-1.2.1.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-core-1.2.1.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-examples-1.2.1.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-test-1.2.1.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-tools-1.2.1.jar

export TESTS=/Users/mahmoud/zmp/map_reduce_book/hadooptests
LIB_DIR=$TESTS/lib
JAR_FILES=‘find $LIB_DIR -name ’*.jar’‘
for jarfile in $JAR_FILES ; do

CLASSPATH=$CLASSPATH:$jarfile

done

export JAR=$TESTS/moving_average/sort_by_mrf/sort_by_mrf.jar
export CLASSPATH=$CLASSPATH:$JAR
export HADOOP_CLASSPATH=$CLASSPATH

javac *.java
jar cvf $JAR *.class
$HADOOP_HOME/bin/hadoop fs -rm /lib/sort_by_mrf.jar
$HADOOP_HOME/bin/hadoop fs -put $JAR /lib/
export input=/moving_average/sort_by_mrf/input
export output=/moving_average/sort_by_mrf/output
$HADOOP_HOME/bin/hadoop fs -rmr $output
export driver=SortByMRF_MovingAverageDriver
export window_size=2
$HADOOP_HOME/bin/hadoop jar $JAR $driver

$window_size $input $output

6.5.0.3 Script Run

map 0% reduce 0%
map 25% reduce 0%

map 100% reduce 86%
map 100% reduce 100%

# ./run.sh
...
Deleted hdfs://localhost:9000/moving_average/sort_by_mrf/output
...
14/05/12 16:15:29 INFO mapred.JobClient: Running job: job_201405121612_0002
14/05/12 16:15:30 INFO mapred.JobClient:
14/05/12 16:15:36 INFO mapred.JobClient:
...
14/05/12 16:16:31 INFO mapred.JobClient:
14/05/12 16:16:32 INFO mapred.JobClient:
14/05/12 16:16:33 INFO mapred.JobClient: Job complete: job_201405121612_0002
...
14/05/12 16:16:33 INFO mapred.JobClient:
14/05/12 16:16:33 INFO mapred.JobClient:
14/05/12 16:16:33 INFO mapred.JobClient:
14/05/12 16:16:33 INFO mapred.JobClient:
14/05/12 16:16:33 INFO mapred.JobClient:
14/05/12 16:16:33 INFO mapred.JobClient:
14/05/12 16:16:33 INFO mapred.JobClient:
...
14/05/12 16:16:33 INFO mapred.JobClient:
14/05/12 16:16:33 INFO mapred.JobClient:
14/05/12 16:16:33 INFO mapred.JobClient:
14/05/12 16:16:33 INFO mapred.JobClient:
14/05/12 16:16:33 INFO mapred.JobClient:

Reduce input records=15
Reduce input groups=3
Combine output records=0
Reduce output records=15
Map output records=15

Map-Reduce Framework

Map output materialized bytes=3176
Map input records=15
Reduce shuffle bytes=3176
Spilled Records=30
Map output bytes=446
Total committed heap usage (bytes)=4545941504

158

6.5.0.4 Generated Output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

2004-11-02,194.87
2004-11-03,193.26999999999998
2004-11-04,188.185
2013-07-17,551.625
2013-07-18,914.6149999999999
2013-07-19,903.64
2013-10-03,483.41
2013-10-04,483.22
2013-10-07,485.39
2013-10-08,484.345
2013-10-09,483.765

# hadoop fs -cat /moving_average/sort_by_mrf/output/part*
GOOG
GOOG
GOOG
GOOG
GOOG
GOOG
AAPL
AAPL
AAPL
AAPL
AAPL
IBM
IBM
IBM
IBM

2013-09-25,189.47
2013-09-26,189.845
2013-09-27,188.57
2013-09-30,186.04999999999995

159

Chapter 7

Market Basket Analysis

7.1 What is Market Basket Analysis?

Market Basket Analysis algorithm is a popular data mining algorithm, fre-
quently used by marketing and e-commerce professionals to reveal aﬃnities
between individual products or product groupings. The general goal of data
mining is to extract interesting correlated information from a large collection
of data, for example millions of sales in supermarket or credit card trans-
actions. Finding frequent sets in mining association rules for market basket
analysis is a computationaly intensive problem. This is an ideal case for
MapReduce to solve this kind of a problem. Market basket analysis is a
technique to identify items likely to be purchased together and association
rule mining ﬁnds correlations between items in a set of transactions. Finally,
marketers may use association rules to place the items next to each other so
that users buy more items.

This chapter provides two solutions to market basket analysis:

• MapReduce/Hadoop solution to MBA for tuples of order of N (where

N=1, 2, 3, ...). This solution just ﬁnds the frequent patterns.

• Spark/Hadoop solution, which not only ﬁnds frequent patterns, but

also generates association rules for frequent patterns.

160

7.2 MapReduce/Hadoop Solution

The goal of this chapter is to present a MapReduce solution for data mining
analysis to ﬁnd the most frequently occurred pair of products (order of 1, 2,
...) in baskets at a given supermarker or e-commerce store. Our MapReduce
solution is expandable to ﬁnd the most frequently occurred Tuple-N (N=1, 2,
3, ...) of products (order of N) in baskets. The ”order of N” (as an integer)
will be passed as an argument to the MapReduce driver, which then will
set that in Hadoop’s Conﬁguration object. Finally, the map() will read that
paramter from the Hadoop’s Configuration object in the setup() method.
Once we have The most frequent item sets Fi (i=1, 2, ...) can be used to
produce association rule of the transaction. For example, if we have 5 items
{A, B, C, D, E} with the following six transactions:

Transaction 1: A, C
Transaction 2: B, D
Transaction 3: A, C, E
Transaction 4: C, E
Transaction 5: A, B, E
Transaction 6: B, E

then the goal is to build frequent item sets F1 (size = 1) and F2 (size =

2) as

• F1 = {[C, 3], [A, 3], [B, 3], [E, 4]}
• F2 = {[<A,C>, 2], [<C,E>, 2], [<A,E>, 2], [<B,E>, 2]}
Note that in this example, we applied a minimum ”support” of 2, which is
a count of how many times a frequent pattern occurs in the entire transaction
set. Thus, [D, 1] is eliminated in F1. The item sets F1 and F2 can be
used to produce association rule of the transaction. An association rule is
something like:

LHS => RHS
coke => chips
if customers purchase coke (called left-hand-side),
they also buy chips (called right-hand-side).

161

In data mining, an association rule has two metrics:

• Support: Frequency of occurrence of an itemset. For example Support({A,C})

= 2. This means that items A and C apear together only in 2 transac-
tions

• Conﬁdence: How often does the left-hand-side of the rule appear with

the right-hand-side.

Market Basket Analysis enables us to understand behavior of shoppers

• what items are bought together?

• what is in each shopping basket?

• what items should be put on sale?

• how should items be placed next to each other for maximum proﬁt? For
example if a supermarket has 10,000 or more unique items, then there
are 50 million 2-item combinations and 100 billion 3-item combinations.

• how to determine te of the catalog of an e-commerce site

To understand the main ideas of MBA, consider the picture of the shopping
cart at a checkout counter in a supermarket ﬁlled with various products pur-
chased by a customer. This basket contains a set of products: tuna, milk,
orange juice, bananas, eggs, tooth paste, window cleaner, and detergent. One
basket tells us about what one customer purchased at one time. A complete
list of purchases made by all customers (all transactions in a supermarket)
provides much more information; it describes the most important part of a
retailing businesswhat merchandise customers are buying and when. There-
fore, the purpose of MBA is how to improve sales by properly marketing
which products should be placed next to each other on the shelves, and by
carefully designing the layout of products in the catalog of an e-commerce
site. The ﬁnal goal of market basket analysis is the automatic generation of
association rules.

162

7.3 What are the Application areas for MBA?

Market Basket Analysis can be applied to supermarket shoppers and it is
important to realize that there are many other areas in which it can be
applied. These include:

• Analysis of credit card purchases

• Analysis of telephone calling patterns

• Identiﬁcation of fraudulent medical insurance claims (Consider cases

where common rules are broken)

• Analysis of telecom service purchases

• Analysis of daily/weekly purchases at Amazon.com

7.4 Market Basket Analysis using MapReduce

Since there will be a lot of big data, MapReduce is an ideal framework to do
Market Basket Analysis. We follow Market Basket Analysis Algorithm [30]
presented by Jongwook Woo and Yuhang Xu. What is the problem we are
trying to solve with MapReduce? Given a set of transactions (where each
transaction is a set of items), we want to answer this question: what is a pair
of items that people frequently buy at store.

The high-level Mapreduce algorithm is presented below. Each map()
function accepts a transaction, which is a set of items {I1, I2, ..., In} pur-
chased by a customer. A mapper ﬁrst sort (it can be ascending or descending)
items, which generates {S1, S2, ..., Sn} and then emits (key, 1) pairs, where
key = Tuple2(Si, Sj) and Si ≤ Sj. The job of combiners and reducers is to
aggregate and count the frequencies.

Before we discuss the MapReduce algorithm in detail, let’s look at the input
and expected output.

163

Figure 7.1: MapReduce Algorithm for Market Basket Analysis

164

7.4.0.5

Input

We assume that input is given as a sequence of transactions (one transaction
per-line). Transaction items are separated by spaces. Sample input will be
(red colors are not part of actual data):

Transaction 1: cracker, ice cream, coke, apple
Transaction 2: chicken, pizza, coke, bread
Transaction 3: baguette, soda, shampoo, cracker, pepsi
Transaction 4: baguette, cream cheese, diapers, milk
...

7.4.0.6 Expected Output for Tuple2 (Order of 2)

For Order of 2, we want to ﬁnd frequency of items for all unique pairs of
(Item1, Item2). Sample expected output is presented below:

Pair of Items

Frequency

...
(bear, cracker)
(baguette, eggs)
(cracker, coke)
...

...
8709
7524
4300
...

7.4.0.7 Expected Output for Tuple3 (Order of 3)

For Order of 3, we want to ﬁnd frequency of items for all unique sets of
(Item1, Item2, Item3). Sample expected output is presented below:

Triplet of Items

Frequency

...
(bear, cracker, eggs)
(baguette, diapers, eggs)
(cracker, coke, meat)
...

...
1940
1900
1843
...

165

7.4.0.8 Mapper Informal

The map() will take a single transation and generate a set of (key, value)
pairs to be consumed by reduce(). The mapper pairs the transaction items
as a key and the number of key occurrences as its value in the basket (for all
transactions and without the transaction numbers).

For example, map() for ”Transaction 1” will emit the following (key,

value) pairs:

[<cracker, icecream>, 1]
[<cracker, coke>, 1]
[<cracker, apple>, 1]
[<icecream, coke>, 1]
[<icecream, apple>, 1]
[<coke, apple>, 1]

We should note that if we select the two items in a basket as a key, there
should be incorrect counting for the occurrence of the items in the pairs. For
example, if transactions T1 and T2 have the following items

T1: cracker, ice cream, coke
T2: ice cream, coke, cracker

which have the same items but in diﬀerent order.

For transaction T1, map() will generate:

[(cracker, ice cream), 1]
[(cracker, coke), 1]
[(ice cream, coke), 1]

For transaction T2, map() will generate:

[(ice cream, coke), 1]
[(ice cream, cracker), 1]
[(coke, cracker), 1]

166

As you observe from map() outputs for transactions T1 and T2, we have a
total of 6 diﬀerent pairs of items that occur only once respectively, which
should amount to 3 diﬀerent pairs. That is, keys (cracker, ice cream)
and (ice cream, cracker) are not the same even though they are, which
is not correct. We can avoid this problem if we sort the transaction items in
alphabetical order before generating (key, value) pairs. After sorting items
in transations we will have:

Sorted T1: coke, cracker, ice cream
Sorted T2: coke, cracker, ice cream

Now each transaction (T1 and T2) has the following 3 pair of (key, value)

pairs:

[(coke, cracker), 1]
[(coke, ice cream), 1]
[(cracker, ice cream), 1)

That is TWO diﬀerent pairs of items that occur twice respectively so that
we can accumulate the value of the occurrence for these two transactions as
follows: [(coke, cracker), 2], [(coke, ice cream), 2], ((cracker, ice cream), 2),
which leads to the correct count of the total number of occurrences.

7.4.1 Mapper Formal

The Market Basket Analysis (MBA) Algorithm for Mapper is illustrated
below. Mapper reads the input data and creates a list of items for each
transaction. For each transaction, its time complexity is O(n) where n is the
number of items for a transaction. Then, the items in the transaction list
are sorted to avoid the duplicated keys; (cracker, coke) and (coke, craker)
are the same keys. Time complexity of quicksort is O(n log n). Then, the
sorted transaction items should be converted to pairs of items as keys, which
is a cross operation in order to generate cross pairs of the items in the list.

Listing 7.1: MBA map() Function

1 // key is transaction ID and ignored here
2 // value = transaction items (I1, I2, ...,In).
3 map(key, value) {
4

(S1, S2, ..., Sn) = sort(I1, I2, ...,In);

167

5

6

7

8

9

10

11

// now, we have: S1 < S2 < ... < Sn
List<Tuple2<Si, Sj>> listOfPairs =

Combinations.generateCombinations(S1, S2, ..., Sn);

for ( Tuple2<Si, Sj> pair : listOfPairs) {
// reducer key is: Tuple2<Si, Sj>
// reducer value is: integer 1
emit([Tuple2<Si, Sj>, 1]);

}

12
13 }

Combinations is a simple Java utility class, which generate combinations
of basket items for a given ”list of items” and ”number of pairs” (as 2, 3, 4,
...). Assume that (S1, S2, ..., Sn) is sorted (i.e., S1 ≤ S2 ≤ ... ≤ Sn). Then
the Combinations.generateCombinations(S1, S2, ..., Sn) method generate
all combinations between any two items in a given transaction. For example,
generateCombinations(S1, S2, S3, S4) will return the following pairs:

(S1, S2)
(S1, S3)
(S1, S4)
(S2, S3)
(S2, S4)
(S3, S4)

7.4.2 Reducer

The Market Basket Analysis (MBA) Algorithm for Reducer is illustrated
below. The reducer is to sum up the number of values per reducer key.
Thus, its time complexity is O(v) where v is the number of values per key.

Listing 7.2: MBA reduce() Function

1 // key is in form of Tuple2(Si, Sj)
2 // value = List<integer>, where each element is an integer number
3 reduce(Tuple2(Si, Sj) key, List<integer> values) {
4

integer sum = 0;
for (integer i : values) {

5

6

7

8

9
10 }

sum += i;

}

emit(key, sum);

168

7.5 MapReduce/Hadoop Implementation Classes

The hadoop implementation is comprised of the following Java classes.

Implementation Classes in MapReduce/Hadoop

Class Name Class Description
Combination A utility class to create combination of items
Submits the job to Hadoop
MBADriver
Deﬁnes map()
MBAMapper
Deﬁnes reduce()
MBAReducer

7.5.1 Find Sorted Combinations

The Combination.findSortedCombinations() is a recursive function, which
will create a unique combinations for any order of N (where N = 2, 3, ...).

Listing 7.3: Find Sorted Combinations

1 /**
2

3

4

5

6

7

8

{ [a, b], [a, c], [a, d], [b, c], [b, d], [c, d] }

* If elements = { a, b, c, d },
* then findCollections(elements, 2) will return:
*
*
* and findCollections(elements, 3) will return:
*
*
*/

{ [a, b, c], [a, b, d], [a, c, d], [b, c, d] }

9
10 public static <T extends Comparable<? super T>> List<List<T>>
11

findSortedCombinations(Collection<T> elements, int n) {

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

List<List<T>> result = new ArrayList<List<T>>();

// handle initial step for recursion
if (n == 0) {

result.add(new ArrayList<T>());
return result;

}

// handle recursion for n-1
List<List<T>> combinations = findSortedCombinations(elements, n - 1);
for (List<T> combination: combinations) {

for (T element: elements) {

if (combination.contains(element)) {

continue;

}

List<T> list = new ArrayList<T>();
list.addAll(combination);

169

if (list.contains(element)) {

continue;

}

list.add(element);
//sort items not to duplicate the items
// example: (a, b, c) and (a, c, b) might become
// different items to be counted if not sorted
Collections.sort(list);

if (result.contains(list)) {

continue;

}
result.add(list);

}

}
return result;

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47
48 }

7.5.2 Market Basket Analysis Driver: MBADriver

The driver class accepts 3 parameters and submits job to the MapReduce/Hadoop
framework. The driver also sets "number.of.pairs" conﬁguration parame-
ter to be read by mappers.

Listing 7.4: MBADriver

1 public class MBADriver extends Configured implements Tool {
2

...
public int run(String args[]) throws Exception {

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

String inputPath = args[0];
String outputPath = args[1];
int numberOfPairs = Integer.parseInt(args[2]);
...
// job configuration
Job job = new Job(getConf());
...
job.getConfiguration().setInt("number.of.pairs", numberOfPairs);

// set input/output path
FileInputFormat.setInputPaths(job, new Path(inputPath));
FileOutputFormat.setOutputPath(job, new Path(outputPath));

//Mapper K, V output
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
//output format
job.setOutputFormatClass(TextOutputFormat.class);

//Reducer K, V output
job.setOutputKeyClass(Text.class);

170

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

job.setOutputValueClass(IntWritable.class);

// set mapper/reducer/combiner
job.setMapperClass(MBAMapper.class);
job.setCombinerClass(MBAReducer.class);
job.setReducerClass(MBAReducer.class);

//delete the output path if exists to avoid "existing dir/file" error
Path outputDir = new Path(outputPath);
FileSystem.get(getConf()).delete(outputDir, true);

// submit job
boolean status = job.waitForCompletion(true);
...

}

7.5.3 Market Basket Analysis Mapper: MBAMapper

The map() function reads one transaction at a time and generates a set of
(key, value) pairs, where key is a Order-N combination of items in a given
transaction and value will be an integer 1 (to indicate this combination has
been seen once). The mapper’s setup() method reads "number.of.pairs"
from Hadoop’s Conﬁguration object.

Listing 7.5: MBAMapper

1 public class MBAMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

public static final int DEFAULT_NUMBER_OF_PAIRS = 2;

//output key2: list of items paired; can be 2 or 3 ...
private static final Text reducerKey = new Text();

//output value2: number of the paired items in the item list
private static final IntWritable NUMBER_ONE = new IntWritable(1);

int numberOfPairs; // will be read by setup(), set by driver

protected void setup(Context context)

throws IOException, InterruptedException {
this.numberOfPairs = context.getConfiguration()

.getInt("number.of.pairs", DEFAULT_NUMBER_OF_PAIRS);

}

public void map(LongWritable key, Text value, Context context)

throws IOException, InterruptedException {
String line = value.toString().trim();
List<String> items = convertItemsToList(line);
if ((items == null) || (items.isEmpty())) {
// no mapper output will be generated

171

25

26

27

28

29

30

31

32

33

34

35

return;

}
generateMapperOutput(numberOfPairs, items, context);

}

private static List<String> convertItemsToList(String line) {

// see the next section

}

private void generateMapperOutput(...){

// see the next section

}

36
37 }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

Listing 7.6: MBAMapper Helper Methods: convertItemsToList

private static List<String> convertItemsToList(String line) {

if ((line == null) || (line.length() == 0)) {
// no mapper output will be generated
return null;

}
String[] tokens = StringUtils.split(line, ",");
if ( (tokens == null) || (tokens.length == 0) ) {

return null;

}
List<String> items = new ArrayList<String>();
for (String token : tokens) {
if (token != null) {

items.add(token.trim());

}

}
return items;

}

Listing 7.7: MBAMapper Helper Methods: generateMapperOutput

/**
*
* This method builds set of <key, value> by sorting the input list.
* key is a combination of items in a transation, and value = 1.
* Sorting is required to make sure that (a, b) and (b, a)
* represent the same key.
* @param numberOfPairs
* @param items
* @param context
* @throws IOException
* @throws InterruptedException
*/
private void generateMapperOutput(int numberOfPairs,

list of items (from input line)

number of pairs associated

Hadoop Job context

throws IOException, InterruptedException {

List<String> items,
Context context)

172

List<List<String>> sortedCombinations =

Combination.findSortedCombinations(items, numberOfPairs);

for (List<String> itemList: sortedCombinations) {

reducerKey.set(itemList.toString());
context.write(reducerKey, NUMBER_ONE);

}

17

18

19

20

21

22

}

23
24 }

7.5.4 Sample Run

7.5.4.1

Input

# hadoop fs -cat /market_basket_analysis/input/input.txt
cracker,bread,banana
cracker,coke,butter,coffee
cracker,bread
cracker,bread
cracker,bread,coffee
butter,coke
butter,coke,bread,cracker

7.5.4.2 Actual Run

$INPUT $OUTPUT 2

# INPUT=/market_basket_analysis/input
# OUTPUT=/market_basket_analysis/output
# $HADOOP_HOME/bin/hadoop fs -rmr $OUTPUT
# $HADOOP_HOME/bin/hadoop jar $JAR MBADriver
...
Deleted hdfs://localhost:9000/market_basket_analysis/output
14/05/02 13:36:36 INFO MBADriver: inputPath: /market_basket_analysis/input
14/05/02 13:36:36 INFO MBADriver: outputPath: /market_basket_analysis/output
14/05/02 13:36:36 INFO MBADriver: numberOfPairs: 2
...
14/05/02 13:36:37 INFO mapred.JobClient: Running job: job_201405021309_0003
14/05/02 13:36:38 INFO mapred.JobClient:
14/05/02 13:36:43 INFO mapred.JobClient:
14/05/02 13:36:51 INFO mapred.JobClient:
...
14/05/02 13:37:29 INFO mapred.JobClient:
14/05/02 13:37:30 INFO mapred.JobClient: Job complete: job_201405021309_0003
...
14/05/02 13:37:30 INFO mapred.JobClient:
14/05/02 13:37:30 INFO mapred.JobClient:
14/05/02 13:37:30 INFO mapred.JobClient:
...
14/05/02 13:37:30 INFO mapred.JobClient:
14/05/02 13:37:30 INFO mapred.JobClient:
14/05/02 13:37:30 INFO mapred.JobClient:
14/05/02 13:37:30 INFO mapred.JobClient:
14/05/02 13:37:30 INFO mapred.JobClient:
14/05/02 13:37:30 INFO mapred.JobClient:

Combine input records=21
SPLIT_RAW_BYTES=125
Reduce input records=12
Reduce input groups=12
Combine output records=12
Reduce output records=12

map 0% reduce 0%
map 100% reduce 0%
map 100% reduce 3%

Map-Reduce Framework

map 100% reduce 100%

Map output materialized bytes=328
Map input records=7

173

14/05/02 13:37:30 INFO mapred.JobClient:
14/05/02 13:37:30 INFO MBADriver: job status=true
14/05/02 13:37:30 INFO MBADriver: Elapsed time: 52737 milliseconds
14/05/02 13:37:30 INFO MBADriver: exitStatus=0

Map output records=21

7.5.4.3 Output

# hadoop fs -cat /market_basket_analysis/output/part*
[bread, coffee]
[butter, coffee]
[banana, cracker]
[butter, coke]
[coffee, cracker]
[bread, butter]
[banana, bread]
[bread, cracker]
[coke, cracker]
[bread, coke]
[coffee, coke]
[butter, cracker]

1
1
1
3
2
1
1
5
2
1
1
2

7.6 Spark/Hadoop Solution

This section presents a Spark solution for generating all ”Association Rules”
for a set of transactions. Association rules are statements of the if-then
form X → Y , which means that if we ﬁnd all of X items in the market
basket (denoted by a transaction), then we have a good chance of ﬁnding Y .
Before delving into generation of ”Association Rules”, we need some basic
deﬁnitions. Let I = {I1, I2, ..., In}: a set of items. Transaction t is deﬁned
as I = {S1, S2, ..., Sm} where {Si ∈ I} and m ≤ n Then transaction Database
T is deﬁned to be a set of transactions T = {t1, t2, ..., tn}. Therefore, each
transaction t, contains a set of items in I. Given these deﬁnitions, now, we
can deﬁne an association rule as:

X → Y, where X, Y ∈ I, and X ∩ Y = ∅

for example, we might have: X={milk, bread} and Y={cereal, sugar,
butter}. X (item set of 2 elements) and Y (item set of 3 elements) are
called the left-hand-side and right-hand-side of an association rule respec-
tively. Therefore, in a nutshell, we can say that an association rule is a
pattern that states when X occurs, then Y occurs with certain probability.
We need few more deﬁnitions before deﬁning two important metrics (”sup-
port” and ”conﬁdence”) for an association rule. An itemset is a collection of

174

one or more items. For example an itemset of Y={cereal, sugar, butter}
contains 3 elements. A support count (denoted by θ is frequency of occurance
of an itemset in all transactions. for example

θ({I1, I2}) = 3

means that among all transactions, I1 and I2 apear together in only 3 trans-
actions.

Now, we can deﬁne ”support” and ”conﬁdence” metrics for an association
rule. In data mining association rules for set of transactions, two important
metrics are deﬁned and used:

• Support:

is the fraction of transactions that contain an itemset. For
example if θ({I1, I2}) = 3 and total number of transactions is 24, then
support of {I1, I2} is deﬁned as 3
24. In frequent itemset generation,
a support threshold is used. So for a given association rule: X → Y ,
support is deﬁned as fraction of transactions that contain both X and
Y . So, we may write this as

support =

θ({I1, I2})
#of transactions

• Conﬁdence: for a given association rule: X → Y , conﬁdence basically
measures how often items in Y appear in transactions that contain
X.
In association rules generation, a conﬁdence threshold is used.
Conﬁdence can be expressed as:

conﬁdence =

θ(Y )
θ(X)

Therefore the goal is to ﬁnd all association rules that satisfy the user-
speciﬁed minimum support (minimum-support) and minimum conﬁdence
(minimum-conﬁdence). These two parameters may be pased to limit the
number of frequent set generation and ﬁnally limit emitting the association
rules. In summary, we can say that an association rule (denoted by X → Y )
is about relationships between two disjoint itemsets X and Y and it presents
the pattern when X occurs, Y also occurs in transactions.

In our solution, we will not limit frequent sets by minimum-support, but our
algorithm will calclulate the conﬁdence of every association rule generated.

175

Our spark solution ﬁnds all frequent item sets, generates all proper associ-
ation rules, and ﬁnally it calculates the conﬁdence of generated association
rules. Calculating ”support” is pretty straightforward: divide frequency of
an itemset by the total number of all transactions.

7.6.1 MapReduce Algorithm

MapReduce algorithm workﬂow is presented below. The algorithm is com-
prised of two MapReduce phases:

• Mapreduce Phase-1: mappers convert transactions to patterns and re-

ducers ﬁnd frequent patterns

• MapReduce Phase-2: mappers convert frequent patterns into sub pat-
terns and ﬁnally reducers generate association rules and their associated
conﬁdence.

7.6.2

Input

Our input is a set of transactions (one transaction per line). For example,
for testin, we will use the following input (comprised of 3 transactions):

a,b,c
a,b,d
b,c
b,c

7.6.3 Spark Implementation

The spark implementation follows the two-phase MapReduce algorithm pre-
sented. First, we present all high-level steps, and then each step is presented
in detail.

176

Figure 7.2: Generating Association Rules

177

7.6.3.1 High Level Steps

We present Spark solution in a single Java driver class. This is possible due
to availability of high-level abstraction of Spark API. Overall, Spark’s API
has a higher abstraction layer than Mapreduce/hadoop and that is why we
can put 2 phases of Mapreduce algorithms in a single Java class.

Listing 7.8: High Level Steps

1 // STEP-0: import required classes and interfaces
2 public class FindAssociationRules {
3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

static JavaSparkContext createJavaSparkContext() {...}
static List<String> toList(String transaction) {...}
static List<String> removeOneItem(List<String> list, int i) {...}

public static void main(String[] args) throws Exception {

// STEP-1: handle input parameters
// STEP-2: create a Spark context object
// STEP-3: read all transactions from HDFS and create the first RDD
// STEP-4: generate frequent patterns (map() phase 1)
// STEP-5: combine/reduce frequent patterns (reduce phase 1)
// STEP-6: generate all sub-patterns (map() phase 2)
// STEP-7: combine sub-patterns
// STEP-8: generate association rules (reduce() phase 2)
System.exit(0);

}

18
19 }

STEP-4 and STEP-5 solve the ﬁrst phase of MapReduce and is illustrated

below ( 7.3).

STEP-6, STEP-7, and STEP-8 solve the second phase of MapReduce and

is illustrated below ( 7.4).

7.6.3.2 STEP-0: Import required classes and interfaces

Listing 7.9: STEP-0: import required classes and interfaces

1 // STEP-0: import required classes and interfaces
2 import java.util.List;
3 import java.util.ArrayList;
4 import scala.Tuple2;
5 import scala.Tuple3;
6 import org.apache.spark.api.java.JavaRDD;

178

Figure 7.3: Generating Association Rules: MR Phase I

179

Figure 7.4: Generating Association Rules: MR Phase I

180

7 import org.apache.spark.api.java.JavaPairRDD;
8 import org.apache.spark.api.java.JavaSparkContext;
9 import org.apache.spark.api.java.function.PairFlatMapFunction;
10 import org.apache.spark.api.java.function.FlatMapFunction;
11 import org.apache.spark.api.java.function.Function;
12 import org.apache.spark.api.java.function.Function2;
13 import org.apache.spark.SparkConf;

7.6.3.3 Create Spark Context Object

To create RDDs, you need a JavaSparkContext object. Here, I have hard-
coded the YARN’s resource manager as myserver100. For production de-
ployments, you should read these values from a conﬁguration ﬁle. This
method of creation of JavaSparkContext object is more suitable when your
run Spark applications on YARN. If you are going to use Spark cluster
(without using YARN), then you should pass "spark master URL" (such
as: spark://<spark-master-node>:<port>) to JavaSparkContext’s con-
structor.

Listing 7.10: Create Spark Context Object

1 static JavaSparkContext createJavaSparkContext() throws Exception {
2

SparkConf conf = new SparkConf();
conf.set("yarn.resourcemanager.hostname", "myserver100");
conf.set("yarn.resourcemanager.scheduler.address", "myserver100:8030");
conf.set("yarn.resourcemanager.resource-tracker.address", "myserver100:8031");
conf.set("yarn.resourcemanager.address",
conf.set("mapreduce.framework.name", "yarn");
conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
conf.set("spark.executor.memory", "1g");
JavaSparkContext ctx = new JavaSparkContext("yarn-cluster", "FindAssociationRules", conf);
return ctx;

"myserver100:8032");

3

4

5

6

7

8

9

10

11
12 }

7.6.3.4 Utility List Functions

The toList() accepts a transaction (items separated by ”,”) and returns list
of items. The removeOneItem() removes a single item from a given list and
returns a new list with that item removed (used for generating the LHS of
association rules).

181

Listing 7.11: Utility List Functions

1 static List<String> toList(String transaction) {
2

String[] items = transaction.trim().split(",");
List<String> list = new ArrayList<String>();
for (String item : items) {

3

4

5

6

list.add(item);

}
return list;

7
8 }
9
10 static List<String> removeOneItem(List<String> list, int i) {
11

if ( (list == null) || (list.isEmpty()) ) {

return list;

}
if ( (i < 0) || (i > (list.size()-1)) ) {

return list;

}
List<String> cloned = new ArrayList<String>(list);
cloned.remove(i);
return cloned;

12

13

14

15

16

17

18

19
20 }

7.6.3.5 STEP-1: handle input parameters

This step reads the transactions ﬁle parameter supplied by command line.

Listing 7.12: STEP-1: handle input parameters

1

2

3

4

5

6

// STEP-1: handle input parameters
if (args.length < 1) {

System.err.println("Usage: FindAssociationRules <transactions>");
System.exit(1);

}
String transactionsFileName =

args[0];

7.6.3.6 STEP-2: create a Spark context object

This step creates a JavaSparkContext object, which is suitable for running
Spark applications on YARN. If you want to run your application on a Spark
cluster (rather than YARN), then you may use the following Spark API:

public JavaSparkContext(String master,

String appName)

Parameters:

182

master - Cluster URL to connect to (e.g. spark://host:port)
appName - A name for your application, to display on the cluster web UI

1

2

1

2

3

Listing 7.13: STEP-2: create a Spark context object

// STEP-2: create a Spark context object
JavaSparkContext ctx = createJavaSparkContext();

7.6.3.7 STEP-3: Read Transactions from HDFS

This step reads all transactions from an HDFS ﬁle and creates the ﬁrst RDD
(JavaRDD<String>), where each item is a transaction.

Listing 7.14: STEP-3: read all transactions from HDFS

// STEP-3: read all transactions from HDFS and create the first RDD
JavaRDD<String> transactions = ctx.textFile(transactionsFileName, 1);
transactions.saveAsTextFile("/rules/output/1");

For debugging purposes, we write the intermediate data to HDFS. Here,

we just emit all raw transactions.

# hadoop fs -cat /rules/output/1/part*
a,b,c
a,b,d
b,c
b,c

7.6.3.8 STEP-4: generate frequent patterns

This step generates all patterns for a given transaction. For examle, given a
transaction with 3 items: "a, b, c", the mappers emits the following (K,V)
pairs:

183

hadoop fs -cat /rules/output/1/part*
Key Value
1
a
1
b
1
c
1
a,b
1
a,c
1
b,c
1
a,b,c

Here is the deﬁnition of the mapper, which generates all patterns. Typically,
in market basket analysis, you might select patterns of length two or three.
Selecting all patterns might be very time consuming process. Here to generate
all patterns, we use a recursive function:

List<List<String>> Combination.findSortedCombinations(List<String>)

For example, findSortedCombinations(List<a, b, c, d>) generates:

[

]

[],
[a],
[b],
[c],
[d],
[a, b],
[a, c],
[a, d],
[b, c],
[b, d],
[c, d],
[a, b, c],
[a, b, d],
[a, c, d],
[b, c, d],
[a, b, c, d]

Note that combinations are always sorted, for example, for list of 2 items
{a, b}, we always create [a, b] (we never create [b, a]). Having sorted
item sets enable us to avoid duplicates. Deﬁnition of the Combination class
is given at the end of this chapter.

Listing 7.15: STEP-4: generate frequent patterns

184

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

// STEP-4: generate frequent patterns
// PairFlatMapFunction<T, K, V>
// T => Iterable<Tuple2<K, V>>
JavaPairRDD<List<String>,Integer> patterns =

transactions.flatMapToPair(new PairFlatMapFunction<

// T
String,
List<String>, // K
// V
Integer

>() {

public Iterable<Tuple2<List<String>,Integer>> call(String transaction) {

List<String> list = toList(transaction);
List<List<String>> combinations = Combination.findSortedCombinations(list);
List<Tuple2<List<String>,Integer>> result =

new ArrayList<Tuple2<List<String>,Integer>>();

for (List<String> combList : combinations) {

if (combList.size() > 0) {

result.add(new Tuple2<List<String>,Integer>(combList, 1));

}

}
return result;

}

});
patterns.saveAsTextFile("/rules/output/2");

Here is the ouput of STEP-4:

# hadoop fs -cat /rules/output/2/part*
([a],1)
([b],1)
([c],1)
([a, b],1)
([a, c],1)
([b, c],1)
([a, b, c],1)
([a],1)
([b],1)
([d],1)
([a, b],1)
([a, d],1)
([b, d],1)
([a, b, d],1)
([b],1)
([c],1)
([b, c],1)
([b],1)

185

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

([c],1)
([b, c],1)

7.6.3.9 STEP-5: combine/reduce frequent patterns

This step implements the reduceByKey() function for Phase-1 of MapReduce
algorithm. It ﬁnds all unique frequent patterns and their associated frequency
among all transactions.

Listing 7.16: STEP-5: combine/reduce frequent patterns

// STEP-5: combine/reduce frequent patterns
JavaPairRDD<List<String>, Integer> combined =

patterns.reduceByKey(new Function2<Integer, Integer, Integer>() {
public Integer call(Integer i1, Integer i2) {

return i1 + i2;

}

});
combined.saveAsTextFile("/rules/output/3");

K = pattern as List<String>
V = frequency of pattern

// now, we have: patterns(K,V)
//
//
// now given (K,V) as (List<a,b,c>, 2) we will
// generate the following (K2,V2) pairs:
//
//
//
//
//

(List<a,b,c>, T2(null, 2))
(List<a,b>,
(List<a,c>,
(List<b,c>,

T2(List<a,b,c>, 2))
T2(List<a,b,c>, 2))
T2(List<a,b,c>, 2))

Here is the ouput of STEP-5:

# hadoop fs -cat /rules/output/3/part*
([a, b],2)
([a, b, d],1)
([c],3)
([b, d],1)
([d],1)
([a],2)
([b, c],3)
([a, b, c],1)
([a, c],1)
([a, d],1)
([b],4)

186

7.6.3.10 STEP-6: generate all sub-patterns

This step creates all sub patterns, which are needed for creation of associa-
tion rules. Given a frequent pattern of

(K = List < A1, A2, .., An >, V = F requency),

we create the following sub-patterns (K2, V2) as:

(K2 = List < A1, A2, .., An >, V 2 = T uple2(null, F requency))
(K2 = List < A1, A2, .., An−1 >, V 2 = T uple2(K, F requency))
(K2 = List < A1, A2, .., An−2, An >, V 2 = T uple2(K, F requency))
...

For example given (K,V) as (List(a,b,c), 2) we will generate the following
(K2,V2) pairs:

Sub Patterns (K2,V2)

V2
K2
List(a,b,c) Tuple2(null, 2)
List(a,b)
List(a,c)
List(b,c)

Tuple2(List(a,b,c), 2)
Tuple2(List(a,b,c), 2)
Tuple2(List(a,b,c), 2)

Listing 7.17: STEP-6: generate all sub-patterns

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

// STEP-6: generate all sub-patterns
// PairFlatMapFunction<T, K, V>
// T => Iterable<Tuple2<K, V>>
JavaPairRDD<List<String>,Tuple2<List<String>,Integer>> subpatterns =

combined.flatMapToPair(new PairFlatMapFunction<

Tuple2<List<String>, Integer>,
List<String>,
Tuple2<List<String>,Integer>

// T
// K
// V

>() {

public Iterable<Tuple2<List<String>,Tuple2<List<String>,Integer>>>

call(Tuple2<List<String>, Integer> pattern) {

List<Tuple2<List<String>,Tuple2<List<String>,Integer>>> result =

new ArrayList<Tuple2<List<String>,Tuple2<List<String>,Integer>>>();

List<String> list = pattern._1;
Integer frequency = pattern._2;
result.add(new Tuple2(list, new Tuple2(null,frequency)));
if (list.size() == 1) {

return result;

}

187

20

21

22

23

24

25

26

27

28

29

30

// pattern has more than one items
// result.add(new Tuple2(list, new Tuple2(null,size)));
for (int i=0; i < list.size(); i++) {

List<String> sublist = removeOneItem(list, i);
result.add(new Tuple2(sublist, new Tuple2(list, frequency)));

}
return result;

}
});
subpatterns.saveAsTextFile("/rules/output/4");

Here is the ouput of STEP-6:

# hadoop fs -cat /rules/output/4/part*
([a, b],(null,2))
([b],([a, b],2))
([a],([a, b],2))
([a, b, d],(null,1))
([b, d],([a, b, d],1))
([a, d],([a, b, d],1))
([a, b],([a, b, d],1))
([c],(null,3))
([b, d],(null,1))
([d],([b, d],1))
([b],([b, d],1))
([d],(null,1))
([a],(null,2))
([b, c],(null,3))
([c],([b, c],3))
([b],([b, c],3))
([a, b, c],(null,1))
([b, c],([a, b, c],1))
([a, c],([a, b, c],1))
([a, b],([a, b, c],1))
([a, c],(null,1))
([c],([a, c],1))
([a],([a, c],1))
([a, d],(null,1))
([d],([a, d],1))
([a],([a, d],1))

188

([b],(null,4))

7.6.3.11 STEP-7: combine sub-patterns

This step groups sub patterns by key using Spark’s groupByKey() method.

Listing 7.18: STEP-7: combine sub-patterns

// STEP-7: combine sub-patterns
JavaPairRDD<List<String>,Iterable<Tuple2<List<String>,Integer>>>

rules = subpatterns.groupByKey();
rules.saveAsTextFile("/rules/output/5");

Here is the output of STEP-7:

# hadoop fs -cat /rules/output/5/part*
([a, b],[(null,2), ([a, b, d],1), ([a, b, c],1)])
([a, b, d],[(null,1)])
([c],[(null,3), ([b, c],3), ([a, c],1)])
([b, d],[([a, b, d],1), (null,1)])
([d],[([b, d],1), (null,1), ([a, d],1)])
([a],[([a, b],2), (null,2), ([a, c],1), ([a, d],1)])
([b, c],[(null,3), ([a, b, c],1)])
([a, b, c],[(null,1)])
([a, c],[([a, b, c],1), (null,1)])
([a, d],[([a, b, d],1), (null,1)])
([b],[([a, b],2), ([b, d],1), ([b, c],3), (null,4)])

7.6.3.12 STEP-8: Generate Association Rules

Now, given a frequent pattern and all sub patterns, we will be able to generate
all association rules and their associated ”conﬁdence” value. This step is
implemented by JavaPairRDD.map() function.

Listing 7.19: STEP-8: generate association rules

// STEP-8: generate association rules
// Now, use (K=List<String>, V=Iterable<Tuple2<List<String>,Integer>>)
// to generate association rules
// JavaRDD<R> map(Function<T,R> f)
// Return a new RDD by applying a function to all elements of this RDD.
JavaRDD<List<Tuple3<List<String>,List<String>,Double>>> assocRules =

rules.map(new Function<

189

1

2

3

4

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

Tuple2<List<String>,Iterable<Tuple2<List<String>,Integer>>>, // T: input
List<Tuple3<List<String>,List<String>,Double>>
// T: input
// R: ( ac => b, 1/3): T3(List(a,c), List(b),
( ad => c, 1/3): T3(List(a,d), List(c),
//
>() {

0.33)
0.33)

// R: output

public List<Tuple3<List<String>,List<String>,Double>>

call(Tuple2<List<String>,Iterable<Tuple2<List<String>,Integer>>> in) {

List<Tuple3<List<String>,List<String>,Double>> result =

new ArrayList<Tuple3<List<String>,List<String>,Double>>();

List<String> fromList = in._1;
Iterable<Tuple2<List<String>,Integer>> to = in._2;
List<Tuple2<List<String>,Integer>> toList =

new ArrayList<Tuple2<List<String>,Integer>>();

Tuple2<List<String>,Integer> fromCount = null;
for (Tuple2<List<String>,Integer> t2 : to) {

// find the "count" object
if (t2._1 == null) {
fromCount = t2;

}
else {

toList.add(t2);

}

}

// Now, we have the required objects for generating association rules:
//
if (toList.isEmpty()) {

"fromList", "fromCount", and "toList"

// no output generated, but since Spark does not
// like null objects, we will fake a null object
return result; // an empty list

}

// now using 3 objects: "from", "fromCount", and "toList",
// create association rules:
for (Tuple2<List<String>,Integer> t2 : toList) {

double confidence = (double) t2._2 / (double) fromCount._2;
List<String> t2List = new ArrayList<String>(t2._1);
t2List.removeAll(fromList);
result.add(new Tuple3(fromList, t2List, confidence));

}

return result;

}
});
assocRules.saveAsTextFile("/rules/output/6");

Here is the output of STEP-8 (ﬁnal output): each output entry depicts
list of Tuple3(X, Y, confidence) where X → Y and ”conﬁdence” (as a
double value).

# hadoop fs -cat /rules/output/6/part*
[([a, b],[d],0.5), ([a, b],[c],0.5)]
[]

190

[([c],[b],1.0), ([c],[a],0.3333333333333333)]
[([b, d],[a],1.0)]
[([d],[b],1.0), ([d],[a],1.0)]
[([a],[b],1.0), ([a],[c],0.5), ([a],[d],0.5)]
[([b, c],[a],0.3333333333333333)]
[]
[([a, c],[b],1.0)]
[([a, d],[b],1.0)]
[([b],[a],0.5), ([b],[d],0.25), ([b],[c],0.75)]

7.6.3.13 YARN Script for Spark

Listing 7.20: High Level Steps

1 # cat run_assoc_rules.sh
2 #!/bin/bash
3 export JAVA_HOME=/usr/java/jdk7
4 export HADOOP_HOME=/usr/local/hadoop2.4.0
5 export SPARK_HOME=/usr/local/spark-1.0.0
6 export CLASSPATH=$CLASSPATH:$HADOOP_HOME/etc/hadoop
7 export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop
8 export YARN_CONF_DIR=$HADOOP_HOME/etc/hadoop
9 export MP=/mp/spark_mahmoud_examples
10 export MY_JAR=$MP/mp.jar
11 export SPARK_JAR=$SPARK_HOME/assembly/target/scala-2.10/spark-assembly-1.0.0-hadoop2.4.0.jar
12 INPUT=/data/data_mining_transactions.txt
13 prog=FindAssociationRules
14 $SPARK_HOME/bin/spark-submit --class $prog \
15

--master yarn-cluster \
--num-executors 12 \
--driver-memory 3g \
--executor-memory 7g \
--executor-cores 12 \
$MY_JAR $INPUT

16

17

18

19

20

7.6.4 Creating Item Sets From Transactions

Given a transaction T = {I1, I2, ..., In}, to create item sets for a given
transaction T (comprised of a set of items), we have a simple POJO class
(Combination) to generate all combinations of sorted item sets. The Combination
class is deﬁnd below.

191

Listing 7.21: Combination Class

1 import java.util.List;
2 import java.util.ArrayList;
3 import java.util.Arrays;
4 import java.util.Collection;
5 import java.util.Collections;
6
7 public class Combination {
8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

public static <T extends Comparable<? super T>> List<List<T>>

findSortedCombinations(Collection<T> elements) {...}

public static <T extends Comparable<? super T>> List<List<T>>

findSortedCombinations(Collection<T> elements, int n) {...}

public static void main(String[] args) throws Exception {

test();

}

public static void test() throws Exception {

List<String> list = Arrays.asList("a", "b", "c", "d");
System.out.println("list="+list);
List<List<String>> comb = findSortedCombinations(list);
System.out.println(comb.size());
System.out.println(comb);

}

25
26 }

Method deﬁnitions are listed below.

Listing 7.22: Combination Class: ﬁndSortedCombinations(List)

/**
* Will return combinations of all sizes...
* If elements = { a, b, c }, then findCollections(elements) will return:
* { [], [a], [b], [c], [a, b], [a, c], [b, c], [a, b, c] }
*
*/
public static <T extends Comparable<? super T>> List<List<T>>

findSortedCombinations(Collection<T> elements) {

List<List<T>> result = new ArrayList<List<T>>();
for (int i = 0; i <= elements.size(); i++) {

result.addAll(findSortedCombinations(elements, i));

}
return result;

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Listing 7.23: Combination Class: ﬁndSortedCombinations(List, n)

192

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

/**
* If elements = { a, b, c }, then findCollections(elements, 2) will return:
* { [a, b], [a, c], [b, c] }
*
*/
public static <T extends Comparable<? super T>> List<List<T>>

findSortedCombinations(Collection<T> elements, int n) {
List<List<T>> result = new ArrayList<List<T>>();
if (n == 0) {

result.add(new ArrayList<T>());
return result;

}

List<List<T>> combinations = findSortedCombinations(elements, n - 1);
for (List<T> combination: combinations) {

for (T element: elements) {

if (combination.contains(element)) {

continue;

}

List<T> list = new ArrayList<T>();
list.addAll(combination);

if (list.contains(element)) {

continue;

}

list.add(element);
// sort items not to duplicate the items, for example: (a, b, c) and
// (a, c, b) might become different items to be counted if not sorted
Collections.sort(list);
if (result.contains(list)) {

continue;

}
result.add(list);

}

}
return result;

}

193

Chapter 8

Common Friends

8.1

Introduction

Given a social network will tens of millions of users, the purpose of this
chapter is to implement a MapReduce program to identify ”common friends”
among all pairs of users. Let U be a set of all users: {U1, U2, ..., Un}. Then
the goal is to ﬁnd common friends for every pair of (Ui, Uj) where i (cid:54)= j.

For ﬁnding common friends, we provide three solutions:

• Classic MapReduce/Hadoop using Primitive data types

• Classic MapReduce/Hadoop using Custom data types

• Spark/Hadoop using RDDs

These days most social network sites (such as Facebook, hi5, LinkedIn)
oﬀer services to help you share messages, pictures, and videos among friends.
Some sites even oﬀer video chat services to help you connect with friends.
By deﬁnition, friend is a person whom one knows, likes, and trusts. For
example, Facebook has a list of friends, and friends are a bi-directional thing
on Facebook. If I’m your friend, you’re mine too. Typically social networks
(such as Facebook) pre-compute calculations when they can to reduce the
processing time of requests. One common processing request is the ”You and
Mary (as your friend) have 185 friends in common” feature. When you visit
someone’s proﬁle, you see a list of friends that you have in common. This

194

list doesn’t change frequently so it had to be wasteful to recalculate it every
time you visited the proﬁle. There are many way to ﬁnd out the common
friends between users of a social network. There are at least two possible
solutions:

1. use a caching strategy and save the common friends in cache (such as

Redis or Memcache)

2. use MapReduce to calculate everyone’s common friends once a day and

store those results

We will focus on a MapReduce solution for ﬁnding common friends.

8.2 Input

We prepare input as a set of records, where each record has the following
format:

< person ><, >< f riend1 >< f riend2 > ... < f riendN >

(8.1)

where < f riend1 >< f riend2 > ... < f riendN > are friends of the <
person >. Note that in real projects/applications, each person/friend will be
identiﬁed as a unique user-id. A very simple and complete example of input
will be as follows.

100, 200 300 400 500 600
200, 100 300 400
300, 100 200 400 500
400, 100 200 300
500, 100 300
600, 100

In this example, user 500 has two friends identiﬁed by user-ids 100 and 300
and user identiﬁed by 600 has only one friend: user 100.

195

8.3 Common Friends Algorithm

Let {A1, A2, ..., Am} be a set of friends for User1 and {B1, B2, ..., Bn} be
a set of friends for User2, then common friends of User1 and User2 can be
deﬁned as the intersection (common elements) of these two sets. The POJO
solution is given below:

Listing 8.1: Common Friends Algorithm

1 import java.util.Set;
2 import java.util.TreeSet;
3
4 public class CommonFriends {
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

// user1friends = {A1, A2, ..., Am}
// user2friends = {B1, B2, ..., Bn}
public static Set<Integer> intersection(Set<Integer> user1friends,

if ((user1friends == null) || (user1friends.isEmpty())) {

Set<Integer> user2friends) {

return null;

}

if ((user2friends == null) || (user2friends.isEmpty())) {

return null;

}

// both sets are non-null
if (user1friends.size() < user2friends.size()) {
return intersect(user1friends, user2friends);

}
else {

return intersect(user2friends, user1friends);

}

}

private static Set<Integer> intersect(Set<Integer> smallSet,

Set<Integer> largeSet) {

Set<Integer> result = new TreeSet<Integer>();
// iterate on small set to improve performance
for (Integer x : smallSet) {

if (largeSet.contains(x)) {

result.add(x);

}

}
return result;

}

37
38 }

196

8.4 MapReduce Algorithm

Our MapReduce solution to ﬁnd ”common friends” has a map() and reduce()
functions. The mapper accepts a (key1, value1) pair, where key1 is a person
and value1 is a list of associated friends of this person. The mapper emits a
set of new (key2, value2) pairs where key2 is a Tuple2(key1, friendi) where
friendi ∈ value1 and value2 is the same as value1 (list of all friends for key1).
The reducer’s key is a pair of two users (Userj, Userk) and value is a list of
sets of friends. The reduce() function will intersect all sets of friends to ﬁnd
common and mutual friends for (Userj, Userk) pair.
Here are the map() and reduce() functions:

Listing 8.2: Finding Common Friends map() Function

1 // key is the person
2 // value is a list of friends for this key=person
3 // value = (<friend_1> <friend_2> ... <friend_N>)
4 map(key, value) {
5

reducerValue = (<friend_1> <friend_2> ... <friend_N>);
foreach friend in (<friend_1> <friend_2> ... <friend_N>)

{

reducerKey = buildSortedKey(person, friend);
emit(reducerKey, reducerValue);

6

7

8

}

9
10 }

Mapper’s output keys are sorted and this property will prevent duplicate
keys. Note that we assume that friendship is a bi-directional thing: if Alex
is a friend of Bob, then Bob is a friend of Alex.
Mappers output sorted keys are generated as:

Listing 8.3: Finding Common Friends buildSortedKey() Function

1 Tuple2 buildSortedKey(person1, person2) {
2

if (person1 < person2) {

3

4

5

6

return Tuple2(person1, person2)

}
else {

return Tuple2(person2, person1)

}

7
8 }

The reduce() function ﬁnds the common friends for every pair of users by

intersecting all associated friends in between.

197

Listing 8.4: Finding Common Friends reduce() Function

1 // key = Tuple2(person1, person2)
2 // value = List {List_1, List_2, ..., List_M}
3 //
4 reduce(key, value) {
5

where each List_i = { set of unique user id’s }

outputKey = key;
outputValue = intersection (List_1, List_2, ..., List_M);
emit (outputKey, outputValue);

6

7
8 }

8.4.1 MapReduce Algorithm in Action

To understand our MapReduce algorithm, I will show all (key, value) pairs
generated by mappers and reducers. Lets apply map() to our sample input:

map(100, (200 300 400 500 600)) will generate:

([100, 200], [200 300 400 500 600])
([100, 300], [200 300 400 500 600])
([100, 400], [200 300 400 500 600])
([100, 500], [200 300 400 500 600])
([100, 600], [200 300 400 500 600])

map(200, (100 300 400)) will generate:

([100, 200], [100 300 400])
([200, 300], [100 300 400])
([200, 400], [100 300 400])

map(300, (100 200 400 500)) will generate:

([100, 300], [100 200 400 500])
([200, 300], [100 200 400 500])
([300, 400], [100 200 400 500])
([300, 500], [100 200 400 500])

map(400, (100 200 300)) will generate:

198

([100, 400], [100 200 300])
([200, 400], [100 200 300])
([300, 400], [100 200 300])

map(500, (100 300)) will generate:

([100, 500], [100 300])
([300, 500], [100 300])

map(600, (100)) will generate:

([100, 600], [100])

So the mappers generate the following (key, value) pairs:

([100, 200], [200 300 400 500 600])
([100, 300], [200 300 400 500 600])
([100, 400], [200 300 400 500 600])
([100, 500], [200 300 400 500 600])
([100, 600], [200 300 400 500 600])
([100, 200], [100 300 400])
([200, 300], [100 300 400])
([200, 400], [100 300 400])
([100, 300], [100 200 400 500])
([200, 300], [100 200 400 500])
([300, 400], [100 200 400 500])
([300, 500], [100 200 400 500])
([100, 400], [100 200 300])
([200, 400], [100 200 300])
([300, 400], [100 200 300])
([100, 500], [100 300])
([300, 500], [100 300])
([100, 600], [100])

Before these key-value pairs are sent to the reducers, they are grouped

by keys:

199

([100, 200], [200 300 400 500 600])
([100, 200], [100 300 400])
=> ([100, 200], ([200 300 400 500 600], [100 300 400]))

([100, 300], [200 300 400 500 600])
([100, 300], [100 200 400 500])
=> ([100, 300], ([200 300 400 500 600],[100 200 400 500]))

([100, 400], [200 300 400 500 600])
([100, 400], [100 200 300])
=> ([100, 400], ([200 300 400 500 600], [100 200 300]))

([100, 500], [200 300 400 500 600])
([100, 500], [100 300])
=> ([100, 500], ([200 300 400 500 600], [100 300]))

([200, 300], [100 300 400])
([200, 300], [100 200 400 500])
=> ([200, 300], ([100 300 400],[100 200 400 500]))

([200, 400], [100 300 400])
([200, 400], [100 200 300])
=> ([200, 400], ([100 300 400],[100 200 300]))

([300, 400], [100 200 400 500])
([300, 400], [100 200 300])
=> ([300, 400], ([100 200 400 500][100 200 300]))

([300, 500], [100 200 400 500])
([300, 500], [100 300])
=> ([300, 500], ([100 200 400 500],[100 300]))

([100, 600], [200 300 400 500 600])
([100, 600], [100])
=> ([100, 600], ([200 300 400 500 600]), [100])

So, reducers will receive the following set of (key, value) pairs:

200

([100, 200], ([200 300 400 500 600], [100 300 400]))
([100, 300], ([200 300 400 500 600],[100 200 400 500]))
([100, 400], ([200 300 400 500 600], [100 200 300]))
([100, 500], ([200 300 400 500 600], [100 300]))
([200, 300], ([100 300 400],[100 200 400 500]))
([200, 400], ([100 300 400],[100 200 300]))
([300, 400], ([100 200 400 500][100 200 300]))
([300, 500], ([100 200 400 500],[100 300]))
([100, 600], ([200 300 400 500 600], [100])

Finally, reducer(s) will generate:

([100, 200], [300, 400])
([100, 300], [200, 400, 500])
([100, 400], [200, 300])
([100, 500], [300])
([200, 300], [100, 400])
([200, 400], [100, 300])
([300, 400], [100, 200])
([300, 500], [100])
([100, 600], [])

Following the generated output, we observe that users 100 and 600 have
no common friends. The business case is now that when user-100 visits user-
200’s proﬁle, we can quickly look up [100, 200] key and see that they have
two friends in common, [300, 400]. Meanwhile, the users identiﬁed by 100
and 500 have one friend (identiﬁed by user-id 300) in common.

8.5 Solution 1: Hadoop Implementation us-

ing Text

Assuming that each user id is a long data type, in this implementation, we
represent ”list of friends” as a ”string” object. For example, a list of three
user ids: 100, 200, 300 can be represented as a string object: ”100,200,300.”
To traverse this kind of list, we do need to tokenize the string object and
then retrieve items from it.

201

Class name
CommonFriendsDriver.java
CommonFriendsMapper.java
CommonFriendsReducer.java Deﬁnes reduce()
HadoopUtil.java

Description
A driver program to submit Hadoop jobs
Deﬁnes map()

Utility methods for Hadoop

8.5.1 Sample Run for Solution 1

$ cat run.sh
#/bin/bash

export HADOOP_HOME=/Users/mahmoud/zmp/zs/hadoop
export HADOOP_HOME_WARN_SUPPRESS=true

export JAVA_HOME=‘/usr/libexec/java_home‘
echo "JAVA_HOME=$JAVA_HOME"

PATH=.:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
export PATH=$PATH:$HADOOP_HOME/bin:$JAVA_HOME/bin

CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-ant-1.2.1.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-core-1.2.1.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-examples-1.2.1.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-test-1.2.1.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-tools-1.2.1.jar

LIB_DIR=/Users/mahmoud/zmp/map_reduce_book/hadooptests/lib
JAR_FILES=‘find $LIB_DIR -name ’*.jar’‘
for jarfile in $JAR_FILES ; do
CLASSPATH=$CLASSPATH:$jarfile
done

echo "CLASSPATH=$CLASSPATH"

export JAR=/Users/mahmoud/zmp/map_reduce_book/hadooptests/common_friends/common_friends.jar
export CLASSPATH=$CLASSPATH:$JAR

202

export HADOOP_CLASSPATH=$CLASSPATH

javac *.java
jar cvf $JAR *.class

$HADOOP_HOME/bin/hadoop fs -rmr /common_friends/output
$HADOOP_HOME/bin/hadoop jar $JAR CommonFriendsDriver /common_friends/input /common_friends/output

$ hadoop fs -mkdir /common_friends
$ hadoop fs -mkdir /common_friends/input
$ hadoop fs -mkdir /common_friends/output

$ cat input/file1.txt
100 200 300 400 500
200 100 300 400
300 100 200 400 500
400 100 200 300

$ cat input/file2.txt
500 100 300
600 100

$ hadoop fs -copyFromLocal input/file1.txt /common_friends/input/
$ hadoop fs -copyFromLocal input/file2.txt /common_friends/input/
$ hadoop fs -ls /common_friends/input/
Found 2 items
-rw-r--r--
-rw-r--r--

1 mahmoud staff
1 mahmoud staff

74 2013-09-21 17:07 /common_friends/input/file1.txt
20 2013-09-21 17:07 /common_friends/input/file2.txt

$ ./run.sh
JAVA_HOME=/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
...
adding: CommonFriendsDriver.class(in = 2844) (out= 1369)(deflated 51%)
adding: CommonFriendsMapper.class(in = 2485) (out= 1084)(deflated 56%)
adding: CommonFriendsReducer.class(in = 2197) (out= 952)(deflated 56%)
adding: HadoopUtil.class(in = 1797) (out= 839)(deflated 53%)
Deleted hdfs://localhost:9000/lib/common_friends.jar
Deleted hdfs://localhost:9000/common_friends/output

203

13/09/21 17:17:25 INFO CommonFriendsDriver: inputDir=/common_friends/input
13/09/21 17:17:25 INFO CommonFriendsDriver: outputDir=/common_friends/output
...
13/09/21 17:17:26 INFO mapred.JobClient: Running job: job_201309211704_0003
13/09/21 17:17:27 INFO mapred.JobClient: map 0% reduce 0%
13/09/21 17:17:34 INFO mapred.JobClient: map 50% reduce 0%
...
13/09/21 17:18:19 INFO mapred.JobClient: map 100% reduce 83%
13/09/21 17:18:20 INFO mapred.JobClient: map 100% reduce 100%
13/09/21 17:18:21 INFO mapred.JobClient: Job complete: job_201309211704_0003
13/09/21 17:18:21 INFO mapred.JobClient: Counters: 26
13/09/21 17:18:21 INFO mapred.JobClient:
...
13/09/21 17:18:21 INFO mapred.JobClient:
13/09/21 17:18:21 INFO mapred.JobClient:
13/09/21 17:18:21 INFO mapred.JobClient:
13/09/21 17:18:21 INFO mapred.JobClient:
13/09/21 17:18:21 INFO mapred.JobClient:
...
13/09/21 17:18:21 INFO mapred.JobClient:
13/09/21 17:18:21 INFO CommonFriendsDriver: run(): status=true
13/09/21 17:18:21 INFO CommonFriendsDriver: jobStatus=0

Map output materialized bytes=510
Map input records=6
Reduce shuffle bytes=510
Spilled Records=34

Map output records=17

Map-Reduce Framework

Job Counters

$ hadoop fs -cat /common_friends/output/part*
100,200 [300, 400]
100,300 [200, 400, 500]
100,400 [300, 200]
100,500 [300]
100,600 []
200,300 [400, 100]
200,400 [300, 100]
300,400 [200, 100]
300,500 [100]

204

8.6 Solution 2: Hadoop Implementation us-

ing ArrayListOfLongsWritable

This implementation represents a ”list of longs” as an ArrayListOfLongsWritable1
class (a customized class), which extends ArrayListOfLongs and imple-
ments WritableComparable<ArrayListOfLongsWritable> object. As long
as your object (ArrayListOfLongsWritable) implemets the Writable2 iter-
face, then you can use it as key or value by mappers and reducers. The rule
of thumb is that, in Hadoop, you can have a customized objects as key or
value as long as it implements the Writable interface. This is how hadoop
persists objects on Hadoop Distributed File System.

Class name
CommonFriendsDriverUsingList.java
CommonFriendsMapperUsingList.java
CommonFriendsReducerUsingList.java Deﬁnes reduce()
HadoopUtil.java

Description
A driver program to submit Hadoop jobs
Deﬁnes map()

Utility methods for Hadoop

8.6.1 Sample Run for Solution 2

$ cat run.sh
#/bin/bash

export HADOOP_HOME=/Users/mahmoud/zmp/zs/hadoop
export HADOOP_HOME_WARN_SUPPRESS=true

export JAVA_HOME=‘/usr/libexec/java_home‘
echo "JAVA_HOME=$JAVA_HOME"

PATH=.:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
PATH=$PATH:$HADOOP_HOME/bin
PATH=$PATH:$JAVA_HOME/bin

1 edu.umd.cloud9.io.array.ArrayListOfLongsWritable
2org.apache.hadoop.io.Writable (a serializable object which implements a simple,
eﬃcient, serialization protocol, based on DataInput and DataOutput). Note that any key
or value type in the Hadoop MapReduce framework implements this interface.

205

export PATH

CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-ant-1.2.1.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-core-1.2.1.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-examples-1.2.1.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-test-1.2.1.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-tools-1.2.1.jar

LIB_DIR=/Users/mahmoud/zmp/map_reduce_book/hadooptests/lib
JAR_FILES=‘find $LIB_DIR -name ’*.jar’‘
for jarfile in $JAR_FILES ; do
CLASSPATH=$CLASSPATH:$jarfile
done

echo "CLASSPATH=$CLASSPATH"

export JAR=/Users/mahmoud/zmp/map_reduce_book/hadooptests/common_friends_using_lists/common_friends_using_lists.jar
export CLASSPATH=$CLASSPATH:$JAR
export HADOOP_CLASSPATH=$CLASSPATH

javac *.java
jar cvf $JAR *.class
$HADOOP_HOME/bin/hadoop fs -rm /lib/common_friends_using_lists.jar
$HADOOP_HOME/bin/hadoop fs -put $JAR /lib/
#
input=/common_friends_using_lists/input
output=/common_friends_using_lists/output
$HADOOP_HOME/bin/hadoop fs -rmr /common_friends_using_lists/output
$HADOOP_HOME/bin/hadoop jar $JAR CommonFriendsDriverUsingList $input $output

$ ./run.sh
JAVA_HOME=/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
...
adding: CommonFriendsDriverUsingList.class(in = 2934) (out= 1413)(deflated 51%)
adding: CommonFriendsMapperUsingList.class(in = 2645) (out= 1127)(deflated 57%)
adding: CommonFriendsReducerUsingList.class(in = 2915) (out= 1286)(deflated 55%)
adding: HadoopUtil.class(in = 1797) (out= 840)(deflated 53%)

206

Deleted hdfs://localhost:9000/lib/common_friends_using_lists.jar
Deleted hdfs://localhost:9000/common_friends_using_lists/output
13/09/23 15:13:33 INFO CommonFriendsDriverUsingList: inputDir=/common_friends_using_lists/input
13/09/23 15:13:33 INFO CommonFriendsDriverUsingList: outputDir=/common_friends_using_lists/output
...
13/09/23 15:13:33 INFO mapred.JobClient: Running job: job_201309231108_0007
13/09/23 15:13:34 INFO mapred.JobClient: map 0% reduce 0%
13/09/23 15:13:39 INFO mapred.JobClient: map 100% reduce 0%
...
13/09/23 15:14:23 INFO mapred.JobClient: map 100% reduce 83%
13/09/23 15:14:24 INFO mapred.JobClient: map 100% reduce 100%
13/09/23 15:14:25 INFO mapred.JobClient: Job complete: job_201309231108_0007
13/09/23 15:14:25 INFO mapred.JobClient: Counters: 26
...
13/09/23 15:14:25 INFO mapred.JobClient:
...
13/09/23 15:14:25 INFO mapred.JobClient:
13/09/23 15:14:25 INFO mapred.JobClient:
13/09/23 15:14:25 INFO CommonFriendsDriverUsingList: run(): status=true
13/09/23 15:14:25 INFO CommonFriendsDriverUsingList: jobStatus=0

Reduce output records=9
Map output records=17

Map output bytes=636

$ hadoop fs -cat /common_friends_using_lists/output/part*
100,200 [400, 300]
100,300 [200, 500, 400]
100,400 [200, 300]
100,500 [300]
100,600 []
200,300 [100, 400]
200,400 [100, 300]
300,400 [100, 200]
300,500 [100]

8.7 Spark Solution

We present a Spark solution by writing a map() and reduce() functions using
Spark’s RDDs. Our users data is represented as HDFS text ﬁles and each
record line has the following format (P is the person and {F1, F2, ..., Fn} are

207

direct friends of P ):

P, F1, F2, ..., Fn

Our Spark solution will be based on the following map() and reduce() func-
tions. The mapper function is listed below:

map(P, {F_1, F_2, ..., F_n}) {

friends = {F_1, F_2, ..., F_n};
for (f : friends) {

key = buildSortedTuple(P, f);
emit(key, friends);

}

}

The reducer function is listed below:

// key = Tuple2<user1,user2>
// values = List<List<user>>
reduce(key, values) {

commonFriends = intersection(values);
emit(key, friends);

}

Since Spark provides a much higher level API than classic MapReduce/Hadoop,

the entire solution is presented in a single Java driver class. First, we present
all steps, and then we will go details on the steps. The high-level solution is
given as:

Listing 8.5: High Level Steps

208

1 // STEP-0: Import required classes and interfaces
2 public class FindCommonFriends {
3

public static void main(String[] args) throws Exception {

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19
20 }

// STEP-1: Check input parameters
// STEP-2: Create a JavaSparkContext object
// STEP-3: Read input text file from HDFS and create
//
the first JavaRDD to represent input file
// STEP-4: map JavaRDD<String> into (key, value) pairs,
//
// STEP-5: reduce (key=Tuple2<u1,u2>, value=List<friends>) pairs
//
// StEP-6: Find common friends by intersection of all List<List<Long>>

into (key=Tuple2<u1,u2>, value=List<List<friends>>)

where key=Tuple<user1,user2>, value=List of friends

System.exit(0);

}

// build a sorted Tuple to avoid duplicates
static Tuple2<Long,Long> buildSortedTuple(long a, long b) {...}

Next, we present details of each steps.

8.7.1 STEP-0: Import Required Classes

Spark’s main Java classes and interfaces are deﬁned in the org.apache.spark.api.java
package.

Listing 8.6: STEP-0: Import required classes and interfaces

1 // STEP-0: Import required classes and interfaces
2 import scala.Tuple2;
3 import org.apache.spark.api.java.JavaRDD;
4 import org.apache.spark.api.java.JavaPairRDD;
5 import org.apache.spark.api.java.JavaSparkContext;
6 import org.apache.spark.api.java.function.PairFlatMapFunction;
7 import org.apache.spark.api.java.function.FlatMapFunction;
8 import org.apache.spark.api.java.function.Function;
9
10 import java.util.Arrays;
11 import java.util.List;
12 import java.util.ArrayList;
13 import java.util.Map;
14 import java.util.HashMap;

209

8.7.2 STEP-1: Check Input Parameters

For our program, we need two input parameters: ”Spark’s master URL” (as
args[0]) and ”input text ﬁle stored in HDFS” (as args[1]).

Listing 8.7: STEP-1: Check input parameters

// STEP-1: Check input parameters
if (args.length < 2) {

System.err.println("Usage: FindCommonFriends <master> <file>");
System.exit(1);

}
System.out.println("spark master URL="+args[0]);
System.out.println("HDFS input file ="+args[1]);

8.7.3 STEP-2: Create a JavaSparkContext Object

A JavaSparkContext object is created from a ”spark master URL”. This a
factory object to create new RDDs.

Listing 8.8: STEP-2: Create a JavaSparkContext object

// STEP-2: Create a JavaSparkContext object
JavaSparkContext ctx = new JavaSparkContext(

args[0], // spark master URL
"FindCommonFriends",
System.getenv("SPARK_HOME"),
System.getenv("SPARK_EXAMPLES_JAR"));

8.7.4 STEP-3: Read Input

We create the ﬁrst RDD from an input ﬁle by using a context object (JavaSparkContext)
created in STEP-2. The new RDD (JavaRDD<String>) represent all records
of the input ﬁle. Each input record is represented as a Java String object.

Listing 8.9: STEP-3: Read Input and Create RDD

// STEP-3: Read input text file from HDFS and create
//
the first JavaRDD to represent input file
JavaRDD<String> records = ctx.textFile(args[1], 1);

// debug0
List<String> debug0 = records.collect();
for (String t : debug0) {

210

1

2

3

4

5

6

7

1

2

3

4

5

6

1

2

3

4

5

6

7

8

9

}

System.out.println("debug0 record="+t);

8.7.5 STEP-4: Apply a Mapper

This step maps every record of [P, F1, F2, ..., Fn] into set of (key, value) pairs
where key=Tuple2(P, Fi) and value is a list [F1, F2, ..., Fn]. If size of friends
list is one, then no friends list will be created (in this case, there cannot be any
friends in common). To implement mapper, we use JavaRDD.flatMapToPair()
function. This is accomplished by using PairFlatMapFunction as (T is input
and (K,V) is generated as an output):

PairFlatMapFunction<T, K, V>
T => Iterable<Tuple2<K, V>>

Here is the complete implmentation of STEP-4:

Listing 8.10: STEP-4: Apply a Mapper

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

where key=Tuple<user1,user2>, value=List of friends

// STEP-4: map JavaRDD<String> into (key, value) pairs,
//
//
// PairFlatMapFunction<T, K, V>
// T => Iterable<Tuple2<K, V>>
JavaPairRDD<Tuple2<Long,Long>,Iterable<Long>> pairs =
T
//
records.flatMapToPair(new PairFlatMapFunction<String, Tuple2<Long,Long>, Iterable<Long>>() {

V

K

public Iterable<Tuple2<Tuple2<Long,Long>,Iterable<Long>>> call(String s) {

String[] tokens = s.split(",");
long person = Long.parseLong(tokens[0]);
String friendsAsString = tokens[1];
String[] friendsTokenized = friendsAsString.split(" ");
if (friendsTokenized.length == 1) {

Tuple2<Long,Long> key = buildSortedTuple(person, Long.parseLong(friendsTokenized[0]));
return Arrays.asList(new Tuple2<Tuple2<Long,Long>,Iterable<Long>>(key, new ArrayList<Long>()));

}
List<Long> friends = new ArrayList<Long>();
for (String f : friendsTokenized) {

friends.add(Long.parseLong(f));

}

List<Tuple2<Tuple2<Long, Long> ,Iterable<Long>>> result =

new ArrayList<Tuple2<Tuple2<Long, Long> ,Iterable<Long>>>();

for (Long f : friends) {

Tuple2<Long,Long> key = buildSortedTuple(person, f);

211

result.add(new Tuple2<Tuple2<Long,Long>, Iterable<Long>>(key, friends));

}
return result;

27

28

29

30

31

}
});

To debug STEP-4, we use the JavaRDD.collect() function.

// debug1
List<Tuple2<Tuple2<Long, Long> ,Iterable<Long>>> debug1 = pairs.collect();
for (Tuple2<Tuple2<Long,Long>,Iterable<Long>> t2 : debug1) {

System.out.println("debug1 key="+t2._1+"\t value="+t2._2);

}

8.7.6 STEP-5: Apply a Reducer

The reducer is applied by calling JavaPairRDD.groupByKey() method.

Listing 8.11: STEP-5: Apply a Reducer

1

2

3

4

5

6

7

8

9

// STEP-5: reduce (key=Tuple2<u1,u2>, value=Iterable<friends>) pairs
//
JavaPairRDD<Tuple2<Long, Long>, Iterable<Iterable<Long>>> grouped = pairs.groupByKey();

into (key=Tuple2<u1,u2>, value=Iterable<Iterable<friends>>)

// debug2
List<Tuple2<Tuple2<Long, Long> ,Iterable<Iterable<Long>>>> debug2 = grouped.collect();
for (Tuple2<Tuple2<Long,Long>, Iterable<Iterable<Long>>> t2 : debug2) {

System.out.println("debug2 key="+t2._1+"\t value="+t2._2);

}

8.7.7 STEP-6: Find Common Friends

To ﬁnd common friends, we intersect all friends for two users by just alter-
ing the values. This is accomplished by JavaPairRDD.mapValues() method
without changing the keys.

Listing 8.12: STEP-6: Find intersection of all

212

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

// STEP-6: Find intersection of all List<List<Long>>
// mapValues[U](f: (V) => U): JavaPairRDD[K, U]
// Pass each value in the key-value pair RDD through a map
// function without changing the keys;
// this also retains the original RDD’s partitioning.
// Find intersection of all List<List<Long>>
JavaPairRDD<Tuple2<Long, Long>, Iterable<Long>> commonFriends =

grouped.mapValues(new Function< Iterable<Iterable<Long>>, // input

Iterable<Long>

// output

>() {

public Iterable<Long> call(Iterable<Iterable<Long>> s) {

Map<Long, Integer> countCommon = new HashMap<Long, Integer>();
int size = 0;
for (Iterable<Long> iter : s) {

size++;
List<Long> list = iterableToList(iter);
if ((list == null) || (list.isEmpty())) {

continue;

}
for (Long f : list) {

Integer count = countCommon.get(f);
if (count == null) {

countCommon.put(f, 1);

}
else {

countCommon.put(f, ++count);

}

}

}

// if countCommon.Entry<f, count> ==
// then that is a common friend
List<Long> finalCommonFriends = new ArrayList<Long>();
for (Map.Entry<Long, Integer> entry : countCommon.entrySet()){

countCommon.Entry<f, s.size()>

if (entry.getValue() == size) {

finalCommonFriends.add(entry.getKey());

}

}
return finalCommonFriends;

}
});

To debug STEP-6, we used the following code:

// debug3
List<Tuple2<Tuple2<Long, Long>, Iterable<Long>>> debug3 = commonFriends.collect();
for (Tuple2<Tuple2<Long, Long>, Iterable<Long>> t2 : debug3) {
System.out.println("debug3 key="+t2._1+ "\t value="+t2._2);

}

213

Finally the following function is used to make sure that we will not have
duplicate Tuple2<user1,user2> objects.

static Tuple2<Long,Long> buildSortedTuple(long a, long b) {

if (a < b) {

return new Tuple2<Long, Long>(a,b);

}
else {

return new Tuple2<Long, Long>(b,a);

}

}

8.8 Sample Run of a Spark Program

8.8.1 HDFS Input

# hadoop fs -cat /data/users_and_friends.txt
100,200 300 400 500
200,100 300 400
300,100 200 400 500
400,100 200 300
500,100 300
600,100

8.8.2 Script to Run Spark Program

# cat run_find_common_friends.sh
source /home/hadoop/conf/env_2.3.0.sh
export SPARK_HOME=/home/hadoop/spark-1.0.0
source /home/hadoop/spark_mahmoud_examples/spark_env_yarn.sh
source $SPARK_HOME/conf/spark-env.sh

# system jars:

214

CLASSPATH=$CLASSPATH:$HADOOP_HOME/etc/hadoop

jars=‘find $SPARK_HOME -name ’*.jar’‘
for j in $jars ; do

CLASSPATH=$CLASSPATH:$j

done

# app jar:
export CLASSPATH=/home/hadoop/spark_mahmoud_examples/mp.jar:$CLASSPATH
export SPARK_CLASSPATH=$CLASSPATH
export SPARK_MASTER=spark://hnode01319.nextbiosystem.net:7077
#-Dsun.lang.ClassLoader.allowArraySyntax=true
USERS=/data/users_and_friends.txt
OPTIONS="-Dsun.lang.ClassLoader.allowArraySyntax=true -Dspark.master=$SPARK_MASTER"
$JAVA_HOME/bin/java -cp $CLASSPATH $OPTIONS FindCommonFriends $SPARK_MASTER $USERS

8.8.3 Log of Sample Run

We ran this program in a cluster environment by using 3 servers identiﬁed
by myserver100 (as a Spark master), myserver200, and myserver300. The
actual log is trimmed to ﬁt the page.

hadoop@hnode01319:~/spark_mahmoud_examples# ./run_find_common_friends.sh
spark master URL=spark://myserver100
:7077
HDFS input file =/data/users_and_friends.txt
...
14/05/31 21:33:40 INFO Remoting: Starting remoting
14/05/31 21:33:40 INFO Remoting: Remoting started; listening on addresses :
:33722]

[akka.tcp://spark@myserver100

14/05/31 21:33:40 INFO Remoting: Remoting now listens on addresses:

[akka.tcp://spark@myserver100

:33722]

...
14/05/31 21:33:46 INFO scheduler.TaskSchedulerImpl: Removed TaskSet 0.0,

whose tasks have all completed, from pool

14/05/31 21:33:46 INFO spark.SparkContext: Job finished: collect at

FindCommonFriends.java:33, took 3.76636011 s

215

debug0 record=100,200 300 400 500
debug0 record=200,100 300 400
debug0 record=300,100 200 400 500
debug0 record=400,100 200 300
debug0 record=500,100 300
debug0 record=600,100
14/05/31 21:33:46 INFO spark.SparkContext: Starting job: collect at

FindCommonFriends.java:69

14/05/31 21:33:46 INFO scheduler.DAGScheduler: Got job 1 (collect at

FindCommonFriends.java:69) with 1 output partitions (allowLocal=false)

...
14/05/31 21:33:46 INFO scheduler.DAGScheduler: Stage 1 (collect at

FindCommonFriends.java:69) finished in 0.043 s

14/05/31 21:33:46 INFO spark.SparkContext: Job finished: collect at

FindCommonFriends.java:69, took 0.051576509 s
debug1 key=(100,200) value=[200, 300, 400, 500]
debug1 key=(100,300) value=[200, 300, 400, 500]
debug1 key=(100,400) value=[200, 300, 400, 500]
debug1 key=(100,500) value=[200, 300, 400, 500]
debug1 key=(100,200) value=[100, 300, 400]
debug1 key=(200,300) value=[100, 300, 400]
debug1 key=(200,400) value=[100, 300, 400]
debug1 key=(100,300) value=[100, 200, 400, 500]
debug1 key=(200,300) value=[100, 200, 400, 500]
debug1 key=(300,400) value=[100, 200, 400, 500]
debug1 key=(300,500) value=[100, 200, 400, 500]
debug1 key=(100,400) value=[100, 200, 300]
debug1 key=(200,400) value=[100, 200, 300]
debug1 key=(300,400) value=[100, 200, 300]
debug1 key=(100,500) value=[100, 300]
debug1 key=(300,500) value=[100, 300]
debug1 key=(100,600) value=[]
14/05/31 21:33:46 INFO spark.SparkContext: Starting job: collect at

FindCommonFriends.java:78

14/05/31 21:33:46 INFO scheduler.DAGScheduler: Registering RDD 2 (flatMap

at FindCommonFriends.java:41)

14/05/31 21:33:46 INFO scheduler.DAGScheduler: Got job 2 (collect at

FindCommonFriends.java:78) with 1 output partitions (allowLocal=false)

216

...
14/05/31 21:33:46 INFO scheduler.DAGScheduler: Stage 2 (collect at

FindCommonFriends.java:78) finished in 0.212 s

14/05/31 21:33:46 INFO spark.SparkContext: Job finished: collect at

FindCommonFriends.java:78, took 0.335984028 s

debug2 key=(200,300) value=[[100, 300, 400], [100, 200, 400, 500]]
debug2 key=(100,300) value=[[200, 300, 400, 500], [100, 200, 400, 500]]
debug2 key=(100,200) value=[[200, 300, 400, 500], [100, 300, 400]]
debug2 key=(300,400) value=[[100, 200, 400, 500], [100, 200, 300]]
debug2 key=(100,500) value=[[200, 300, 400, 500], [100, 300]]
debug2 key=(200,400) value=[[100, 300, 400], [100, 200, 300]]
debug2 key=(100,400) value=[[200, 300, 400, 500], [100, 200, 300]]
debug2 key=(100,600) value=[[]]
debug2 key=(300,500) value=[[100, 200, 400, 500], [100, 300]]
14/05/31 21:33:46 INFO spark.SparkContext: Starting job: collect at

FindCommonFriends.java:122

14/05/31 21:33:46 INFO scheduler.DAGScheduler: Got job 3 (collect at

FindCommonFriends.java:122) with 1 output partitions (allowLocal=false)

...
14/05/31 21:33:47 INFO scheduler.DAGScheduler: Stage 4 (collect at

FindCommonFriends.java:122) finished in 0.068 s

14/05/31 21:33:47 INFO scheduler.TaskSchedulerImpl: Removed TaskSet 4.0,

whose tasks have all completed, from pool

14/05/31 21:33:47 INFO spark.SparkContext: Job finished: collect at

FindCommonFriends.java:122, took 0.084085412 s

debug3 key=(200,300) value=[100, 400]
debug3 key=(100,300) value=[200, 500, 400]
debug3 key=(100,200) value=[400, 300]
debug3 key=(300,400) value=[100, 200]
debug3 key=(100,500) value=[300]
debug3 key=(200,400) value=[100, 300]
debug3 key=(100,400) value=[200, 300]
debug3 key=(100,600) value=[]
debug3 key=(300,500) value=[100]

217

Chapter 9

Recommendation Engines using
MapReduce

This chapter deals with recommendation engines using MapReduce algo-
rithms.

If you are a frequent user of Amazon.com website, youre probably familiar
with the lists of related products they feature to help customers ﬁnd what
they are looking for on the site. Amazon.com, presents several such lists
on every page, including "Frequently Bought Together" and "Customers
Who Bought This Item Also Bought." These features have roots and solu-
tions in recommendation engines and systems. Examples of such applications
include recommending books, CDs and other products at Amazon.com. Typ-
ically, recommendation engines and systems enhance user experience in the
following ways:

• Assist users in ﬁnding information

• Reduce search and navigation time

• User satisfaction and return to the site frequently

The purpose of a recommender engine and systems are to predict or

recommend:

• items that user have not rated, bought, or navigated to those items yet

• movies or books that a user had not yet considered

218

• restaruants or locations that a user have not been there

Recommender systems have become extremely common in recent years.

A few examples of such systems are:

• Amazon.com and Mybuys.com, providers of recommender systems for

buying similar items

• When viewing a product on Amazon.com, the store will recommend
additional items based on a matrix of what other shoppers bought
along with the currently selected item.

• Tripbase.com, a travel recommendation website, which recommends

travel/vacation packages based on your input or prefrences.

• Netﬂix oﬀers predictions of movies that a user might like to watch based
on the user’s previous ratings and watching habits (as compared to the
behavior of other users).

In this chapter, we will address the following problems, which have roots
in recommendation engines and systems. For details on recommendation
systems, refer to [1], [26], and [9].

• Customers Who Bought This Item Also Bought

• Frequently Bought Together

• Movie Recommendation

• Recommend People Connection

219

9.1 Customers Who Bought This Item Also

Bought

including Amazon.com, use the feature
Most of the e-commerce vendors,
"Customers Who Bought This Item Also Bought" (CWBTIAB) on their
web site for recommending books, CDs, and other items. Here we will build
a simple recommendation system to answer CWBTIAB question.

Suppose that the Amazon.com store log contains "user-id" and "bought-item"

for each transaction sale. We are going to implement CWBTIAB function-
ality by MapReduce paradigm. Whenever the item is shown, the store will
suggest ﬁve other items most often bought by the buyers of the item.

9.1.1

Input

We assume that the input is a set of large transations (a transaction log
has a lot of data including, transaction-id, date, price, ...), which have the
following ﬁelds:

<user-id><,><bought-item>

9.1.2 Expected Output

The recommendation engine should emit the following (key, value) pairs:

• key: item

• value: list of ﬁve most common ”Customers Who Bought This Item

Also Bought” items

9.1.3 MapReduce Solution

We solve CWBTIAB problem with two iterations of MapReduce.

PHASE-1: The ﬁrst MapReduce iteration generates lists of all items bought
by the same user. Grouping is done by the Hadoop framework, both
mapper and reducer perform an identity function.

PHASE-2: The second MapReduce iteration solves co-occurrences problem
It uses the stripes approach and emits only ﬁve most

on list items.
common co-occurrences.

220

Before we discus PHASE-1 and PHASE-2, I will explain the concept of

stripes by a simple example.

9.1.3.1 Stripes Design Pattern

Stripes is a design pattern and the main idea behind it is to group together
pairs into an associative array. Consider the following (K,V)’s emitted by a
mapper (note that in this example, mappers output key is a composite key
as Tuple2):

A Mappers Output: Classic
Key
(k, k1)
(k, k2)
(k, k3)
(k, k4)
(z, z1)
(z, z2)
(z, z3)

Value
3
2
4
6
7
8
5

The idea behind stripes approch is that rather than emitting many (K,V)’s,
just emit one per stripe: for our example, we will emit only one (key, value)
pair per stripe as (k and z are called natural keys):

A Mappers Output: Stripes Approach

Key Value
k
z

{ (k1, 3), (k2, 2), (k3, 4), (k4, 6) }
{ (z1, 7), (z2, 8), (z3, 5) }

The stripes approach creates an associative array (or a hash table) per
natural key and it reduces the number of (K,V)’s emitted per mapper. But
the emitted value of mappers becomes a complex object (an associative ar-
ray), but with Stripes approach there will be less sorting and shuﬄing of
(K,V) pairs.

How does a reducer work in Stripes approach? Reducers perform element-
wise sum of associative arrays: consider the following three (K,V)’s for a
reducer (as input):

221

K -> { (a, 1), (b, 2), (c, 4), (d, 3) }
}
K -> { (a, 2),
(d, 5) }
K -> { (a, 3), (b, 5),

(c, 2)

Then, the generated output will be:

K -> { (a, 1+2+3), (b, 2+5), (c, 4+2), (d, 3+5) }

or

K -> { (a, 6), (b, 7), (c, 6), (d, 8) }

The advantages and disadvantages of the Stripes approch is summarized

below:

• Advantages

– Since mappers generate less (K,V) pairs than classic approch, then
there will be less sorting and shuﬄing of key-value pairs generated
by mappers

– Stripes enable us to utilize combiners and this way it can make

better use of combiners (as a local per node optimization)

– Better performance[12]

• Disadvantages

– More diﬃcult to implement (since value of the mappers is an as-
sociative array and we have to write a serilizer and deseializer for
that associative array)

– Underlying object (values generated by mappers as an associative

array) more heavyweight

– Fundamental limitation in terms of size of event space (since we
are creating an associate array per natural key, we need to make
sure that mappers have enough RAM to hold these hash tables).

222

9.1.3.2 MapReduce PHASE-1

This iteration generates lists of all items bought by the same user. Grouping
is done by the MapReduce framework on the userID (as a key). Both mapper
and reducer perform an identity function. The goal of PHASE-1 is to ﬁnd
all items purchaded by all users.

Mapper PHASE-1

The mapper is an identity function, which just emits (key,value) pairs as
received.

Listing 9.1: Mapper PHASE-1

1 // key = userID
2 // value = item bought by userID
3 map(userID, item) {
4
5 }

emit(userID, item);

Reducer PHASE-1

The reducer is an identity function, which just groups all items for a single
user.

Listing 9.2: Reducer PHASE-1

1 // key = userID
2 // value = list of items bought by userID
3 reduce(userID, items[I1, I2, ..., In]) {
4
5 }

emit(userID, items);

9.1.3.3 MapReduce PHASE-2

The second MapReduce iteration solves co-occurrences problem on list items.
We use the stripes approach, which basically keeps mappers busy by doing
more work similar to the combiners. So with the stripes approcah, the map-
pers aggregate as much as data, and then pass them to combiners and re-
ducers. Finally the reducers emit the expected outputs (an item followed by
list of ﬁve most common co-occurrences).

223

Since we might be creating so many hash tables (associative arrays) per
mappers/reducers, you need to make sure that you have enough memory to
hold these data structures. If number of users or items were large enough,
then it might not ﬁt in memory. If your memory/RAM is limited, then you
might consider creating these associative arrays (has tables) in disk (such a
solution is available in MapDB1.

Mapper PHASE-2

The mapper functionality includes combiner functionality as well (since we
are doing as much as possible by stripes technique in mappers). The stripes
approach minimizes the number of keys generated and therefore the MapRe-
duce’s execution framework has less shuﬄing and sorting to perform. Since
we are using non-primitive type for our values (an associative array), more
serialization and deserialization will be required.

Listing 9.3: Mapper PHASE-2

1 // key = userID
2 // value = list of items bought by userID
3 map(userID, items[I1, I2, ..., In]) {
4

for (Item item : items) {

Map<Item, Integer> map = new HashMap<Item, Integer>();
for (Item j : items) {

map(j) = map(j) + 1;

}
emit(item, map);

5

6

7

8

9

}

10
11 }

Reducer PHASE-2

The reducer generates ”top 5” items for every item in all transactions. The
reducer performs an item-wise sum of all stripes (represented as an associative
arrays) for a given item.

Listing 9.4: Reducer PHASE-2

1MapDB (developed by Jan Kotek) provides concurrent Maps, Sets and Queues backed
by disk storage or oﬀ-heap-memory. It is a fast and easy to use embedded Java database
engine. Source: http://www.mapdb.org

224

1 // key = item
2 // value = list of stripes[M1, M2, ..., Mm]
3 reduce(item, stripes[M1, M2, ..., Mm]) {
4

Map<Item, Integer> final = new HashMap<Item, Integer>();
for (Map<Item, Integer> map : stripes) {

5

6

7

8

9

10
11 }

for (all (k, v) in map) {

final(k) = final(k) + value;

}

}
emit(key, top(5, final))

The top(N, Map<Item, Integer>) will return N items, which have the

top/maximum frequencies for a given associate array.

225

Figure 9.1: Frequently Bought Together

9.2 Frequently Bought Together

The purpose of this section is to implement "Frequently Bought Together"
(FBT) feature by a MapReduce/Hadoop. FBT is a behavioral targeting tech-
nique, which is used for selecting advertisements and products that leverage
a user’s previous history in order to select and display other relevant prod-
ucts that the user may desire to purchase. For example, Amazon.com uses
”Frequently Bought Together” links underneath an item that a buyer is con-
sidering.

Suppose you are searching for Donald Knuth’s book (”The Art of Com-
puter Programming”) on Amazon.com. When you view this book on Ama-
zon.com site, they present a section called ”Frequently Bought Together,”
which lists books bought together. This list also includes the book you
searched. Here is the example:

Example: http://www.amazon.com/Computer-Programming-Volumes-1-4A-Boxed/dp/

0321751043/ref=sr_1_1?ie=UTF8&qid=1400102273&sr=8-1&keywords=knuth

How do they do come up with this list of ”Frequently Bought Together”
for most of their items? This is basically derived by a search for relationships
between items (such as books and CDs). Typically, e-commerce sites (such as
Amazon.com) gathers data on customer purchasing habits. Using association
rule learning, the Amazon.com can determine which products are frequently
bought together and use this information for marketing purposes. This is
sometimes referred to as variation on market basket analysis, a well-known
topic in data mining.

226

9.2.1

Input

Let us assume that we have an input of product sales transations for all
customers. Let’s then assume that we have n Transactions (labeled as
T1, · · · , Tn) and m products (labeled as P1, · · · , Pm), and furthermore let’s
assume that we have compiled the input as:

Transaction Purchased Items
T1
T2
...
Tn

{P1,1, P1,2, ..., P1,k1
{P2,1, P2,2, ..., P2,k2
...
{Pn,1, Pn,2, ..., Pn,kn

}

}

}

where Pi,j ∈ {P1, · · · , Pm}

and ki is the number of items purchased in transaction Ti

So each line of input is a transaction ID, followed by a list of products

purchased.

Therefore our goal is to build a hash table such for which the key will be
Pi for i = 1, 2, · · · , m and value will be list of products purchased together.

For example, if we have the following as an input:

Transaction Purchased Items
T1
T2
T3
T4
T5

{P1, P2, P3}
{P2, P3}
{P2, P3, P4}
{P5, P6}
{P3, P4}

Then our desired output will look like:

227

Item Frequently Bought Together
P1
P2
P3
P4
P5
P6

{P2, P3}
{P1, P3, P4}
{P1, P2, P4}
{P2, P3}
{P6}
{P5}

Therefore if a customer is browsing product P3, then we will say the

Frequently Bought Together products are P1, P2, and P4.

9.2.2 MapReduce Solution

The map() will take a single transation and generate a set of (key, value)
pairs to be consumed by reduce(). The mapper pairs the transaction items
(i.e., products) as a key and the number of key occurrences as its value in the
transaction (for all transactions and without the transaction ID – transaction
ID is ignored)

For example, map() for ”Transaction 1 (T1)” will emit the following (key,

value) pairs:

[<P1, P2>, 1]
[<P1, P3>, 1]
[<P2, P3>, 1]

We should note that if we select the two products in a transaction as a
key, there should be incorrect counting for the occurrence of the products in
the pairs. NEEDS CLARIFICATION: For example, if transactions T1 and
T2 have the same products T1: (P1, P2, P3) and T2: (P1, P3, P2), which
have the same products but in diﬀerent order.
For transaction T1, map() will generate:

[<P1, P2>, 1]
[<P1, P3>, 1]
[<P2, P3>, 1]

For transaction T2, map() will generate:

228

[<P1, P3>, 1]
[<P1, P3>, 1]
[<P3, P2>, 1]

As you observe from map() outputs for transactions T1 and T2, there-
fore, we have a total of six diﬀerent pairs of products that occur only once
respectively, when there should be three diﬀerent pairs. That is, keys (P2,
P3) and (P3, P2) are not the same even though they are. We know that this
is not correct. We can avoid this problem if we sort the transaction products
in alphabetical order before generating (key, value) pairs. After sorting items
in transations we will have:

sorted T1: (P1, P2, P3)
sorted T2: (P1, P2, P3)

Now each transaction (T1 and T2) have the following 3 pair of (key, value)

pairs:

[<P1, P2>, 1]
[<P1, P3>, 1]
[<P2, P3>, 1)

That is TWO diﬀerent pairs of products that occurs twice respectively so
that we accumulate the value of the occurrence for these two transactions as
follows: [¡P1, P2¿, 2], [¡P1, P3¿, 2], (¡P2, P3¿, 2), which is a correct count of
the total number of occurrences.

9.2.2.1 Mapper

Mapper reads the input data and creates a list of items for each transaction.
For each transaction, its time complexity is O(n) where n is the number of
items for a transaction. Then, the items in the transaction list are sorted to
avoid the duplicated keys; (P2, P3) and (P3, P2) are the same keys. Time
complexity of quicksort is O(nlogn). Then, the sorted transaction items
should be converted to pairs of items as keys, which is a cross operation that
allows us to generate cross pairs of the items in the list.

Listing 9.1: MBA map() Function

229

// key is transaction ID and ignored here
// value = transaction items (P1, P2, ...,Pm).
map(key, value) {

(S1, S2, ..., Sm) = sort(P1, P2, ...,Pm);
// now, we have: S1 < S2 < ... < Sm
ListOfPair<Si, Sj> = generateCombinations(S1, S2, ..., Sm)
for ( (Si, Sj) pair : ListOfPair<Si, Sj>) {

// reducer key is: (Si, Sj)
// reducer value is: integer 1
emit([(Si, Sj), 1]);

}

}

The generateCombinations(S1, S2, ..., Sm) generates all combinations
between any two items in a given transaction. For example, generateCombi-
nations(S1, S2, S3, S4) will return the following pairs:

(S1, S2)
(S1, S3)
(S1, S4)
(S2, S3)
(S2, S4)
(S3, S4)

Finally, map() will output the following (key, value) pairs:

<P1, P2> 1
<P1, P3> 1
<P2, P3> 1
<P2, P3> 1
<P2, P3> 1
<P3, P4> 1
<P5, P6> 1
<P1, P5> 1
<P3, P4> 1

9.2.2.2 Reducer

The ”Frequently Bought Together” algorithm for Reducer is illustrated be-
low. The reducer is to sum up the number of values per reducer key. Thus,
its time complexity is O(v) where v is the number of values per key.

230

Listing 9.2: MBA reduce() Function
// key is in form of (Si, Sj)
// value = List<integer>, where each element is an integer number
reduce(key, value) {

int sum = 0;
for (int i : List<integer>) {

sum += i;

}
emit(key, sum);

}

9.2.2.3 Reducer Output

The reducer will create the following output format:

<Pi, Pj>, N

where N is number of transaction, where products Pi and Pj have been
purchased together. The higher N indicates that there is close relationship
between these two products. Now, with this output, we can create the desired
hash table, where keys are in {P1, P2, · · · , Pm}.

For our input, the reducer will generate the following output:

<P1, P2> 1
<P1, P3> 1
<P2, P3> 3
<P2, P4> 1
<P3, P4> 2
<P5, P6> 1

231

9.3 Recommend People Connection

In this section, we provide a complete Spark-based MapReduce algorithm to
recommend people connection. These days, there are lots of social network
sites (Facebook, Instagram, LinkedIn, Pinterest...). One common feature in
social network site is to recommend that people connect. For example, the
”People you may know” feature from LinkedIn, allows members to consider
if Alex is a
who they might want to link with. The basic idea is this:
friend of Bob and Alex is a friend of Barbara (Alex is a common friend
of Bob and Barbara, but Bob and Barbara do not know each other) then
the social network system should recommend Bob to connect with Barbara
and vice versa. Therefore, the key point is that if two people have a set
of mutual friends, but they are not friends, then the MapReduce solution
should recommend them to be connected to each other.

Friendship among all users can be expressed as a graph. For our simple ex-
ample, we can show graph as:

In mathematics, a graph is an ordered pair G = (V, E) comprising a set
V of vertices or nodes together with a set E of edges or lines, which are
2-element subsets of V (i.e., an edge is related with two vertices, and the
relation is represented as an unordered pair of the vertices with respect to the
particular edge). This type of graph may be described precisely as undirected
and simple. Our assumption is that friendship between all people can be
represented in an undirected graph (if person A is a friend with person B,
then B is a friend with A). For our MapReduce solutions, we assume that
the friendships are undirected: if A is a friend of B then B is also a friend of
A. Most social networks (such as Facebook and LinkedIn) use bidirectional
frienships, while twitter’s friendship is directional. Therefore, we assume that
our graph is undirected.

In our case, the graph is an ordered pair G = (V, E) where
• V - ﬁnite set of people (users of social network)

• E - is a binary relation on V called the edge set, whose elements are

called friendship

From a graph theory perspective, for each person or member of a speciﬁc
social network, who is 2 − degree reachable from person A, we count how

232

Figure 9.2: Friendship Graph

233

many distinct paths (with 2 connecting edges) exist between this person and
person A. Rank this list in terms of the number of paths and show the top 10
persons that person A should connect with. We will show that how we can
use MapReduce solution to compute this top − 10 connection list for every
person. Therefore, the goal is to pre-compute (as a batch job) the top 10
recommended persons for every member of a social network.

The friendship-recommendation problem can be stated as: For every per-
son X, we determine a list of person X1, X2, · · · , X10 which is the top 10
persons that person X has common friends with.

9.3.1

Input

The social network graph is generally very sparse. Here we assume the input
record is an adjacency list sorted by name. Therefore, every line of input will
be a member ID (such as a user ID) followed by a list of immediate friends
identiﬁed by F1, F2, · · · , Fn

X

F1 F2 ... Fn

where F1 < F2 < · · · < Fn

For example, for three members, we have an adjacency list sorted by name

(here we use names instead of IDs to better comprehend the input):

alex => bob, jane, dave, terry
bob => alex, dan, jeff, phil
terry => alex, jeb, russel

We will read our unput from HDFS as:

# hadoop fs -cat /data/friends2.txt

1 2,3,4,5,6,7,8
2 1,3,4,5,7
3 1,2
4 1,2,6
5 1,2
6 1,4

234

7 1,2
8 1

User 1 is friends with all, so we should not have any recommendation for this
user. On the other hand, User 3 is friends with Users 1 and 2, therefore we
can recommend Users 4,5,6,7, and 8 to User 3 since {4,5,6,7,8} are mutual
friends of Users 1 and 2.

9.3.2 Output

The output of our Spark program will be provided in the following format:

<USER><:><F(M: [I1, I2, I3, ...]), ...>

where

F is "Recommended friend to USER"
M is the number of mutual friends
I1, I2, I3, ... are the ids of mutual friends

For our sample input, the expected output will be:

4: 3 (2: [1, 2]),5 (2: [1, 2]),7 (2: [1, 2]),8 (1: [1]),
2: 6 (2: [1, 4]),8 (1: [1]),
6: 2 (2: [1, 4]),3 (1: [1]),5 (1: [1]),7 (1: [1]),8 (1: [1]),
8: 2 (1: [1]),3 (1: [1]),4 (1: [1]),5 (1: [1]),6 (1: [1]),7 (1: [1]),
3: 4 (2: [1, 2]),5 (2: [1, 2]),6 (1: [1]),7 (2: [1, 2]),8 (1: [1]),
1:
7: 3 (2: [1, 2]),4 (2: [1, 2]),5 (2: [1, 2]),6 (1: [1]),8 (1: [1]),
5: 3 (2: [1, 2]),4 (2: [1, 2]),6 (1: [1]),7 (2: [1, 2]),8 (1: [1]),

Note that User 1 does not have any friend recommendation, since he is friends
with everyone. The output can be veriﬁed from the graph.

235

9.3.3 MapReduce Solution

This section provides a general MapReduce solution without using any spe-
ciﬁc framework implementations. To solve ”Recommend People Connection”
problem, we just need a mapper and a reducer outlined below. The mapper
identiﬁes direct friends and possible future friends (which will be recom-
mended).

Listing 9.5: Recommend People Connection: Mapper

1 // key = person (as Long for userID)
2 // value = friends = List<userID> = direct friends of person as {F1, F2, F3, ...}
3 map(key, friends) {
4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

// emit all direct friendships
for (friend : friends) {

// -1 denotes direct friendship
directFriend = Tuple2(friend, -1);
emit(key, directFriend);

}

// emit all possible friendships, where
// they have mutual friend, person (as a key)
for (int i = 0; i < friends.size(); i++) {

for (int j = i + 1; j < friends.size(); j++) {

// possible friend 1
possibleFriend1 = Tuple2(friends.get(j), person);
emit(friends.get(i), possibleFriend1);
// possible friend 2
possibleFriend2 = Tuple2(friends.get(i), person);
emit(friends.get(j), possibleFriend2);

}

}

23
24 }

Reducer is presented below. The reducer ﬁnds mutual friends between the
key (as a person), and the value (which is a list of Tuple2<Long, Long>). If
any of values has a mutual friend (denoted by special long value as -1), then
we do not make the recommendation since they are already friends. Finally,
we prepare a formatted output, which might be read by other programs for
further processing.

Listing 9.6: Recommend People Connection: Reducer

1 // key = person
2 // values = possible recommendations as List<Tuple2<userID1, userID2>>
3 reduce(key, values) {
4

236

// mutualFriends.key is the recommended friend
// mutualFriends.value is the list of mutual friends
Map<Long, List> mutualFriends = new HashMap<Long, List>();

for (Tuple2<toUser, mutualFriend> t2 : values) {

Long toUser = t2.toUser; // t2._1
Long mutualFriend = t2.mutualFriend; // t2._2
boolean alreadyFriend = (mutualFriend == -1);

if (mutualFriends.containsKey(toUser)) {

if (isAlreadyFriend) {

mutualFriends.put(toUser, null);

}
else if (mutualFriends.get(toUser) != null) {

mutualFriends.get(toUser).add(mutualFriend);

}

}
else {

if (alreadyFriend) {

mutualFriends.put(toUser, null);

}
else {

mutualFriends.put(toUser, List<mutualFriend>)

}

}

}

String reducerOutput = buildOutput(mutualFriends);
emit(key, reducerOutput);

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 }

The buildOutput() method deﬁnition is given below:

Listing 9.7: buildOutput() Method

1 String buildOutput(Map<Long, List> map) {
2

String output = "";
for (Map.Entry<Long, List> entry : map.entrySet()) {

String K = entry.getKey();
List V = entry.getValue();
output += K + " (" + V.size() + ": " + V + "),";

}
return output;

3

4

5

6

7

8
9 }

9.4 Spark Implementation

Our implementation of MapReduce solution uses Spark-1.0.0 Java API (as
a Spark/Hadoop/YARN job). Since Spark provids a higher-level Java API

237

than MapReduce/Hadoop API, we will present the entire solution in a single
Java class (called SparkFriendRecommendation), which will include a series
of flatMapToPair() and groupBy() functions. Spark’s MapReduce abstrac-
tion is based on RDDs2 We use JavaRDD<T> (to represent a set of objects of
type T) and JavaPairRDD<K,V> (to represent a set of (K,V) pairs).

First, I will provide a high-level solution in 10 basic steps, and then we will
dissect into each step with a proper working Spark code. Note that some
of these steps can be merged (to create somewhat complex steps), but for
simplicity reasons I did not merege them.

Listing 9.8: SparkFriendRecommendation: High Level Steps

1 // STEP-0: import required classes and interfaces
2 public class SparkFriendRecommendation {
3

4

5

6

7

8

9

10

11

12

1

2

3

4

5

6

7

8

9

10

11

12

13

public static void main(String[] args) throws Exception {

// STEP-1: handle input parameters
// STEP-2: create a Spark’s context object
// STEP-3: read hdfs input text and create the first RDD
// STEP-4: implement map() function
// STEP-5: implement reduce() function
// STEP-6: generate desired final output
System.exit(0);

}

The following helper methods are used in our Spark solution:

Listing 9.9: SparkFriendRecommendation: Helper Methods

static String buildRecommendations(Map<Long, List<Long>> mutualFriends) {

// body of buildRecommendations()

}

// convenient methods to create Tuple2<long,long>
static Tuple2<Long,Long> T2(long a, long b) {

return new Tuple2<Long,Long>(a, b);

}

// convenient methods to create Tuple2<long, Tuple2<long,long>>
static Tuple2<Long,Tuple2<Long,Long>> T2(long a, Tuple2<Long,Long> b) {

return new Tuple2<Long,Tuple2<Long,Long>>(a, b);

}

2In Spark, an RDD (Resilient Distributed Dataset) is the basic abstraction for data
representation. Represents an immutable, partitioned collection of elements that can be
operated on in parallel.

238

9.4.1 STEP-0: Import Required Classes

This step imports required classes and interfaces. We just utilize two impo-
rant packages from Spark:

• org.apache.spark.api.java

This package deﬁnes RDDs (JavaRDD, JavaPairRDD, and JavaSpark-
Context)

• org.apache.spark.api.java.function

This package deﬁnes transformation functions (Function and PairFlatMap-
Function)

Listing 9.10: STEP-0: Import Required Classes

1 // STEP-0: import required classes and interfaces
2 import scala.Tuple2;
3 import org.apache.spark.api.java.JavaRDD;
4 import org.apache.spark.api.java.JavaPairRDD;
5 import org.apache.spark.api.java.JavaSparkContext;
6 import org.apache.spark.api.java.function.Function;
7 import org.apache.spark.api.java.function.PairFlatMapFunction;
8 import java.util.Arrays;
9 import java.util.List;
10 import java.util.ArrayList;
11 import java.util.Map;
12 import java.util.HashMap;

9.4.2 STEP-1: Handle Input Parameters

We read 2 input parameters: ”spark master URL” and users data (as HDFS
text ﬁle), which contains users and its associated friends.

Listing 9.11: STEP-1: Handle Input Parameters

1

2

3

4

5

6

7

// STEP-1: handle input parameters
if (args.length < 2) {

System.err.println("Usage: SparkFriendRecommendation <master> <file>");
System.exit(1);

}
String sparkMasterURL = args[0];
String hdfsInputFile = args[1];

239

9.4.3 STEP-2: Create Spark’s Context Object

A JavaSparkContext3 object is created by using spark master URL. This
object is used to create ﬁrst RDD. JavaSparkContext returns JavaRDDs and
works with Java collections such as List<T> and Iterable<T>. There are
several ways to create JavaSparkContext object, for details refer to Spark’s
Java API.

Listing 9.12: STEP-2: create a Spark’s context object

1

2

3

4

5

6

// STEP-2: create a Spark’s context object
JavaSparkContext ctx = new JavaSparkContext(

sparkMasterURL,
"SparkFriendRecommendation",
System.getenv("SPARK_HOME"),
System.getenv("SPARK_EXAMPLES_JAR"));

Note that, we created an instance of a JavaSparkContext object by
connecting to a Spark cluster.
If you are running Spark on a Hadoop/-
YARN cluster (without starting an Spark cluster), then you should create
JavaSparkContext object as (assuming that your YARN resource manager
server is ”server100”):

SparkConf conf = new SparkConf();
conf.set("yarn.resourcemanager.hostname", "server100");
conf.set("yarn.resourcemanager.scheduler.address", "server100:8030");
conf.set("yarn.resourcemanager.resource-tracker.address", "server100:8031");
conf.set("yarn.resourcemanager.address",
conf.set("mapreduce.framework.name", "yarn");
conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
conf.set("spark.executor.memory", "7g");
JavaSparkContext ctx = new JavaSparkContext("yarn-cluster", "myprogram", conf);

"server100:8032");

9.4.4 STEP-3: Read HDFS Input File

JavaSparkContext returns the ﬁrst JavaRDD<String> object, which repre-
sents all records from the HDFS Input File. I use JavaRDD.collect() for
debugging purposes to make sure we have the correct input data.

3org.apache.spark.api.java.JavaSparkContext

240

Listing 9.13: STEP-3: Read HDFS Input File

// STEP-3: read hdfs text and create the first RDD
JavaRDD<String> records = ctx.textFile(hdfsInputFile, 1);

// debug0
List<String> debug1 = records.collect();
for (String t : debug1) {

System.out.println("debug1 record="+t);

}

1

2

3

4

5

6

7

8

9.4.5 STEP-4: Implement map() Function

This step implements the map() algorithm we presented earlier as part of the
MapReduce algorithm. The mapper converts each record of

<person><TAB><friend1><,><friend2><,><friend3><,>...

into (key, value) pairs where key is the <person> and value a Tuple2<user1,user2>

signifying direct friendship or possible future friendship. The mapper is im-
plemented by JavaRDD.flatMapToPair() function. This implementation is
accomplished by providing call() method as:

JavaPairRDD<K2,V2> flatMapToPair(PairFlatMapFunction<T,K2,V2> f)
// Return a new RDD by first applying a function to all
// elements of this RDD, and then flattening the results.

PairFlatMapFunction<T, K, V>
T => Iterable<Tuple2<K, V>>

where

T is an input parameter/record
(K,V) pairs are generated from T

Here is the detail of mapper implementation:

241

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

Listing 9.14: STEP-4: implement map() function

<K2,V2> JavaPairRDD<K2,V2> flatMapToPair(PairFlatMapFunction<T,K2,V2> f)
Return a new RDD by first applying a function to all elements of this RDD,
and then flattening the results.

// STEP-4: implement map() function
// flatMapToPair
//
//
//
//
// PairFlatMapFunction<T, K, V>
// T => Iterable<Tuple2<K, V>>
JavaPairRDD<Long, Tuple2<Long,Long>> pairs =

//
records.flatMapToPair(new PairFlatMapFunction<String, Long, Tuple2<Long,Long>>() {

K

V

T

public Iterable<Tuple2<Long,Tuple2<Long,Long>>> call(String record) {
// record=<person><TAB><friend1><,><friend2><,><friend3><,>...
String[] tokens = record.split("\t");
long person = Long.parseLong(tokens[0]);
String friendsAsString = tokens[1];
String[] friendsTokenized = friendsAsString.split(",");

List<Long> friends = new ArrayList<Long>();
List<Tuple2<Long,Tuple2<Long, Long>>> mapperOutput =

new ArrayList<Tuple2<Long,Tuple2<Long, Long>>>();

for (String friendAsString : friendsTokenized) {
long toUser = Long.parseLong(friendAsString);
friends.add(toUser);
Tuple2<Long,Long> directFriend = T2(toUser, -1L);
mapperOutput.add(T2(person, directFriend));

}

for (int i = 0; i < friends.size(); i++) {

for (int j = i + 1; j < friends.size(); j++) {

// possible friend 1
Tuple2<Long,Long> possibleFriend1 = T2(friends.get(j), person);
mapperOutput.add(T2(friends.get(i), possibleFriend1));
// possible friend 2
Tuple2<Long,Long> possibleFriend2 = T2(friends.get(i), person);
mapperOutput.add(T2(friends.get(j), possibleFriend2));

}

}
return mapperOutput;

}
});

To debug STEP˙4, we used the following code:

// debug2
List<Tuple2<Long,Tuple2<Long,Long>>> debug2 = pairs.collect();
for (Tuple2<Long,Tuple2<Long,Long>> t2 : debug2) {

System.out.println("debug2 key="+t2._1+"\t value="+t2._2);

}

242

9.4.6 STEP-5: Implement reduce() Function

Listing 9.15: STEP-5: implement reduce() function

// STEP-5: implement reduce() function
JavaPairRDD<Long, Iterable<Tuple2<Long, Long>>> grouped = pairs.groupByKey();

// debug3
List<Tuple2<Long, Iterable<Tuple2<Long, Long>>>> debug3 = grouped.collect();
for (Tuple2<Long, Iterable<Tuple2<Long, Long>>> t2 : debug3) {
System.out.println("debug3 key="+t2._1+"\t value="+t2._2);

}

9.4.7 STEP-6: Generate Final Output

The ﬁnal output is created from aggregating all values grouped by in STEP-
5. This step generates ﬁnal recommendations for possible future friendships.
This step uses JavaPairRDD.mapValues() method:

public <U> JavaPairRDD<K,U> mapValues(Function<V,U> f)

Description: Pass each value in the key-value pair RDD through

a map function without changing the keys; this also
retains the original RDD’s partitioning.

This step converts Iterable<Tuple2<Long, Long>> (as input) into a String
object (as output). Details of implementation for this step is given below.

Listing 9.16: STEP-6: generate desired ﬁnal output

// STEP-6: generate desired final output
// Find intersection of all List<List<Long>>
// mapValues[U](f: (V) => U): JavaPairRDD[K, U]
// Pass each value in the key-value pair RDD through a map
// function without changing the keys;
// this also retains the original RDD’s partitioning.
JavaPairRDD<Long, String> recommendations =

grouped.mapValues(new Function< Iterable<Tuple2<Long, Long>>, // input

243

1

2

3

4

5

6

7

8

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

public String call(Iterable<Tuple2<Long, Long>> values) {

String

>() {

// final output

// mutualFriends.key = the recommended friend
// mutualFriends.value = the list of mutual friends
final Map<Long, List<Long>> mutualFriends = new HashMap<Long, List<Long>>();
for (Tuple2<Long, Long> t2 : values) {

final Long toUser = t2._1;
final Long mutualFriend = t2._2;
final boolean alreadyFriend = (mutualFriend == -1);

if (mutualFriends.containsKey(toUser)) {

if (alreadyFriend) {

mutualFriends.put(toUser, null);

}
else if (mutualFriends.get(toUser) != null) {

mutualFriends.get(toUser).add(mutualFriend);

}

}
else {

if (alreadyFriend) {

mutualFriends.put(toUser, null);

}
else {

List<Long> list1 = new ArrayList<Long>(Arrays.asList(mutualFriend));
mutualFriends.put(toUser, list1);

}

}

}
return buildRecommendations(mutualFriends);

}
});

To debug STEP˙6, we used the following code:

// debug4
List<Tuple2<Long,String>> debug4 = recommendations.collect();
for (Tuple2<Long,String> t2 : debug4) {

System.out.println("debug4 key="+t2._1+ "\t value="+t2._2);

}

9.4.8 Convenient Methods

244

Listing 9.17: Convenient Methods

static String buildRecommendations(Map<Long, List<Long>> mutualFriends) {

StringBuilder recommendations = new StringBuilder();
for (Map.Entry<Long, List<Long>> entry : mutualFriends.entrySet()) {

if (entry.getValue() == null) {

// already a friend, no need to recommend again!
continue;

}
recommendations.append(entry.getKey());
recommendations.append(" (");
recommendations.append(entry.getValue().size());
recommendations.append(": ");
recommendations.append(entry.getValue());
recommendations.append("),");

}
return recommendations.toString();

}

static Tuple2<Long,Long> T2(long a, long b) {

return new Tuple2<Long,Long>(a, b);

}

static Tuple2<Long,Tuple2<Long,Long>> T2(long a, Tuple2<Long,Long> b) {

return new Tuple2<Long,Tuple2<Long,Long>>(a, b);

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

9.4.9 HDFS Input

# hadoop fs -cat /data/friends2.txt
1 2,3,4,5,6,7,8
2 1,3,4,5,7
3 1,2
4 1,2,6
5 1,2
6 1,4
7 1,2
8 1

9.4.10 Script to Run Spark Program

# cat run_friends_recommendations2.sh

245

#!/bin/bash
source /home/hadoop/conf/env_2.3.0.sh
export SPARK_HOME=/home/hadoop/spark-1.0.0
source /home/hadoop/spark_mahmoud_examples/spark_env_yarn.sh
source $SPARK_HOME/conf/spark-env.sh

# system jars:
CLASSPATH=$CLASSPATH:$HADOOP_HOME/etc/hadoop

jars=‘find $SPARK_HOME -name ’*.jar’‘
for j in $jars ; do

CLASSPATH=$CLASSPATH:$j

done

# app jar:
export CLASSPATH=/home/hadoop/spark_mahmoud_examples/mp.jar:$CLASSPATH
export SPARK_CLASSPATH=$CLASSPATH
export SPARK_MASTER=spark://myserver100:7077
#-Dsun.lang.ClassLoader.allowArraySyntax=true
USERS=/data/friends2.txt
OPTIONS="-Dsun.lang.ClassLoader.allowArraySyntax=true -Dspark.master=$SPARK_MASTER"
$JAVA_HOME/bin/java -cp $CLASSPATH $OPTIONS SparkFriendRecommendation $SPARK_MASTER $USERS

9.4.11 Program Run Log

The log is trimmed and edited to ﬁt the page.

# ./run_friends_recommendations2.sh
...
14/06/02 12:46:50 WARN spark.SparkConf: null jar passed to SparkContext constructor
14/06/02 12:46:51 INFO slf4j.Slf4jLogger: Slf4jLogger started
14/06/02 12:46:51 INFO Remoting: Starting remoting
14/06/02 12:46:51 INFO Remoting: Remoting started; listening on addresses :

[akka.tcp://spark@myserver100:38397]

14/06/02 12:46:51 INFO Remoting: Remoting now listens on addresses:

[akka.tcp://spark@myserver100:38397]

...

246

14/06/02 12:46:51 INFO server.AbstractConnector:

Started SocketConnector@0.0.0.0:43523

14/06/02 12:46:51 INFO broadcast.HttpBroadcast:

Broadcast server started at http://myserver100:43523

...
14/06/02 12:46:52 INFO client.AppClient$ClientActor:
Connecting to master spark://myserver100:7077...

...
14/06/02 12:46:57 INFO scheduler.DAGScheduler: Stage 0

(collect at SparkFriendRecommendation.java:34) finished in 3.446 s

14/06/02 12:46:57 INFO spark.SparkContext: Job finished:

collect at SparkFriendRecommendation.java:34, took 3.543265173 s

debug1 record=1 2,3,4,5,6,7,8
debug1 record=2 1,3,4,5,7
debug1 record=3 1,2
debug1 record=4 1,2,6
debug1 record=5 1,2
debug1 record=6 1,4
debug1 record=7 1,2
debug1 record=8 1
14/06/02 12:46:57 INFO spark.SparkContext: Starting job:

collect at SparkFriendRecommendation.java:79

...
14/06/02 12:46:58 INFO scheduler.DAGScheduler: Stage 1

(collect at SparkFriendRecommendation.java:79) finished in 1.643 s

14/06/02 12:46:58 INFO spark.SparkContext: Job finished:

collect at SparkFriendRecommendation.java:79, took 1.654938027 s

debug2 key=1
debug2 key=1
debug2 key=1
debug2 key=1
debug2 key=1
debug2 key=1
debug2 key=1
debug2 key=2
debug2 key=3
debug2 key=2
debug2 key=4

value=(2,-1)
value=(3,-1)
value=(4,-1)
value=(5,-1)
value=(6,-1)
value=(7,-1)
value=(8,-1)
value=(3,1)
value=(2,1)
value=(4,1)
value=(2,1)

247

debug2 key=2
debug2 key=5
debug2 key=2
debug2 key=6
debug2 key=2
debug2 key=7
debug2 key=2
debug2 key=8
debug2 key=3
debug2 key=4
debug2 key=3
debug2 key=5
debug2 key=3
debug2 key=6
debug2 key=3
debug2 key=7
debug2 key=3
debug2 key=8
debug2 key=4
debug2 key=5
debug2 key=4
debug2 key=6
debug2 key=4
debug2 key=7
debug2 key=4
debug2 key=8
debug2 key=5
debug2 key=6
debug2 key=5
debug2 key=7
debug2 key=5
debug2 key=8
debug2 key=6
debug2 key=7
debug2 key=6
debug2 key=8
debug2 key=7
debug2 key=8

value=(5,1)
value=(2,1)
value=(6,1)
value=(2,1)
value=(7,1)
value=(2,1)
value=(8,1)
value=(2,1)
value=(4,1)
value=(3,1)
value=(5,1)
value=(3,1)
value=(6,1)
value=(3,1)
value=(7,1)
value=(3,1)
value=(8,1)
value=(3,1)
value=(5,1)
value=(4,1)
value=(6,1)
value=(4,1)
value=(7,1)
value=(4,1)
value=(8,1)
value=(4,1)
value=(6,1)
value=(5,1)
value=(7,1)
value=(5,1)
value=(8,1)
value=(5,1)
value=(7,1)
value=(6,1)
value=(8,1)
value=(6,1)
value=(8,1)
value=(7,1)

248

debug2 key=2
debug2 key=2
debug2 key=2
debug2 key=2
debug2 key=2
debug2 key=1
debug2 key=3
debug2 key=1
debug2 key=4
debug2 key=1
debug2 key=5
debug2 key=1
debug2 key=7
debug2 key=3
debug2 key=4
debug2 key=3
debug2 key=5
debug2 key=3
debug2 key=7
debug2 key=4
debug2 key=5
debug2 key=4
debug2 key=7
debug2 key=5
debug2 key=7
debug2 key=3
debug2 key=3
debug2 key=1
debug2 key=2
debug2 key=4
debug2 key=4
debug2 key=4
debug2 key=1
debug2 key=2
debug2 key=1
debug2 key=6
debug2 key=2
debug2 key=6

value=(1,-1)
value=(3,-1)
value=(4,-1)
value=(5,-1)
value=(7,-1)
value=(3,2)
value=(1,2)
value=(4,2)
value=(1,2)
value=(5,2)
value=(1,2)
value=(7,2)
value=(1,2)
value=(4,2)
value=(3,2)
value=(5,2)
value=(3,2)
value=(7,2)
value=(3,2)
value=(5,2)
value=(4,2)
value=(7,2)
value=(4,2)
value=(7,2)
value=(5,2)
value=(1,-1)
value=(2,-1)
value=(2,3)
value=(1,3)
value=(1,-1)
value=(2,-1)
value=(6,-1)
value=(2,4)
value=(1,4)
value=(6,4)
value=(1,4)
value=(6,4)
value=(2,4)

249

debug2 key=5
debug2 key=5
debug2 key=1
debug2 key=2
debug2 key=6
debug2 key=6
debug2 key=1
debug2 key=4
debug2 key=7
debug2 key=7
debug2 key=1
debug2 key=2
debug2 key=8
14/06/02 12:46:58 INFO spark.SparkContext: Starting job:

value=(1,-1)
value=(2,-1)
value=(2,5)
value=(1,5)
value=(1,-1)
value=(4,-1)
value=(4,6)
value=(1,6)
value=(1,-1)
value=(2,-1)
value=(2,7)
value=(1,7)
value=(1,-1)

collect at SparkFriendRecommendation.java:88
14/06/02 12:46:58 INFO scheduler.DAGScheduler:

Registering RDD 2 (flatMapToPair at SparkFriendRecommendation.java:42)

...
14/06/02 12:46:59 INFO scheduler.DAGScheduler: Stage 2

(collect at SparkFriendRecommendation.java:88) finished in 0.319 s

14/06/02 12:46:59 INFO spark.SparkContext: Job finished:

collect at SparkFriendRecommendation.java:88, took 0.408234901 s

debug3 key=4

value=[(2,1), (3,1), (5,1), (6,1), (7,1), (8,1), (1,2),

debug3 key=2

value=[(3,1), (4,1), (5,1), (6,1), (7,1), (8,1), (1,-1), (3,-1),

(3,2), (5,2), (7,2), (1,-1), (2,-1), (6,-1), (1,6)]

(4,-1), (5,-1), (7,-1), (1,3), (1,4), (6,4), (1,5), (1,7)]

debug3 key=6

value=[(2,1), (3,1), (4,1), (5,1), (7,1), (8,1), (1,4),

(2,4), (1,-1), (4,-1)]

debug3 key=8
debug3 key=3

value=[(2,1), (3,1), (4,1), (5,1), (6,1), (7,1), (1,-1)]
value=[(2,1), (4,1), (5,1), (6,1), (7,1), (8,1), (1,2),
(4,2), (5,2), (7,2), (1,-1), (2,-1)]

debug3 key=1

value=[(2,-1), (3,-1), (4,-1), (5,-1), (6,-1), (7,-1), (8,-1), (3,2),

(4,2), (5,2), (7,2), (2,3), (2,4), (6,4), (2,5), (4,6), (2,7)]

debug3 key=7

value=[(2,1), (3,1), (4,1), (5,1), (6,1), (8,1), (1,2), (3,2),

(4,2), (5,2), (1,-1), (2,-1)]

debug3 key=5

value=[(2,1), (3,1), (4,1), (6,1), (7,1), (8,1), (1,2), (3,2),

14/06/02 12:46:59 INFO spark.SparkContext: Starting job:

(4,2), (7,2), (1,-1), (2,-1)]

250

collect at SparkFriendRecommendation.java:135

14/06/02 12:46:59 INFO scheduler.DAGScheduler: Got job 3 (collect at

SparkFriendRecommendation.java:135) with 1 output partitions (allowLocal=false)

...
14/06/02 12:46:59 INFO scheduler.DAGScheduler: Stage 4 (collect at

SparkFriendRecommendation.java:135) finished in 0.109 s

14/06/02 12:46:59 INFO spark.SparkContext: Job finished: collect

at SparkFriendRecommendation.java:135, took 0.124233834 s

debug4 key=4
debug4 key=2
debug4 key=6
debug4 key=8
debug4 key=3
debug4 key=1
debug4 key=7
debug4 key=5

value=3 (2: [1, 2]),5 (2: [1, 2]),7 (2: [1, 2]),8 (1: [1]),
value=6 (2: [1, 4]),8 (1: [1]),
value=2 (2: [1, 4]),3 (1: [1]),5 (1: [1]),7 (1: [1]),8 (1: [1]),
value=2 (1: [1]),3 (1: [1]),4 (1: [1]),5 (1: [1]),6 (1: [1]),7 (1: [1]),
value=4 (2: [1, 2]),5 (2: [1, 2]),6 (1: [1]),7 (2: [1, 2]),8 (1: [1]),
value=
value=3 (2: [1, 2]),4 (2: [1, 2]),5 (2: [1, 2]),6 (1: [1]),8 (1: [1]),
value=3 (2: [1, 2]),4 (2: [1, 2]),6 (1: [1]),7 (2: [1, 2]),8 (1: [1]),

251

Chapter 10

Content-Based Recommendation:
Movies

Have you ever asked how does Netﬂix (or similar web sites) create movie or
book recommendation to its users? There must be some kind of magic algo-
rithm to do this kind of recommendation, right? Netﬂix even oﬀered one mil-
lion dollars for ﬁnding the optimal solution for movie recommendations[18].
Content-based recommendation systems, such as Netﬂix for movies, examine
properties of items (such as movies) recommended. For example, if a user
has watched a lot of action movies, then the recommendation system will
suggest movies, which are categorized as tt ”action” movies.

Here we present a basic MapReduce solution, which is based on Edwin Chen’s
blog[6]. Suppose you run an online movie business, and you want to generate
movie recommendations. You have a rating system (people can rate movies
with 1 to 5 stars), and well assume for simplicity that all of the ratings are
stored in a TSV (Tab Separated Value) ﬁle in HDFS. After presenting a
generic MapReduce solution, we provide a concrete Spark implementation
for movie recommendation.

We should note that in content-based recommendation techniques, the more
information (such as a domain knowledge and metadata) we have about con-
tents, the algorithms become more complex (more variables are involved),
but recommendations become more accurate and reasonable. For example,
for movie recommendations the recommendation system needs to know the

252

additional metadata such as actors, directors, and producers. For our exam-
ples here, we will limit our algorithms only to ”ratings of movies”. Typically,
in a recommendation-system application there are two classes of entities users
and items. In a movie recommendation, users are people, who watched and
rated movies and items are movies. The input data in the following section
will show the relationship (rating a movie from 1 to 5) between users and
movies.

The purpose of this section is to present a three-phase MapReduce solution
for movie recommendations:

• PHASE-1: Find total number of raters for each movie

• PHASE-2: For every pair of movies A and B, ﬁnd all the people who

rated both A and B.

• PHASE-3: Find correlation of every two related movies

10.1

Input

We assume that the raw input data in the following format:

user movie rating

Where user is a user id, who rated the movie and rating is a an integer

number from 1 to 5. An example is given below:

Users and Movies
User Movie Rating
User1 Movie1
User1 Movie2
User1 Movie3
User2 Movie1
User2 Movie2
User2 Movie3
User2 Movie5
...

1
2
3
1
2
3
5
...

...

From this input we generate another input, which has the following format

(we basically group by movie).

253

10.2 MapReduce PHASE-1

The goal of this phase is to generate the following output.

user movie rating numberOfRaters

where numberOfRaters is the number of people who rated that speciﬁc
movie. For ﬁnding numberOfRaters, we write a simple MapReduce job com-
prised of a mapper and a reducer. Given an input record of <user><movie><rating>,
the mapper emits (K2, V2) pair, where K2 is movie and V2 is a Tuple2(user,
rating). The reducer ﬁnds out the number of times a movie has been rated
and then generates our desired output (as deﬁned above).

Mapper PHASE-1

Listing 10.1: Mapper PHASE-1

1 map( <user> <movie>
K2 = <movie>;
2
V2 = Tuple2(user, rating);
emit(K2, V2);

3

<rating>) {

4
5 }

Reducer PHASE-1

Listing 10.2: Reducer PHASE-1

1 //key = <movie>
2 //values = List<Tuple2<user,rating>>
3 reduce(key, values) {
4

numberOfRaters = values.size();
for (Tuple2<user,rating> t2 : values) {

5

6

7

8

K3 = t2.user;
V3 = Tuple3(key, t2.rating, numberOfRaters);
emit(K3, V3);

}

9
10 }

The output of PHASE-1 will be used as in input to PHASE-2.

254

10.3 MapReduce PHASE-2 and PHASE-3

MapReduce solution will calculate how similar pairs of movies are, so that if
someone watches The Lion King, you can recommend ﬁlms like Toy Story.
So how should you deﬁne the similarity between two movies? One way is to
use their correlation[29]:

• For every pair of movies A and B, ﬁnd all the people who rated both

A and B.

• Use these ratings to form a Movie A vector and a Movie B vector.

• Calculate the correlation (mutual relation of two or more movies –
here, the correlation is a way to measure how associated or related two
movies are) between these two vectors.

• Whenever someone watches a movie, you can then recommend the

movies most correlated with it.

The ﬁrst two steps will be done by MapReduce-Phase-2 (will generate a
Movie A vector and a Movie B vector). The last two steps will be done by
MapReduce-Phase-3 (to calculate the correlation between every two-related
movies).

To get all pairs of co-rated movies, we’ll join our input (all movie ratings)
against itself (similar to SQL’s joining a table against itself). To join ratings
input against itself, the mapper will collect all movies per user and then
reducer will generate unique combinations of all movies rated by a user.

To understand this better, lets create a sample input for two users (note
that this input is generated by PHASE-1 – each record contains: user, movie,
rating, and numberOfRaters):

255

Users and Movies
User Movie Rating Number of Raters
User1 Movie1
User1 Movie2
User1 Movie3
User2 Movie1
User2 Movie2
User2 Movie3
User2 Movie5
...

10
20
30
10
20
30
50
...

1
2
3
1
2
3
5
...

...

10.4 MapReduce-Phase-2 Mapper

The map() will accept one line of input as:

<user> <movie> <rating> <numberOfRaters>

and emit a (key, value) pair as:

key: <user>

value: <movie> <rating> <numberOfRaters>

Here is the deﬁnition of map() function:

Listing 10.3: Mapper PHASE-2

1 // key is <user>
2 // value = <movie> <rating> <NumOfRaters>
3 map(key, value) {
4

String[] tokens = value.split("\t");
movie = tokens[0];
rating = tokens[1];
numberOfRaters = tokens[2];
Tuple3<String, Integer, Integer> t3 = Tuple3(movie, rating, numberOfRaters);
emit(key, t3);

5

6

7

8

9
10 }

The mapper will generate the following output for our sample input (to

be consumed by reducers):

256

Mappers Output

KEY VALUE
User1
User1
User1
User2
User2
User2
User2
...

<Movie1, 1, 10>
<Movie2, 2, 20>
<Movie3, 3, 30>
<Movie1, 1, 10>
<Movie2, 2, 20>
<Movie3, 3, 30>
<Movie5, 5, 50>
...

10.5 MapReduce-Phase-2 Reducer

The reduce() will accept a user (as a key) and list of Tuple3(movie, rating,
numOfRaters) and will emit unique combiations of all movies rated by user.

Therefore, input for reducer will look like:

Output of Sort and Shuﬄe
KEY VALUE(s)
User1

[<Movie1, 1, 10>,
<Movie2, 2, 20>,
<Movie3, 3, 30>]
[<Movie1, 1, 10>,
<Movie2, 2, 20>,
<Movie3, 3, 30>,
<Movie5, 5, 50>]
...

User2

...

Here is the deﬁnition of reduce() function, which will join output of

”Sort and Shuﬄe” phase against itself (join will be on the ”user” key).

Listing 10.4: Reducer PHASE-2

1 // key is user (generated by map())
2 // value = List{ Tuple3(<movie> <rating> <NumOfRaters>) }
3 reduce(key, value) {
4

// Generate unique combinations of all movies against each other
// make sure not create duplicate entries like (movie1, movie2) and
// (movie2, movie1).

5

6

257

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

// To avoid this, we will create (movie1, movie2)
// where movie1 < movie2
List[ Tuple2( Tuple3(<movie1> <rating1> <numOfRaters1>),

Tuple3(<movie2> <rating2> <numOfRaters2>) ]
list = generateUniqueCombinations(value);

for (Tuple2( Tuple3(<movie1> <rating1> <numOfRaters1>),

Tuple3(<movie2> <rating2> <numOfRaters2>) pair : list) {

m1 = pair._1; // = Tuple3(<movie1> <rating1> <numOfRaters1>)
m2 = pair._2; // = Tuple3(<movie2> <rating2> <numOfRaters2>)

//define the reducer key
reducerKey = Tuple2(m1.movie, m2.movie);

// calculate additional information, which will be needed by correlation
int ratingProduct = m1.rating * m2.rating;
int rating1Squared = m1.rating * m1.rating;
int rating2Squared = m2.rating * m2.rating;

// define the reducer value
reducerValue = Tuple7(m1.rating,

m1.NumOfRaters,
m2.rating,
m2.NumOfRaters,
ratingProduct,
rating1Squared,
rating2Squared);

emit(reducerKey, reducerValue);

} // end-for-loop

35
36 }

Therefore, reducer will generate the following (key, value) pairs:

• Generated from key=User1:

KEY
<Movie1, Movie2>
<Movie1, Movie3>
<Movie2, Movie3>

Reducer Output
VALUE
<1 10 2 20
<1 10 3 30
<2 20 3 30

2
3
6

1
1
4

4>
9>
9>

• Generated from key=User2:

258

KEY
<Movie1, Movie2>
<Movie1, Movie3>
<Movie1, Movie5>
<Movie2, Movie3>
<Movie2, Movie5>
<Movie3, Movie5>

Reducer Output
VALUE
<2 10 3 20
<2 10 4 30
<2 10 5 50
<3 20 4 30
<3 20 5 50
<4 30 5 50

4
9>
6
4 16>
8
4 25>
10
9 16>
12
15
9 25>
20 16 25>

10.6 MapReduce-Phase-3 Mapper

The mapper is an identity mapper. The map() will accept (key, value) input
pairs as:

key: Tuple2(<movie1>, <movie2>)

value: Tuple7(<rating1>,

<numOfRaters1>,
<rating2>,
<numOfRaters2>,
<ratingProduct>,
<rating1Squared>,
<rating2Squared>

)

The mapper is an identity mapper. It just emits (key, value) as received.

Here is the deﬁnition of map() function:

Listing 10.5: Mapper PHASE-3

Tuple2(<movie1>, <movie2>) and generated by reducer of phase 2

1 // key is
2 // value = Tuple7(<rating1> <numOfRaters1> <rating2> <numOfRaters2>
3 //
4 map(key, value) {
5
6 }

<ratingProduct> <rating1Squared> <rating2Squared>)

emit(key, value);

The mapper will generate the following for our sample input (used as an

input to reducer of phase 3):

259

KEY
<Movie1, Movie2>
<Movie1, Movie3>
<Movie2, Movie3>
<Movie1, Movie2>
<Movie1, Movie3>
<Movie1, Movie5>
<Movie2, Movie3>
<Movie2, Movie5>
<Movie3, Movie5>

Mapper Output
VALUE
<1 10 2 20
<1 10 3 30
<2 20 3 30
<2 10 3 20
<2 10 4 30
<2 10 5 50
<3 20 4 30
<3 20 5 50
<4 30 5 50

4>
1
2
9>
1
3
9>
4
6
4
9>
6
4 16>
8
4 25>
10
9 16>
12
15
9 25>
20 16 25>

10.7 MapReduce-Phase-3 Reducer

The reduce() will accept (<movie1>, <movie2>) as a key and list of Tu-
ple7 (< rating1 >< numOf Raters1 >, < rating2 >< numOf Raters2 ><
ratingP roduct >< rating1Squared >< rating2Squared >) and will emit
correlation of every two related movies.
So the input for reducer will be:

Reducer Input

KEY
<Movie1, Movie2>

<Movie1, Movie3>

<Movie2, Movie3>

<Movie1, Movie5>
<Movie2, Movie5>
<Movie3, Movie5>

VALUE
[<1 10 2 20
<2 10 3 20
[<1 10 3 30
<2 10 4 30
[<2 20 3 30
<3 20 4 30
<2 10 5 50
<3 20 5 50
<4 30 5 50

6

8

2

3

6

1

4

1

4>,

9>]

9>,

4 16>]

4

9>,

9 16>]
12
4 25>
10
15
9 25>
20 16 25>

Following is the deﬁnition of reduce(). Recall that we can write the Pearson
correlation in the following form:

260

correlation(X, Y ) =

b

n (cid:80) xy − (cid:80) x (cid:80) y
b

n (cid:80) x2 − p (cid:80) xq2

n (cid:80) y2 − p (cid:80) yq2

This correlation is ”Pearson product-moment correlation coeﬃcient” [?].

Listing 10.6: Reducer PHASE-3

Tuple2(<movie1, movie2>)

1 // key is
2 // values = List{ Tuple7(<rating1>
3 //
4 //
5 //
6 //
7 //
8 //
9 // }
10 reduce(key, value) {
11

<numOfRaters1>
<rating2>
<numOfRaters2>
<ratingProduct>
<rating1Squared>
<rating2Squared>)

// calculate additional information, which will be needed by correlation
int groupSize = value.size(); // length of each vector
int dotProduct = 0; // sum of ratingProd
int rating1Sum = 0; // sum of rating1
int rating2Sum = 0; // sum of rating2
int rating1NormSq = 0; // sum of rating1Squared
int rating2NormSq = 0; // sum of rating2Squared
int maxNumOfumRaters1 = 0; // max of numOfRaters1
int maxNumOfumRaters2 = 0; // max of numOfRaters2
for (Tuple7(<rating1>

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

<numOfRaters1>
<rating2>
<numOfRaters2>
<ratingProduct>
<rating1Squared>
<rating2Squared>) : values) {

dotProduct += ratingProd;
rating1Sum += rating1;
rating2Sum += rating2;
rating1NormSq += rating1Squared;
rating2NormSq += rating2Squared;
if (numOfRaters1 > maxNumOfumRaters1) {
maxNumOfumRaters1 = numOfRaters1;

}
if (numOfRaters2 > maxNumOfumRaters2) {
maxNumOfumRaters2 = numOfRaters2;

}

}

double pearson = calculatePearsonCorrelation(

groupSize,
dotProduct,
rating1Sum,
rating2Sum,

261

45

46

47

48

49

50
51 }

rating1NormSq,
rating2NormSq);

double cosine = calculateCosineCorrelation(dotProduct, Math.sqrt(rating1NormSq), Math.sqrt(rating2NormSq));
double jaccard = calculateJaccardCorrelation(groupSize, maxNumOfumRaters1, maxNumOfumRaters2);
return Tuple3(pearson, cosine, jaccard);

The deﬁnition of correlation() function is given below:

Listing 10.7: Pearson Correlation Function

1 double calculatePearsonCorrelation
2

(double size,

double dotProduct,
double rating1Sum,
double rating2Sum,
double rating1NormSq,
double rating2NormSq)

{

double numerator = size * dotProduct - rating1Sum * rating2Sum;
double denominator =

math.sqrt(size * rating1NormSq - rating1Sum * rating1Sum) *
math.sqrt(size * rating2NormSq - rating2Sum * rating2Sum);

return numerator / denominator;

3

4

5

6

7

8

9

10

11

12

13
14 }

Therefore, reducer will generate similarities of every two movies:

<Movie1, Movie2> pearson1, cosine1, jaccard1
<Movie1, Movie3> pearson2, cosine2, jaccard2
<Movie2, Movie3> pearson3, cosine3, jaccard3
<Movie1, Movie2> pearson4, cosine4, jaccard4
<Movie1, Movie3> pearson5, cosine5, jaccard5
<Movie1, Movie5> pearson6, cosine6, jaccard6
<Movie2, Movie3> pearson7, cosine7, jaccard7
<Movie2, Movie5> pearson8, cosine8, jaccard8
<Movie3, Movie5> pearson9, cosine9, jaccard9

10.8 More Similarity Measures

Note that for the correlation calculation, we used ”Pearson product-moment
correlation coeﬃcient” [?]. We may use other formulas to calculate corre-
lation. Of course, there are lots of other similarity measures we could use

262

besides correlation. For example, we may use Cosine Similarity, which is a
another common vector-based similarity measure and deﬁned as:

Listing 10.1: Cosine Similarity
double calculateCosineCorrelation

(double dotProduct,
double rating1Norm,
double rating2Norm) {

return dotProduct / (rating1Norm * rating2Norm)

}

There are other Correlations or Similarity Measures:

• Regularized Correlation

• Jaccard Similarity

• Cosine Similarity

• Euclidean Distance

• Manhattan Distance

Selecting Correlations or Similarity Measures algorithm is domain/prob-
lem speciﬁc. You do need to investigate to see which algorithm gives you
better (pragmatic optimal) answers.

10.9 Movie Recommendation in Spark

This section presents Spark implementation for the 3 phases of MapReduce
algorithms provided in earlier sections of this chapter. The entire Spark solu-
tion is written in a single Java driver class called MovieRecommendationsWithJoin.
The following are presented for Spark implementation:

• First, we present all high-level steps

• Second, each step is presented in detail with complete Spark code in

Java.

• Finally, a sample run is provided using Spark-1.0.0

263

10.9.1 High-Level Solution in Spark

The solution in Spark is presented in 12 steps, which use RDDs. Spark’s
primary data abstraction and programming model is based on RDDs. In a
nutshell, Resilient distributed datasets (RDDs) are immutable data struc-
tures, which have the following properties:

• Created from HDFS ﬁles or ”parallelized” arrays

• Can be transformed with map() and filter

• Can be cached across parallel operations such as reduce, collect, and

foreach.

10.9.2 High-Level Solution: All Steps

The driver class,MovieRecommendationsWithJoin, is presented below.

Listing 10.8: High-Level Solution: All Steps

1 //STEP-0: import required classes and interfaces
2 public class MovieRecommendationsWithJoin {
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

public static void main(String[] args) throws Exception {

note that (movie1, movie2) and (movie2, movie1) are the same

joinedRDD = usersRDD.join(usersRDD);
joinedRDD = (user, T2((m1,r1,n1), (m2,r2,n2)) )

//STEP-1: handle input parameters
//STEP-2: create a Spark’s context object
//STEP-3: read HDFS file and create the first RDD
//STEP-4: find who has seen and rated this movie
//STEP-5: group moviesRDD by movie
//STEP-6: find number of raters per movie and then create (K,V) pairs as
usersRDD = <K=user, V=<movie,rating,numberOfRaters>>
//
//STEP-7: join usersRDD against itself to find all (movie1, movie2) pairs
//
//
//STEP-8: remove duplicate (movie1, movie2) pairs.
//
//STEP-9: generate all (movie1, movie2) combinations
// The goal of this step is to create (K,V) pairs of
//
//
//
//
//
//
//
//
//
//STEP-10: group moviePairs by key(movie1,movie2)
//STEP-11: calculate correlation/similarities between every (movie1,movie2)
//STEP-12: print final results

movie1.numOfRaters,
movie2.rating,
movie2.numOfRaters,
ratingProduct,
rating1Squared, = movie1.rating * movie1.rating
= movie2.rating * movie2.rating
rating2Squared

K: Tuple2(movie1, movie2)
V: Tuple7(movie1.rating,

)

264

System.exit(0);

}

static Tuple3<Double,Double,Double> calculateCorrelations(...);
static double calculatePearsonCorrelation(...);
static double calculateCosineCorrelation(...);
static double calculateJaccardCorrelation(...);

31

32

33

34

35

36

37
38 }

10.9.3 STEP-0: Import Required Classes

Most of the classes and interfaces we need are included in the following two
packages: org.apache.spark.api.java and org.apache.spark.api.java.function.

Listing 10.9: STEP-0: Import Required Classes

1 //STEP-0: import required classes and interfaces
2 import scala.Tuple2;
3 import java.util.List;
4 import java.util.ArrayList;
5 import org.apache.spark.api.java.JavaRDD;
6 import org.apache.spark.api.java.JavaPairRDD;
7 import org.apache.spark.api.java.JavaSparkContext;
8 import org.apache.spark.api.java.function.Function;
9 import org.apache.spark.api.java.function.PairFlatMapFunction;
10 import org.apache.spark.api.java.function.FlatMapFunction;
11 import org.apache.spark.api.java.function.PairFunction;

10.9.4 STEP-1: Handle Input Parameters

Two parameters are needed to run the Spark program: ”spark master URL”
and ”HDFS input ﬁle”. The ”spark master URL” will be used to create a
JavaSparkContext object.

Listing 10.10: STEP-1: Handle Input Parameters

//STEP-1: handle input parameters
if (args.length < 2) {

System.err.println("Usage: MovieRecommendationsWithJoin <master> <users-ratings>");
System.exit(1);

}

String sparkMaster = args[0];
String usersRatingsInputFile = args[1];
System.out.println("sparkMaster="+ sparkMaster);
System.out.println("usersRatingsInputFile="+ usersRatingsInputFile);

1

2

3

4

5

6

7

8

9

10

265

10.9.5 STEP-2: Create a Spark’s Context Object

This step creates a JavaSparkContext object that returns JavaRDDs and
works with Java collections. JavaSparkContext is a factory class, which
creates JavaRDD<T> and JavaPairRDD<K,V> objects.

Listing 10.11: STEP-2: Create a Spark’s Context Object

1 //STEP-2: create a Spark’s context object
2 JavaSparkContext ctx = new JavaSparkContext(
3

sparkMaster,
"MovieRecommendationsWithJoin",
System.getenv("SPARK_HOME"),
System.getenv("SPARK_EXAMPLES_JAR"));

4

5

6

10.9.6 STEP-3: Read Input File and Create RDD

Using a JavaSparkContext object we read an HDFS input text ﬁle and
create the ﬁrst JavaRDD<String> object (set of String type records) , which
represents the input ﬁle.

//STEP-3: read HDFS file and create the first RDD
JavaRDD<String> usersRatings = ctx.textFile(usersRatingsInputFile, 1);

After executing STEP-3, the usersRating RDD is a list of:

{

}

"user1 movie1 1",
"user1 movie2 2",
"user1 movie3 3",
"user2 movie1 1",
"user2 movie2 2"
"user2 movie3 3"
"user2 movie5 5"
...

266

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

10.9.7 STEP-4: Find Who Has Rated Movies

The usersRating RDD is an input to STEP-4. The three steps (STEP-4,
STEP-5, and STEP-6) ﬁnd the ”number of raters for every movie”. STEP-
4 implements a mapper: it accepts a single record (comprised of user, movie,
and rating) and create a (key,value) pair of (movie, (user,rating). JavaRDD.mapToPair()
accepts a single input record and creates a JavaPairRDD<K2,V2> where
K2=movie and V2=Tuple2(user,rating).

Listing 10.12: STEP-4: Find Who Has Rated Movies

//STEP-4: find who has seen this movie

// <K2,V2> JavaPairRDD<K2,V2> mapToPair(PairFunction<T,K2,V2> f)
// Return a new RDD by applying a function to all elements of this RDD.
// PairFunction<T, K2, V2>
// T => Tuple2<K2, V2>
// T = <user> <movie> <rating>
// K2 = <movie>
// V2 = Tuple2<user, rating>
JavaPairRDD<String,Tuple2<String,Integer>> moviesRDD =
K

V

T

//
usersRatings.mapToPair(new PairFunction<String, String, Tuple2<String,Integer>>() {
//

T

public Tuple2<String,Tuple2<String,Integer>> call(String s) {

String[] record = s.split("\t");
String user = record[0];
String movie = record[1];
Integer rating = new Integer(record[2]);
Tuple2<String,Integer> userAndRating = new Tuple2<String,Integer>(user, rating);

return new Tuple2<String,Tuple2<String,Integer>>(movie, userAndRating);

}
});

To debug STEP-4, we use JavaPairRDD.collect() method.

System.out.println("=== debug1: moviesRDD: K = <movie>, V = Tuple2<user, rating> ===");
List<

Tuple2<String,Tuple2<String,Integer>>

> debug1 = moviesRDD.collect();

for (Tuple2<String,Tuple2<String,Integer>> t2 : debug1) {

System.out.println("debug1 key="+t2._1 + "\t value="+t2._2);

}

After executing STEP-4, the moviesRDD is a list of (K,V) pairs:

{

267

((movie1, (user1, 1)),
((movie2, (user1, 2)),
((movie3, (user1, 3)),
((movie1, (user2, 1)),
((movie2, (user2, 2)),
((movie3, (user2, 3)),
((movie5, (user2, 5))
...

}

10.9.8 STEP-5: Group moviesRDD by Movie

STEP-4 created a JavaPairRDD<K2,V2> where K2=movie and V2=Tuple2(user,rating).
This step groups moviesRDD by its key. The result of this step will be:

JavaPairRDD<K,V>

where K=movie

V=List(Tuple2(user,rating))

This step is implemented by JavaPairRDD.groupByKey() method.

Listing 10.13: STEP-5: Group moviesRDD by Movie

1

2

3

4

5

6

7

8

9

//STEP-5: group moviesRDD by movie

JavaPairRDD<String, Iterable<Tuple2<String,Integer>>> moviesGrouped =

moviesRDD.groupByKey();

System.out.println("=== debug2: moviesGrouped: K = <movie>, V = Iterable<Tuple2<user, rating>> ===");
List<

Tuple2<String,Iterable<Tuple2<String,Integer>>>

> debug2 = moviesGrouped.collect();

for (Tuple2<String,Iterable<Tuple2<String,Integer>>> t2 : debug2) {

System.out.println("debug2 key="+t2._1 + "\t value="+t2._2);

10

}

After executing STEP-5, the moviesGrouped is a list of the following
(K,V) pairs. Clearly, we can count the number of raters (which is the size of
list value per movie) for each movie.

{

(movie1, [(user1, 1), (user2, 1), ...]),
(movie2, [(user1, 2), (user2, 2), ...]),

268

(movie3, [(user1, 3), (user2, 3), ...]),
(movie5, [(user2, 5), ...])
...

}

10.9.9 STEP-6: Find Number of Raters per Movie

This steps tallys the raters for each movie and generates another JavaPairRDD<K,V>
where K=user and V=Tuple3(movie, rating, numberOfRaters). This step
is implemented by JavaPairRDD.flatMapToPair() method.

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

Listing 10.14: STEP-6: Find Number of Raters per Movie

//STEP-6: find number of raters per movie and then create (K,V) pairs as
//
//
//

K = user
V = Tuple3<movie, rating, numberOfRaters>

// PairFlatMapFunction<T, K, V>
// T => Iterable<Tuple2<K, V>>
JavaPairRDD<String,Tuple3<String,Integer,Integer>> usersRDD =
moviesGrouped.flatMapToPair(new PairFlatMapFunction<

Tuple2<String, Iterable<Tuple2<String,Integer>>>, // T
// K
String,
// V
Tuple3<String,Integer,Integer>>() {

public Iterable<Tuple2<String,Tuple3<String,Integer,Integer>>>

call(Tuple2<String, Iterable<Tuple2<String,Integer>>> s) {
List<Tuple2<String,Integer>> listOfUsersAndRatings =

new ArrayList<Tuple2<String,Integer>>();

// now read inputs and generate desired (K,V) pairs
String movie = s._1;
Iterable<Tuple2<String,Integer>> pairsOfUserAndRating = s._2;
int numberOfRaters = 0;
for (Tuple2<String,Integer> t2 : pairsOfUserAndRating) {

numberOfRaters++;
listOfUsersAndRatings.add(t2);

}

// now emit (K, V) pairs
List<Tuple2<String,Tuple3<String,Integer,Integer>>> results =

new ArrayList<Tuple2<String,Tuple3<String,Integer,Integer>>>();

for (Tuple2<String,Integer> t2 : listOfUsersAndRatings) {

String user = t2._1;
Integer rating = t2._2;
Tuple3<String,Integer,Integer> t3 =

new Tuple3<String,Integer,Integer>(movie, rating, numberOfRaters);

results.add(new Tuple2<String, Tuple3<String,Integer,Integer>>(user, t3));

}
return results;

}
});

269

To debug STEP-6, we use JavaPairRDD.collect() method.

System.out.println("=== debug3: moviesGrouped: K = user, "+

"V = Tuple3<movie, rating, numberOfRaters>

===");

List<

Tuple2<String,Tuple3<String,Integer,Integer>>

> debug3 = usersRDD.collect();

for (Tuple2<String,Tuple3<String,Integer,Integer>> t2 : debug3) {
System.out.println("debug3 key="+t2._1 + "\t value="+t2._2);

}

After executing STEP-6, the usersRDD is a list of the following (K,V) pairs,
which includer the number of raters per movie. Here K=user and V=(movie,
rating, numberOfRatters).

{

}

(user1, (movie1, 1, 2)),
(user1, (movie2, 2, 2))
(user1, (movie3, 3, 2)),
(user2, (movie1, 1, 2)),
(user2, (movie2, 2, 2)),
(user2, (movie3, 3, 2)),
(user2, (movie5, 5, 1)),
...

10.9.10 STEP-7: Perform Self-Join

This step uses a very powerful feature of Spark API: the join operation.
Self-join is persormed on usersRDD as (the join will be done on the ”user”
key):

joinedRDD = usersRDD.join(usersRDD);

where botth usersRDD and joinedRDD are JavaRDD types. The signature of
join() is given as:

270

public <W> JavaPairRDD<K,scala.Tuple2<V,W>> join(JavaPairRDD<K,W> other)
Description: Return an RDD containing all pairs of elements with matching

keys in this and other. Each pair of elements will be returned
as a (k, (v1, v2)) tuple, where (k, v1) is in this and (k, v2)
is in other. Performs a hash join across the cluster.

Here is the self-join (self-join is needed to ﬁnd combinations of (movie1,
movie2)) implementation by JavaPairRDD.join(JavaPairRDD):

Listing 10.15: STEP-7: Perform Self-Join

1

2

3

4

5

6

7

8

9

10

11

12

//STEP-7: join usersRDD against itself to find all (movie1, movie2) pairs
// usersRDD = <K=user, V=<movie,rating,numberOfRaters>>
// the result will be joinedRDD = (user, T2((m1,r1,n1), (m2,r2,n2)) )
// the join will be done on the "user" key
JavaPairRDD<String, Tuple2<Tuple3<String,Integer,Integer>,Tuple3<String,Integer,Integer>>>

joinedRDD = usersRDD.join(usersRDD);

List<

Tuple2<String, Tuple2<Tuple3<String,Integer,Integer>,Tuple3<String,Integer,Integer>>>

> debug5 = joinedRDD.collect();

for (Tuple2<String, Tuple2<Tuple3<String,Integer,Integer>,Tuple3<String,Integer,Integer>>> t2 : debug5) {

System.out.println("debug5 key="+t2._1 + "\t value="+t2._2);

}

After executing STEP-7, the joinedRDD is a list of the following (K,V)

pairs:

{

}

(user1, [(movie1, 1, 2), (movie2, 2, 2)]),
(user1, [(movie1, 1, 2), (movie3, 3, 2)]),
(user1, [(movie2, 2, 2), (movie1, 1, 2)]),
(user1, [(movie2, 2, 2), (movie3, 3, 2)]),
(user1, [(movie3, 3, 2), (movie1, 1, 2)]),
(user1, [(movie3, 3, 2), (movie2, 2, 2)]),
...

As you can see for each K=user, we have duplicate movie pairs (note that,
(movie1, movie2) is the same as (movie2, movie1) pairs). The next step will
remove duplicates by filter API.

271

10.9.11 STEP-8: Remove Duplicate (movie1, movie2)

Pairs

In previous step, STEP-7, we generated (movie1, movie2) combinations pairs,
which have duplicates. This step removes duplicates by using JavaPairRDD.filter()
method. The filter() method is deﬁned as:

public JavaPairRDD<K,V> filter(Function<scala.Tuple2<K,V>,Boolean> f)
Description: Return a new RDD containing only the

elements that satisfy a predicate.

Filter implementation is provided below. The filter() function only keeps
(movie1, movie2) pairs if movie1 < movie2 (this is the predicate the we
implemented below):

Listing 10.16: STEP-8: Remove Duplicate (movie1, movie2) Pairs

//STEP-8: remove duplicate (movie1, movie2) pairs.
// note that (movie1, movie2) and (movie2, movie1) are the same

// now we have: filteredRDD = (user, T2((m1,r1,n1), (m2,r2,n2)) ) where m1 < m2
// to guarntee that we will not have duplicate movie pais per user
JavaPairRDD<String, Tuple2<Tuple3<String,Integer,Integer>,Tuple3<String,Integer,Integer>>>

filteredRDD = joinedRDD.filter(new Function<

Tuple2<String,Tuple2<Tuple3<String,Integer,Integer>,Tuple3<String,Integer,Integer>>>,
Boolean

>() {

public Boolean call(Tuple2<String,

Tuple2<Tuple3<String,Integer,Integer>,Tuple3<String,Integer,Integer>>> s) {

// to remove duplicates, make sure that movie1 < movie2 for all (movie1, movie2) pairs
Tuple3<String,Integer,Integer> movie1 = s._2._1;
Tuple3<String,Integer,Integer> movie2 = s._2._2;
String movieName1 = movie1.first();
String movieName2 = movie2.first();
if (movieName1.compareTo(movieName2) < 0) {

return true;

}
else {

return false;

}

}
});

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

To debug STEP-8, we use JavaPairRDD.collect() method.

List<

Tuple2<String, Tuple2<Tuple3<String,Integer,Integer>,Tuple3<String,Integer,Integer>>>

272

> debug55 = filteredRDD.collect();

for (Tuple2<String, Tuple2<Tuple3<String,Integer,Integer>,Tuple3<String,Integer,Integer>>> t2 : debug55) {

System.out.println("debug55 key="+t2._1 + "\t value="+t2._2);

}

After executing STEP-8, the filteredRDD is a list of the following (K,V)
pairs (without duplicates):

{

}

(user1, [(movie1, 1, 2), (movie2, 2, 2)]),
(user1, [(movie1, 1, 2), (movie3, 3, 2)]),
(user1, [(movie2, 2, 2), (movie3, 3, 2)]),
...

10.9.12 STEP-9: Generate All (movie1, movie2) Com-

binations

For each (movie1, movie2) pair, this step creates some derived data, which
will be used for calculating three correlation algorithms (Pearson, Cosine,
Jaccard). This is achieved by another transformation by using JavaPairRDD.mapToPair().

Listing 10.17: STEP-9: Generate All (movie1, movie2) Combinations

K: Tuple2(movie1, movie2)
V: Tuple7(movie1.rating,

//STEP-9: generate all (movie1, movie2) combinations
// The goal of this step is to create (K,V) pairs of
//
//
//
//
//
//
//
//
//

movie1.numOfRaters,
movie2.rating,
movie2.numOfRaters,
ratingProduct,
rating1Squared, = movie1.rating * movie1.rating
rating2Squared = movie2.rating * movie2.rating

)

// PairFunction<T, K, V>
// T => Tuple2<K, V>
// user attribute will be dropped at this phase.
//

V

K

JavaPairRDD<Tuple2<String,String>, Tuple7<Integer,Integer,Integer,Integer,Integer,Integer,Integer>>

moviePairs = filteredRDD.mapToPair(new PairFunction

<Tuple2<String,Tuple2<Tuple3<String,Integer,Integer>,Tuple3<String,Integer,Integer>>>,

// T

Tuple2<String,String>,
// K
Tuple7<Integer,Integer,Integer,Integer,Integer,Integer,Integer> // V

273

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

>() {

public Tuple2<Tuple2<String,String>, Tuple7<Integer,Integer,Integer,Integer,Integer,Integer,Integer>>

call(Tuple2<String,Tuple2<Tuple3<String,Integer,Integer>,Tuple3<String,Integer,Integer>>> s) {

// String user = s._1; // will be dropped
Tuple3<String,Integer,Integer> movie1 = s._2._1;
Tuple3<String,Integer,Integer> movie2 = s._2._2;
Tuple2<String,String> m1m2Key = new Tuple2<String,String>(movie1.first(), movie2.first());
int ratingProduct = movie1.second() * movie2.second();
// movie1.rating * movie2.rating;
int rating1Squared = movie1.second() * movie1.second(); // movie1.rating * movie1.rating;
int rating2Squared = movie2.second() * movie2.second(); // movie2.rating * movie2.rating;
Tuple7<Integer,Integer,Integer,Integer,Integer,Integer,Integer> t7 =

new Tuple7<Integer,Integer,Integer,Integer,Integer,Integer,Integer>(

movie1.second(), // movie1.rating,
movie1.third(),
movie2.second(), // movie2.rating,
movie2.third(),
ratingProduct,
rating1Squared,
rating2Squared);

// movie1.numberOfRaters,

// movie2.numberOfRaters,

return new Tuple2<Tuple2<String,String>,Tuple7<Integer,Integer,Integer,Integer,Integer,Integer,Integer>>(m1m2Key, t7);

}

});

10.9.13 STEP-10: Group Movie Pairs

This step groups data by movie pairs: (movie1, movie2), which gather re-
quired data needed for computing correlations.

//STEP-10: group moviePairs by key(movie1,movie2)
JavaPairRDD< Tuple2<String,String>,

Iterable<Tuple7<Integer,Integer,Integer,Integer,Integer,Integer,Integer>>

> corrRDD = moviePairs.groupByKey();

10.9.14 STEP-11: Calculate Correlations

This step uses 3 diﬀerent correlation algorithms to ﬁnd similarities between
every pair of movies. There is no golden rule for selecting a correlation al-
gorithm for a speciﬁc application. You should select a correlation algorithm,
which ﬁts into your applicatin environment.

Listing 10.18: STEP-11: Calculate Correlations

1

2

3

//STEP-11: calculate correlation/similarities between every (movie1,movie2)
// coor.key = (movie1,movie2)
// corr.value= (pearson, cosine, jaccard) correlations

274

4

5

6

7

8

9

10

11

12

13

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

JavaPairRDD<Tuple2<String,String>, Tuple3<Double,Double,Double>> corr =

corrRDD.mapValues(new Function<

Iterable<Tuple7<Integer,Integer,Integer,Integer,Integer,Integer,Integer>>,
Tuple3<Double,Double,Double>

// input
// output

>() {

public Tuple3<Double,Double,Double> call(

Iterable<Tuple7<Integer,Integer,Integer,Integer,Integer,Integer,Integer>> s) {

return calculateCorrelations(s);

}
});

10.9.15 STEP-12: Print Final Results

//STEP-12: print final results
System.out.println("=== Movie Correlations ===");
List<

Tuple2< Tuple2<String,String>, Tuple3<Double,Double,Double>>

> debug6 = corr.collect();

for (Tuple2<Tuple2<String,String>, Tuple3<Double,Double,Double>> t2 : debug6) {

System.out.println("debug5 key="+t2._1 + "\t value="+t2._2);

}

corr.saveAsTextFile("/movies/output");

10.9.16 Helper Method: calculateCorrelations()

Listing 10.19: Helper Method: calculateCorrelations()

static Tuple3<Double,Double,Double> calculateCorrelations(

Iterable<Tuple7<Integer,Integer,Integer,Integer,Integer,Integer,Integer>> values) {
int groupSize = 0; // length of each vector
int dotProduct = 0; // sum of ratingProd
int rating1Sum = 0; // sum of rating1
int rating2Sum = 0; // sum of rating2
int rating1NormSq = 0; // sum of rating1Squared
int rating2NormSq = 0; // sum of rating2Squared
int maxNumOfumRaters1 = 0; // max of numOfRaters1
int maxNumOfumRaters2 = 0; // max of numOfRaters2
for (Tuple7<Integer,Integer,Integer,Integer,Integer,Integer,Integer> t7 : values) {

//Tuple7(<rating1>:
//
//
//
//

<numOfRaters1>:
<rating2>:
<numOfRaters2> :
<ratingProduct> :

t7._1
t7._2
t7._3
t7._4
t7._5

275

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

//
//

<rating1Squared> : t7._6
<rating2Squared>): t7._7

groupSize++;
dotProduct += t7._5; // ratingProduct;
rating1Sum += t7._1; // rating1;
rating2Sum += t7._3; // rating2;
rating1NormSq += t7._6; // rating1Squared;
rating2NormSq += t7._7; // rating2Squared;
int numOfRaters1 = t7._2;
if (numOfRaters1 > maxNumOfumRaters1) {
maxNumOfumRaters1 = numOfRaters1;

}
int numOfRaters2 = t7._4;
if (numOfRaters2 > maxNumOfumRaters2) {
maxNumOfumRaters2 = numOfRaters2;

}

}

double pearson = calculatePearsonCorrelation(

groupSize,
dotProduct,
rating1Sum,
rating2Sum,
rating1NormSq,
rating2NormSq);

double cosine = calculateCosineCorrelation(dotProduct, Math.sqrt(rating1NormSq), Math.sqrt(rating2NormSq));

double jaccard = calculateJaccardCorrelation(groupSize, maxNumOfumRaters1, maxNumOfumRaters2);

return new Tuple3<Double,Double,Double>(pearson, cosine, jaccard);

}

10.9.17 Helper Method: calculatePearsonCorrelation()

Listing 10.20: Helper Method: calculateCorrelations()

static double calculatePearsonCorrelation(

double size,
double dotProduct,
double rating1Sum,
double rating2Sum,
double rating1NormSq,
double rating2NormSq)

{

double numerator = size * dotProduct - rating1Sum * rating2Sum;
double denominator =

Math.sqrt(size * rating1NormSq - rating1Sum * rating1Sum) *
Math.sqrt(size * rating2NormSq - rating2Sum * rating2Sum);

return numerator / denominator;

}

276

10.9.18 Helper Method: calculateCosineCorrelation()

Listing 10.21: Helper Method: calculateCosineCorrelation()

/**

* The cosine similarity between two vectors A, B is
*
*/

dotProduct(A, B) / (norm(A) * norm(B))

static double calculateCosineCorrelation(double dotProduct,

double rating1Norm,
double rating2Norm) {

return dotProduct / (rating1Norm * rating2Norm);

}

10.9.19 Helper Method: calculateJaccardCorrelation()

Listing 10.22: Helper Method: calculateJaccardCorrelation()

/**

* The Jaccard Similarity between two sets A, B is
*
*/

|Intersection(A, B)| / |Union(A, B)|

static double calculateJaccardCorrelation(double inCommon,

double totalA,
double totalB) {

double union = totalA + totalB - inCommon;
return inCommon / union;

1

2

3

4

5

6

7

8

9

1

2

3

4

5

6

7

8

9

10

}

10.10 Sample Run of Spark Program

10.10.1 HDFS Input

To refresh, we assume that our input data is stored in HDFS as a text ﬁle

# hadoop fs -cat /movies.txt
User1
User1

Movie1
Movie2

3
4

277

User1
User2
User2
User2
User2
User3
User3
User3
User4
User4
User4
User4
User4

Movie3
Movie1
Movie2
Movie3
Movie5
Movie1
Movie2
Movie3
Movie1
Movie2
Movie3
Movie4
Movie5

3
2
5
3
5
2
3
2
5
3
3
2
3

10.10.2 Script

# cat run_movies.sh
#!/bin/bash
source /home/hadoop/conf/env_2.3.0.sh
export SPARK_HOME=/home/hadoop/spark-1.0.0
source /home/hadoop/spark_mahmoud_examples/spark_env_yarn.sh
source $SPARK_HOME/conf/spark-env.sh

# system jars:
CLASSPATH=$CLASSPATH:$HADOOP_HOME/etc/hadoop

jars=‘find $SPARK_HOME -name ’*.jar’‘
for j in $jars ; do

CLASSPATH=$CLASSPATH:$j

done

# app jar:
export CLASSPATH=/home/hadoop/spark_mahmoud_examples/mp.jar:$CLASSPATH
export SPARK_CLASSPATH=$CLASSPATH
export SPARK_MASTER=spark://hnode01319.nextbiosystem.net:7077
MOVIES=/movies.txt
OPTIONS="-Dsun.lang.ClassLoader.allowArraySyntax=true -Dspark.master=$SPARK_MASTER"
$JAVA_HOME/bin/java -cp $CLASSPATH $OPTIONS MovieRecommendationsWithJoin $SPARK_MASTER $MOVIES

278

10.11 Log of Sample Run

The actual output is edited to ﬁt the page.

# ./run_movies.sh
sparkMaster=spark://hnode01319.nextbiosystem.net:7077
usersRatingsInputFile=/movies.txt
...
14/06/07 23:18:13 INFO scheduler.DAGScheduler: Stage 0

(collect at MovieRecommendationsWithJoin.java:73) finished in 4.199 s

14/06/07 23:18:13 INFO spark.SparkContext: Job finished: collect at

MovieRecommendationsWithJoin.java:73, took 4.290270699 s

debug1 key=Movie1
debug1 key=Movie2
debug1 key=Movie3
debug1 key=Movie1
debug1 key=Movie2
debug1 key=Movie3
debug1 key=Movie5
debug1 key=Movie1
debug1 key=Movie2
debug1 key=Movie3
debug1 key=Movie1
debug1 key=Movie2
debug1 key=Movie3
debug1 key=Movie4
debug1 key=Movie5
=== debug2: moviesGrouped: K = <movie>, V = Iterable<Tuple2<user, rating>> ===
14/06/07 23:18:13 INFO spark.SparkContext: Starting job: collect at

value=(User1,3)
value=(User1,4)
value=(User1,3)
value=(User2,2)
value=(User2,5)
value=(User2,3)
value=(User2,5)
value=(User3,2)
value=(User3,3)
value=(User3,2)
value=(User4,5)
value=(User4,3)
value=(User4,3)
value=(User4,2)
value=(User4,3)

MovieRecommendationsWithJoin.java:85

14/06/07 23:18:13 INFO scheduler.DAGScheduler: Registering RDD 2

(mapToPair at MovieRecommendationsWithJoin.java:56)

...
14/06/07 23:18:13 INFO scheduler.DAGScheduler: Stage 1

(collect at MovieRecommendationsWithJoin.java:85) finished in 0.752 s

14/06/07 23:18:13 INFO spark.SparkContext: Job finished: collect at

MovieRecommendationsWithJoin.java:85, took 0.833602896 s

debug2 key=Movie2

value=[(User1,4), (User2,5), (User3,3), (User4,3)]

279

value=[(User2,5), (User4,3)]
value=[(User4,2)]
value=[(User1,3), (User2,3), (User3,2), (User4,3)]
value=[(User1,3), (User2,2), (User3,2), (User4,5)]

debug2 key=Movie5
debug2 key=Movie4
debug2 key=Movie3
debug2 key=Movie1
=== debug3: moviesGrouped: K = user,
14/06/07 23:18:13 INFO spark.SparkContext: Starting job: collect at
..MovieRecommendationsWithJoin.java:126
...
14/06/07 23:18:14 INFO scheduler.DAGScheduler: Stage 3

V = Tuple3<movie, rating, numberOfRaters>

===

(collect at MovieRecommendationsWithJoin.java:126) finished in 0.141 s

14/06/07 23:18:14 INFO spark.SparkContext: Job finished:

collect at MovieRecommendationsWithJoin.java:126, took 0.159691236 s

value=Tuple3[Movie2,4,4]
debug3 key=User1
value=Tuple3[Movie2,5,4]
debug3 key=User2
value=Tuple3[Movie2,3,4]
debug3 key=User3
value=Tuple3[Movie2,3,4]
debug3 key=User4
value=Tuple3[Movie5,5,2]
debug3 key=User2
value=Tuple3[Movie5,3,2]
debug3 key=User4
value=Tuple3[Movie4,2,1]
debug3 key=User4
value=Tuple3[Movie3,3,4]
debug3 key=User1
value=Tuple3[Movie3,3,4]
debug3 key=User2
value=Tuple3[Movie3,2,4]
debug3 key=User3
value=Tuple3[Movie3,3,4]
debug3 key=User4
value=Tuple3[Movie1,3,4]
debug3 key=User1
value=Tuple3[Movie1,2,4]
debug3 key=User2
value=Tuple3[Movie1,2,4]
debug3 key=User3
debug3 key=User4
value=Tuple3[Movie1,5,4]
14/06/07 23:18:14 INFO spark.SparkContext: Starting job: collect

at MovieRecommendationsWithJoin.java:142

...
14/06/07 23:18:15 INFO scheduler.DAGScheduler: Stage 5 (collect at

MovieRecommendationsWithJoin.java:142) finished in 0.728 s

14/06/07 23:18:15 INFO spark.SparkContext: Job finished: collect at

MovieRecommendationsWithJoin.java:142, took 0.846712724 s

debug5 key=User3
debug5 key=User3
debug5 key=User3
debug5 key=User3

value=(Tuple3[Movie2,3,4],Tuple3[Movie2,3,4])
value=(Tuple3[Movie2,3,4],Tuple3[Movie3,2,4])
value=(Tuple3[Movie2,3,4],Tuple3[Movie1,2,4])
value=(Tuple3[Movie3,2,4],Tuple3[Movie2,3,4])

280

debug5 key=User3
debug5 key=User3
debug5 key=User3
debug5 key=User3
debug5 key=User3
debug5 key=User2
debug5 key=User2
debug5 key=User2
debug5 key=User2
debug5 key=User2
debug5 key=User2
debug5 key=User2
debug5 key=User2
debug5 key=User2
debug5 key=User2
debug5 key=User2
debug5 key=User2
debug5 key=User2
debug5 key=User2
debug5 key=User2
debug5 key=User2
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4

value=(Tuple3[Movie3,2,4],Tuple3[Movie3,2,4])
value=(Tuple3[Movie3,2,4],Tuple3[Movie1,2,4])
value=(Tuple3[Movie1,2,4],Tuple3[Movie2,3,4])
value=(Tuple3[Movie1,2,4],Tuple3[Movie3,2,4])
value=(Tuple3[Movie1,2,4],Tuple3[Movie1,2,4])
value=(Tuple3[Movie2,5,4],Tuple3[Movie2,5,4])
value=(Tuple3[Movie2,5,4],Tuple3[Movie5,5,2])
value=(Tuple3[Movie2,5,4],Tuple3[Movie3,3,4])
value=(Tuple3[Movie2,5,4],Tuple3[Movie1,2,4])
value=(Tuple3[Movie5,5,2],Tuple3[Movie2,5,4])
value=(Tuple3[Movie5,5,2],Tuple3[Movie5,5,2])
value=(Tuple3[Movie5,5,2],Tuple3[Movie3,3,4])
value=(Tuple3[Movie5,5,2],Tuple3[Movie1,2,4])
value=(Tuple3[Movie3,3,4],Tuple3[Movie2,5,4])
value=(Tuple3[Movie3,3,4],Tuple3[Movie5,5,2])
value=(Tuple3[Movie3,3,4],Tuple3[Movie3,3,4])
value=(Tuple3[Movie3,3,4],Tuple3[Movie1,2,4])
value=(Tuple3[Movie1,2,4],Tuple3[Movie2,5,4])
value=(Tuple3[Movie1,2,4],Tuple3[Movie5,5,2])
value=(Tuple3[Movie1,2,4],Tuple3[Movie3,3,4])
value=(Tuple3[Movie1,2,4],Tuple3[Movie1,2,4])
value=(Tuple3[Movie2,3,4],Tuple3[Movie2,3,4])
value=(Tuple3[Movie2,3,4],Tuple3[Movie5,3,2])
value=(Tuple3[Movie2,3,4],Tuple3[Movie4,2,1])
value=(Tuple3[Movie2,3,4],Tuple3[Movie3,3,4])
value=(Tuple3[Movie2,3,4],Tuple3[Movie1,5,4])
value=(Tuple3[Movie5,3,2],Tuple3[Movie2,3,4])
value=(Tuple3[Movie5,3,2],Tuple3[Movie5,3,2])
value=(Tuple3[Movie5,3,2],Tuple3[Movie4,2,1])
value=(Tuple3[Movie5,3,2],Tuple3[Movie3,3,4])
value=(Tuple3[Movie5,3,2],Tuple3[Movie1,5,4])
value=(Tuple3[Movie4,2,1],Tuple3[Movie2,3,4])
value=(Tuple3[Movie4,2,1],Tuple3[Movie5,3,2])
value=(Tuple3[Movie4,2,1],Tuple3[Movie4,2,1])
value=(Tuple3[Movie4,2,1],Tuple3[Movie3,3,4])
value=(Tuple3[Movie4,2,1],Tuple3[Movie1,5,4])
value=(Tuple3[Movie3,3,4],Tuple3[Movie2,3,4])
value=(Tuple3[Movie3,3,4],Tuple3[Movie5,3,2])

281

debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User4
debug5 key=User1
debug5 key=User1
debug5 key=User1
debug5 key=User1
debug5 key=User1
debug5 key=User1
debug5 key=User1
debug5 key=User1
debug5 key=User1
14/06/07 23:18:15 INFO spark.SparkContext: Starting job: collect at

value=(Tuple3[Movie3,3,4],Tuple3[Movie4,2,1])
value=(Tuple3[Movie3,3,4],Tuple3[Movie3,3,4])
value=(Tuple3[Movie3,3,4],Tuple3[Movie1,5,4])
value=(Tuple3[Movie1,5,4],Tuple3[Movie2,3,4])
value=(Tuple3[Movie1,5,4],Tuple3[Movie5,3,2])
value=(Tuple3[Movie1,5,4],Tuple3[Movie4,2,1])
value=(Tuple3[Movie1,5,4],Tuple3[Movie3,3,4])
value=(Tuple3[Movie1,5,4],Tuple3[Movie1,5,4])
value=(Tuple3[Movie2,4,4],Tuple3[Movie2,4,4])
value=(Tuple3[Movie2,4,4],Tuple3[Movie3,3,4])
value=(Tuple3[Movie2,4,4],Tuple3[Movie1,3,4])
value=(Tuple3[Movie3,3,4],Tuple3[Movie2,4,4])
value=(Tuple3[Movie3,3,4],Tuple3[Movie3,3,4])
value=(Tuple3[Movie3,3,4],Tuple3[Movie1,3,4])
value=(Tuple3[Movie1,3,4],Tuple3[Movie2,4,4])
value=(Tuple3[Movie1,3,4],Tuple3[Movie3,3,4])
value=(Tuple3[Movie1,3,4],Tuple3[Movie1,3,4])

MovieRecommendationsWithJoin.java:171

...
14/06/07 23:18:15 INFO scheduler.DAGScheduler: Stage 9 (collect at

MovieRecommendationsWithJoin.java:171) finished in 0.109 s

14/06/07 23:18:15 INFO spark.SparkContext: Job finished: collect at

MovieRecommendationsWithJoin.java:171, took 0.13069563 s

debug55 key=User3
debug55 key=User3
debug55 key=User3
debug55 key=User2
debug55 key=User2
debug55 key=User2
debug55 key=User2
debug55 key=User2
debug55 key=User2
debug55 key=User4
debug55 key=User4
debug55 key=User4
debug55 key=User4
debug55 key=User4

value=(Tuple3[Movie2,3,4],Tuple3[Movie3,2,4])
value=(Tuple3[Movie1,2,4],Tuple3[Movie2,3,4])
value=(Tuple3[Movie1,2,4],Tuple3[Movie3,2,4])
value=(Tuple3[Movie2,5,4],Tuple3[Movie5,5,2])
value=(Tuple3[Movie2,5,4],Tuple3[Movie3,3,4])
value=(Tuple3[Movie3,3,4],Tuple3[Movie5,5,2])
value=(Tuple3[Movie1,2,4],Tuple3[Movie2,5,4])
value=(Tuple3[Movie1,2,4],Tuple3[Movie5,5,2])
value=(Tuple3[Movie1,2,4],Tuple3[Movie3,3,4])
value=(Tuple3[Movie2,3,4],Tuple3[Movie5,3,2])
value=(Tuple3[Movie2,3,4],Tuple3[Movie4,2,1])
value=(Tuple3[Movie2,3,4],Tuple3[Movie3,3,4])
value=(Tuple3[Movie4,2,1],Tuple3[Movie5,3,2])
value=(Tuple3[Movie3,3,4],Tuple3[Movie5,3,2])

282

debug55 key=User4
debug55 key=User4
debug55 key=User4
debug55 key=User4
debug55 key=User4
debug55 key=User1
debug55 key=User1
debug55 key=User1
=== Movie Correlations ===
14/06/07 23:18:15 INFO spark.SparkContext: Starting job: collect at

value=(Tuple3[Movie3,3,4],Tuple3[Movie4,2,1])
value=(Tuple3[Movie1,5,4],Tuple3[Movie2,3,4])
value=(Tuple3[Movie1,5,4],Tuple3[Movie5,3,2])
value=(Tuple3[Movie1,5,4],Tuple3[Movie4,2,1])
value=(Tuple3[Movie1,5,4],Tuple3[Movie3,3,4])
value=(Tuple3[Movie2,4,4],Tuple3[Movie3,3,4])
value=(Tuple3[Movie1,3,4],Tuple3[Movie2,4,4])
value=(Tuple3[Movie1,3,4],Tuple3[Movie3,3,4])

MovieRecommendationsWithJoin.java:242

...
14/06/07 23:18:15 INFO scheduler.DAGScheduler: Stage 13 (collect
at MovieRecommendationsWithJoin.java:242) finished in 0.075 s
14/06/07 23:18:15 INFO spark.SparkContext: Job finished: collect
at MovieRecommendationsWithJoin.java:242, took 0.216924159 s

debug5 key=(Movie2,Movie3)
debug5 key=(Movie1,Movie3)
debug5 key=(Movie3,Movie4)
debug5 key=(Movie3,Movie5)
debug5 key=(Movie4,Movie5)
debug5 key=(Movie1,Movie2)
debug5 key=(Movie2,Movie5)
debug5 key=(Movie1,Movie5)
debug5 key=(Movie1,Movie4)
debug5 key=(Movie2,Movie4)
...
14/06/07 23:18:16 INFO scheduler.DAGScheduler: Stage 18 (saveAsTextFile at

value=Tuple3[0.5222329678670935,0.9820699844444069,1.0]
value=Tuple3[0.47140452079103173,0.9422657923052785,1.0]
value=Tuple3[NaN,1.0,0.25]
value=Tuple3[NaN,0.970142500145332,0.5]
value=Tuple3[NaN,1.0,0.5]
value=Tuple3[-0.492365963917331,0.8638091589670809,1.0]
value=Tuple3[1.0,1.0,0.5]
value=Tuple3[-1.0,0.7961621941231025,0.5]
value=Tuple3[NaN,1.0,0.25]
value=Tuple3[NaN,1.0,0.25]

MovieRecommendationsWithJoin.java:247) finished in 1.014 s

14/06/07 23:18:16 INFO spark.SparkContext: Job finished: saveAsTextFile at

MovieRecommendationsWithJoin.java:247, took 1.131578238 s

10.11.1

Inspecting HDFS Output

# hadoop fs -ls /movies/output/
Found 2 items
-rw-r--r--
-rw-r--r--

3 hadoop root,hadoop
3 hadoop root,hadoop

283

0 2014-06-07 23:18 /movies/output/_SUCCESS
504 2014-06-07 23:18 /movies/output/part-00000

# hadoop fs -cat /movies/output/part-00000
((Movie2,Movie3),Tuple3[0.5222329678670935,0.9820699844444069,1.0])
((Movie1,Movie3),Tuple3[0.47140452079103173,0.9422657923052785,1.0])
((Movie3,Movie4),Tuple3[NaN,1.0,0.25])
((Movie3,Movie5),Tuple3[NaN,0.970142500145332,0.5])
((Movie4,Movie5),Tuple3[NaN,1.0,0.5])
((Movie1,Movie2),Tuple3[-0.492365963917331,0.8638091589670809,1.0])
((Movie2,Movie5),Tuple3[1.0,1.0,0.5])
((Movie1,Movie5),Tuple3[-1.0,0.7961621941231025,0.5])
((Movie1,Movie4),Tuple3[NaN,1.0,0.25])
((Movie2,Movie4),Tuple3[NaN,1.0,0.25])

284

Chapter 11

Smarter Email Marketing with Markov
Model

11.1

Introduction

The goal of this chapter is to show that how Markov Model (in the simplest
form known as Markov Chain) can be used in predicting the ”next smart
email marketing date” to customers based on their transaction history. Given
a set of random varibles (such as last purchase date by customers), Markov
model indicates that the distribution for this variable (last purchase date)
depends only on the distribution of the previous state (another last purchase
date). We implement a MapReduce solution for smarter email marketing
with using Markove Model.

For writing this chapter, I was inspired by the blog ”Smarter Email Market-
ing with Markov Model” posted by Pranab Ghosh 1, and this chapter is based
on his blog. For implementation of MapReduce phases of this chapter, I have
developed brand new modular Java classes to demonstrate the core values
(such as sorting of reduced values by MapReduce’s ”secondary sort” tech-
nique, deﬁning custom partitioner class, and deﬁning ”grouping compara-
tor” class). Therefore, given customer’s transation history (purchase-date,
amount-purchased) the goal is to use MapReduce and Markov Chain Model
to predict the next date (predictive modeling technique) for sending an email

1http://pkghosh.wordpress.com/2013/04/15/smarter-email-marketing-with-markov-model/

285

marketing to that customer. This is kind of a machine learning algorithm.
Typically, a machine leaning based solutions consist of two distinct phases:

• Phase-1: build a model by using historical training data.

• Phase-2: make a prediction for next new data using the model built in

Phase-1.

11.2 Markov Chain in a Nutshell

Let S = {S1, S2, S3, ...} be a set of ﬁnite states and we want to collect the
following probabilities:

P (Sn|Sn−1, Sn−2, ..., S1)

Markov’s ﬁrst-order assumption is the following:

P (Sn|Sn−1, Sn−2, ..., S1) ≈ P (Sn|Sn−1)

This approximation states the Markov Property: the state of the system at
time t+1 depends only on the state of the system at time t, and Markov
second-order assumption is the following:

P (Sn|Sn−1, Sn−2, ..., S1) ≈ P (Sn|Sn−1, Sn−2)

Now, we can express the joint probability using the Markov assumption:

P (S1, S2, ..., Sn) =

n
(cid:89)

i=1

P (Si, Si−1)

Markov random processes can be summaraized as2:

• A random sequence has the Markov property if its distribution is de-
termined solely by its current state. Any random process having this
property is called a Markov random process.

2Based on slides by Mehmet Yunus Dnmez:

http://classes.soe.ucsc.edu/

cmpe264/Fall06/LecHMM.pdf

286

• For observable state sequences (state is known from data), this leads to
a Markov chain model. This is what we will use in creating a Markov
model to predict the next email marketing date.

• For non-observable states, this leads to a Hidden Markov Model (HMM).

Now, we formalize Markov Chain (which we will use in this chapter):

Markov Chain has 3 components:

1. State Space: a ﬁnite set of states S = {S1, S2, S3, ...}

2. Transition Probabilities: a function f : S × S → R such that 0 ≤

f (a, b) ≤ 1 for all a, b ∈ S and (cid:80)
b∈S

f (a, b) = 1 for every a ∈ S.

3. Initial Distribution: a function g : S × R such that 0 ≤ g(a) ≤ 1 for

every a ∈ S and (cid:80)
a∈S

g(a) = 1.

Then a Markov Chain is a random process in S such that

1. At time 0 the state of the chain is distributed according to function g

2. If at time t the state of chain is a, then at time t + 1 it will end up at

state b with probability of f (a, b) for every b ∈ S.

Let’s illustrate this by an example: let a weather pattern for a city be in
4 states: sunny, cloudy, rainy, foggy and further assume that the state
does not change for a day. The sum of each row is 1.00.

(cid:104)(cid:104)(cid:104)(cid:104)(cid:104)(cid:104)(cid:104)(cid:104)(cid:104)(cid:104)(cid:104)(cid:104)(cid:104)(cid:104)(cid:104)(cid:104)(cid:104)(cid:104)(cid:104)(cid:104)(cid:104)(cid:104)

Tomorrow’s Weather

Today’s Weather
sunny
rainy
cloudy
foggy

sunny

rainy

cloudy

foggy

0.6
0.5
0.1
0.0

0.1
0.2
0.7
0.3

0.2
0.2
0.1
0.4

0.1
0.1
0.1
0.3

Now, we can answer the following questions:

• Given that today is sunny, what is the probability that tomorrow is

cloudy and the day after is foggy?

287

P (S2 = cloudy, S3 = f oggy|S1 = sunny)
= P (S3 = f oggy|S2 = cloudy, S1 = sunny) ×
P (S2 = cloudy|S1 = sunny)
= P (S3 = f oggy|S2 = cloudy) ×
P (S2 = cloudy|S1 = sunny)
= 0.1 × 0.2
= 0.02

• Given that today is foggy, what is the probability that it will rainy
two days from now? (this means that the second day can be any of
sunny, cloudy, rainy, foggy):

P (S3 = f oggy|S1 = f oggy) =
P (S3 = f oggy, S2 = sunny|S1 = f oggy) +
P (S3 = f oggy, S2 = cloudy|S1 = f oggy) +
P (S3 = f oggy, S2 = rainy|S1 = f oggy) +
P (S3 = f oggy, S2 = f oggy|S1 = f oggy) +
= P (S3 = f oggy|S2 = sunny) × P (S2 = sunny|S1 = f oggy) +
P (S3 = f oggy|S2 = cloudy) × P (S2 = cloudy|S1 = f oggy) +
P (S3 = f oggy|S2 = rainy) × P (S2 = rainy|S1 = f oggy) +
P (S3 = f oggy|S2 = f oggy) × P (S2 = f oggy|S1 = f oggy)
= 0.1 × 0.0 +
0.1 × 0.4 +
0.1 × 0.3 +
0.3 × 0.3
= 0.00 + 0.04 + 0.03 + 0.09
= 0.16

So one of the main goal of this chapter is to build the model (the proba-
bility transition table), which will deﬁne f (a, b) for all a ∈ S. Once we have
this model the rest is easy.

11.3 Markov Model using MapReduce

We assume that we have historical customer transaction data, which in-
cludes transaction-id, customer-id, purchase-date, amount. There-
fore, each input record will have:

288

Figure 11.1: Markov Work Flow

transaction-id, customer-id, purchase-date, amount

The entire solution involves two MapReduce jobs and a set of Ruby scripts
(the Ruby scripts are developed by Pranab Ghosh – will provide pointers for
these Ruby scripts as we use them).

The entire workﬂow is depicted below ( 11.1):

Steps are outlined below:

1. We use a script to generate fake Customer Data (1).

2. The MapReduce Prjection (2) accepts Customer Data (1) as an input
and generates Sorted Data (3). The Sorted Data (3) is a date-ordered-
in-asscending order.

3. The State Converter (4) script accepts the Sorted Data (3) and gener-

ates State Sequence (5).

289

4. The MapReduce Markov State Transition Model (6) accepts State Se-
quence (5) as an input and generates Markov Chain Model (7). This
model enable us to predict the next state.

5. Finally, we use a script, Predict Next State (9), which accepts new
Customer Data (8) and Markov Chain Model (7) and gives/predicts
the next email date for marketing.

11.3.1 MapReduce to Generate Time-ordered Trans-

actions

The goal of this MapReduce phase will be to accept historical customer
transaction data and generate the following output for every customer-id:

customerid, (Date1, Amount1), (Date2, Amount2), ...(DateN , AmountN )

such that

Date1 ≤ Date2 ≤ ... ≤ DateN

Output of MapReduce is sorted on the ”purchased-date” by ascending
order. After output is created, we will convert (Date, Amount) into a two-
letter-symbol (this step is done by a script), which stands for a Markov
Chain state. Generating sorted output can be accomplished in two ways:
each reducer can sort its output by the ”purchased-date” by ascending order
(here you need enough RAM to hold all your data for sorting) or you can use
MapReduce’s ”secondary sort” (by using the sort capability of MapReduce
framework — this way you do not need much RAM at all) to sort data by
date. We will present solutions for both cases. The ﬁnal output generated
from this phase will have the following format:

customerid, State1, State2, ..., Staten

11.3.1.1 Mapper

Listing 11.1: Time-ordered Transactions map() Function

290

/**
* @param key is ignored
* @param value is transaction-id, customer-id, purchase-date, amount
*/
map(key, value) {

pair(Date, Integer) pair = (value.purchase-date, value.amount);
emit(value.customer-id, pair);

}

11.3.1.2 Reducer

Listing 11.2: Time-ordered Transactions reduce() Function
/**
* @param key is a customer-id
* @param values is a list of pairs of Pair(Date, Integer)
*/
reduce(String key, List<Pair<Date, Integer>> values) {
sortedValues = sortbyDateInAscendingOrder(values);
emit(key, sortedValues);

}

11.3.1.3 Hadoop Solution 1: Time-ordered Transactions

Mappers emit (key, value), where key is a ”customer-id” and value is pair of
(”purchase-date”, ”amount”). Data arrive to reducers unsorted. This solu-
tion performs sorting of transactions in reducer. In the number of trasactions
arriving at reducers are too big, then this might cause ”out-of-memory” ex-
ception in reducers. Our ”Hadoop Solution 2” will not have this restriction:
rather than sorting data in memeory per reducer, we use ”secondary sort”,
which is a feature of MapReduce paradigm for sorting the values of reducers.

Hadoop Solution 1: Implementation Classes

Class Name
SortInMemoryProjectionDriver
SortInMemoryProjectionMapper Mapper class
SortInMemoryProjectionReducer Reducer class
DateUtil
HadoopUtil

Basic Date Utility class
Basic Hadoop Utility class

Description
Driver class to submit jobs

291

11.3.1.4 Hadoop Solution 1: Sample Run

11.3.1.4.1 Hadoop Solution 1: Partial Input

Pranab Ghosh has provided a Ruby script (buy_xaction.rb3), which gen-
erates fake customer transaction data:

./buy_xaction.rb 80000 210 .05 > training.txt

# hadoop fs -copyFromLocal training.txt

/markov_email_marketing/projection_by_sorting_in_ram/input/

# hadoop fs -cat

/markov_email_marketing/projection_by_sorting_in_ram/input/training.txt

...
EY2I3D12PZ,1382705171,2013-07-29,28
VC38QFM2IF,1382705172,2013-07-29,84
1022R2QPWG,1382705173,2013-07-29,27
4G02MW73CK,1382705174,2013-07-29,31
VKV2K1S0D2,1382705175,2013-07-29,28
LDFK8WZQFH,1382705176,2013-07-29,25
8874144Q11,1382705177,2013-07-29,180
...

11.3.1.4.2 Hadoop Solution 1: Run

# ./run.sh
JAVA_HOME=/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
...
adding: DateUtil.class(in = 1126) (out= 614)(deflated 45%)
adding: HadoopUtil.class(in = 1797) (out= 840)(deflated 53%)
adding: SortInMemoryProjectionDriver.class(in = 2780) (out= 1361)(deflated 51%)
adding: SortInMemoryProjectionMapper.class(in = 2112) (out= 899)(deflated 57%)
adding: SortInMemoryProjectionReducer.class(in = 2477) (out= 1143)(deflated 53%)
Deleted hdfs://localhost:9000/lib/projection_by_sorting_in_ram.jar
Deleted hdfs://localhost:9000/markov_email_marketing/projection_by_sorting_in_ram/output
...

3https://github.com/pranab/avenir/blob/master/resource/buy_xaction.rb

292

Map-Reduce Framework

13/11/27 12:03:16 INFO mapred.JobClient: Running job: job_201311271011_0012
13/11/27 12:03:17 INFO mapred.JobClient: map 0% reduce 0%
13/11/27 12:03:26 INFO mapred.JobClient: map 100% reduce 0%
13/11/27 12:03:34 INFO mapred.JobClient: map 100% reduce 6%
...
13/11/27 12:04:16 INFO mapred.JobClient: map 100% reduce 100%
13/11/27 12:04:17 INFO mapred.JobClient: Job complete: job_201311271011_0012
...
13/11/27 12:04:17 INFO mapred.JobClient:
13/11/27 12:04:17 INFO mapred.JobClient:
13/11/27 12:04:17 INFO mapred.JobClient:
13/11/27 12:04:17 INFO mapred.JobClient:
13/11/27 12:04:17 INFO mapred.JobClient:
13/11/27 12:04:17 INFO mapred.JobClient:
13/11/27 12:04:17 INFO mapred.JobClient:
13/11/27 12:04:17 INFO mapred.JobClient:
13/11/27 12:04:17 INFO mapred.JobClient:
13/11/27 12:04:17 INFO mapred.JobClient:
13/11/27 12:04:17 INFO mapred.JobClient:
13/11/27 12:04:17 INFO mapred.JobClient:
13/11/27 12:04:17 INFO mapred.JobClient:
13/11/27 12:04:17 INFO mapred.JobClient:
13/11/27 12:04:17 INFO SortInMemoryProjectionDriver: jobStatus: true
13/11/27 12:04:17 INFO SortInMemoryProjectionDriver: elapsedTime (in milliseconds): 62063

Map output materialized bytes=20807060
Map input records=832280
Reduce shuffle bytes=20807060
Spilled Records=2496840
Map output bytes=19142440
Total committed heap usage (bytes)=1047195648
Combine input records=0
SPLIT_RAW_BYTES=157
Reduce input records=832280
Reduce input groups=79998
Combine output records=0
Reduce output records=79998
Map output records=832280

11.3.1.4.3 Hadoop Solution 1: partial Output

...
ZTOBR28AH2 2013-01-06,190;2013-04-02,109;2013-04-09,26;2013-05-04,40;2013-05-12,34;2013-07-16,154
ZV2A56WNI6 2013-01-22,51;2013-01-24,34;2013-02-09,52;2013-04-11,200;2013-05-25,58;2013-07-02,102;2013-07-11,31
ZVPH1EE3CI 2013-01-20,45;2013-03-02,107;2013-03-31,31;2013-06-12,198;2013-07-21,64;2013-07-24,33
ZXN7727FBA 2013-02-07,164;2013-02-23,30;2013-03-28,107;2013-04-02,26;2013-04-04,49;2013-07-02,175
ZY44ATNBK7 2013-03-27,191;2013-04-27,51;2013-05-06,31;2013-06-30,81
...

The next task is to convert (using a Ruby script developed by Pranab
Ghosh) sorted consecutive sequence of (purchase-date, purchase-amount)
pairs into a set of ”Markov Chain states”. The state is deﬁned by a ”two-
letter-symbol” and is deﬁned below:

293

Time elapsed since Amount spent compared
to previous transaction
last transaction
L : signiﬁcantly less than
S : small
E : more or less same
M : medium
G : signiﬁcantly greater than
L : large

Therefore, we will have 9 (3 × 3) states:

Time elapsed since last transaction :

State
Name Amount spent compared to previous transaction
SL
SE
SG
ML
ME
MG
LL
LE
LG

small : signiﬁcantly less than
small : more or less same
small : signiﬁcantly greater than
medium : signiﬁcantly less than
medium : more or less same
medium : signiﬁcantly greater than
large : signiﬁcantly less than
large : more or less same
large : signiﬁcantly greater than

Therefore our Markov Chain model has 9 states (transition matrix of
9 × 9). The next step is to build our model’s Transition Probabilities: that
is to deﬁne

0.0 ≤ P (state1, state2) ≤ 1.0

where state1 and state2 ∈ {SL, SE, SG, M L, M E, M G, LL, LE, LG}.

11.3.1.5 Hadoop Solution 2: Time-ordered Transactions

This implementation provides a solution, which sorts reducers values by us-
ing ”secondary sort” technique, which is a feature of MapReduce paradigm
for sorting the values of reducers. To accomplish this, we need some cus-
tome classes, which will be plugged in to the MapReduce’s framework imple-
mentation. Mappers emit (key, value), where key is a pair (”customer-id”,
”purchase-date”) and value is pair of (”purchase-date”, ”amount”). Data
arrive to reducers sorted. As you can see, to generate sorted values for each
reducer key, we put the ”purchase-date” (which is the ﬁrst part of the emitted
mapper value) as part of the mapper key. So, the CompositeKey is comprised
of a pair (”customer-id”, ”purchase-date”). We represent value as pair of

294

(”purchase-date”, ”amount”) as a class edu.umd.cloud9.io.pair.PairOfLongInt4,
where the ”Long” part will represent Date and ”Int” part represents purchase
”amount”.

MapReduce framework states that once the data values reaches a reducer,
all data is grouped by key. Since we have a composite key (represented as
CompositeKey — comprised of a pair (”customer-id”, ”purchase-date”)), we
need to make sure that records are grouped solely by the natural key (the
natural key is the ”customer-id”) . This is accomplished by writing a custom
partitioner class: NaturalKeyPartitioner.

We do need to provide more plug-in classes:

Configuration conf = new Configuration();
JobConf jobconf = new JobConf(conf, SecondarySortProjectionDriver.class);
...
jobconf.setPartitionerClass(NaturalKeyPartitioner.class);
jobconf.setOutputKeyComparatorClass(CompositeKeyComparator.class);
jobconf.setOutputValueGroupingComparator(NaturalKeyGroupingComparator.class);

Let’s summarize "secondary sort": mappers generate (key, value) pairs.
The order of the values arriving to a reducer is unspeciﬁed and can vary
between job runs. For example, let all mappers generate (K, V1), (K, V2),
and (K, V3). So, for the key K, we have 3 values: V1, V2, V3: so a reducer,
which is processing key K might get one (out of 6) of the following orders:

V1, V2, V3
V1, V3, V2
V2, V1, V3
V2, V3, V1
V3, V1, V2
V3, V2, V1

OR
OR
OR
OR
OR

In most of the situations (this depends on your requirements and how
you will process reducer values), it really does not matter in what order we

4

http://lintool.github.io/Cloud9/docs/api/edu/umd/cloud9/io/pair/

PairOfLongInt.html

295

get these values (i.e., V1, V2, V3). But if you want to put some ordering
in receiving and processing values (such as sorted by ascending or sorted by
descending), then the ﬁrst option is to get all values V1, V2, V3 and then
apply a sort function on these values, which you will get your desired order of
values. This sort technique might not be feasible if you do not have enough
RAM in your servers. There is another preferable method (which scales out
very well and you do not need to worry about big RAM requirements) to
have sorted values arriving at a reducer by utilizing the sort and shuﬄe fea-
ture of the MapReduce’s framework. This technique is called a "secondary
sort". Secondary sort is a technique that allows the MapReduce program-
mer to control the order that the values show up within a reduce function
call. To achieve this, you need to use a composite key that contains both the
information needed to sort by key and the information needed by value, and
then decoupling the grouping of the intermediate data from the sorting of the
intermediate data. The ”secondary sorting” enables to deﬁne sorting order
of the values generated by mappers. Sorting is done on both by the keys and
the values. Further, grouping enable us to decide which sets of (key, value)
are put together into a single call of the reduce function. For our example,
the composite key is illustrated below ( 11.2):

In Hadoop, the grouping is controlled in two places: (1) the partitioner,
which sends map outputs to reduce tasks, and the (2) grouping comparator,
which groups data within a reduce task. Both of these (partitioner and group
comparator) can be accomplished by pluggable classes per MapReduce job.
To sort values for reducers, we have to deﬁne a pluggable class, which sets the
output key comparator. Therefore, using raw MapReduce, getting secondary
sort working can take a little bit of work - we need to deﬁne a composite key
and specify three functions (by deﬁning pluggable classes to the MapReduce
job — details are given below) that each use it in diﬀerent ways. Note that,
for our example the natural key is a customerID (as a String object) and
there is no need to wrap it in another class, which we might call it as a
NaturalKey. The natural key is what you would normally use as the key or
”group by” operator.

296

Figure 11.2: Composite Key for Secondary Sorting

297

Hadoop Solution 2: Implementation Classes

Class Name
SecondarySortProjectionDriver
SecondarySortProjectionMapper Mapper class
SecondarySortProjectionReducer Reducer class
CompositeKey

Description
Driver class to submit jobs

Custom key to hold a pair
of (customer-id, purchase-date)
which is a combination of
the natural key and the natural value
we want to sort by
How to sort CompositeKey objects,
compares two composite keys for sorting.
considers the natural key;
makes sure that a single reducer
sees a custom view of the groups
(how to group CustomerID)
How to partition by the natural key
(customerID) to reducers; blocks
all data into a logical group,
inside which we want the secondary
sort to occur on the natural value
Basic Date Utility class
Basic Hadoop Utility class

CompositeKeyComparator

NaturalKeyGroupingComparator

NaturalKeyPartitioner

DateUtil
HadoopUtil

11.3.1.6 Hadoop Solution 2: Sample Run

11.3.1.6.1 Hadoop Solution 2: Partial Input

# hadoop fs -cat /markov_email_marketing/projection_by_secondary_sort/input/training.txt | head
V31E55G4FI,1381872898,2013-01-01,123
301UNH7I2F,1381872899,2013-01-01,148
PP2KVIR4LD,1381872900,2013-01-01,163
AC57MM3WNV,1381872901,2013-01-01,188
BN020INHUM,1381872902,2013-01-01,116
UP8R2SOR77,1381872903,2013-01-01,183
VD91210MGH,1381872904,2013-01-01,204
COI4OXHET1,1381872905,2013-01-01,78

298

76S34ZE89C,1381872906,2013-01-01,105
6K3SNF2EG1,1381872907,2013-01-01,214

11.3.1.6.2 Hadoop Solution 1: Run

# ./run.sh
JAVA_HOME=/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
...
adding: CompositeKey$CompositeKeyComparator.class(in = 448) (out= 305)(deflated 31%)
adding: CompositeKey.class(in = 1767) (out= 883)(deflated 50%)
adding: CompositeKeyComparator.class(in = 715) (out= 448)(deflated 37%)
adding: DateUtil.class(in = 1126) (out= 614)(deflated 45%)
adding: HadoopUtil.class(in = 2541) (out= 1139)(deflated 55%)
adding: NaturalKeyGroupingComparator.class(in = 588) (out= 354)(deflated 39%)
adding: NaturalKeyPartitioner.class(in = 1204) (out= 672)(deflated 44%)
adding: SecondarySortProjectionDriver.class(in = 3290) (out= 1576)(deflated 52%)
adding: SecondarySortProjectionMapper.class(in = 2136) (out= 916)(deflated 57%)
adding: SecondarySortProjectionReducer.class(in = 1999) (out= 897)(deflated 55%)
Deleted hdfs://localhost:9000/lib/projection_by_secondary_sort.jar
Deleted hdfs://localhost:9000/markov_email_marketing/projection_by_secondary_sort/output
...
13/11/27 15:14:34 INFO mapred.FileInputFormat: Total input paths to process : 1
13/11/27 15:14:34 INFO mapred.JobClient: Running job: job_201311271459_0003
13/11/27 15:14:35 INFO mapred.JobClient: map 0% reduce 0%
13/11/27 15:14:45 INFO mapred.JobClient: map 25% reduce 0%
...
13/11/27 15:16:01 INFO mapred.JobClient: map 100% reduce 93%
13/11/27 15:16:02 INFO mapred.JobClient: map 100% reduce 100%
13/11/27 15:16:03 INFO mapred.JobClient: Job complete: job_201311271459_0003
...
13/11/27 15:16:03 INFO mapred.JobClient:
13/11/27 15:16:03 INFO mapred.JobClient:
13/11/27 15:16:03 INFO mapred.JobClient:
13/11/27 15:16:03 INFO mapred.JobClient:
13/11/27 15:16:03 INFO mapred.JobClient:
13/11/27 15:16:03 INFO mapred.JobClient:
13/11/27 15:16:03 INFO mapred.JobClient:
13/11/27 15:16:03 INFO mapred.JobClient:

Map output materialized bytes=7560600
Map input records=832280
Reduce shuffle bytes=7560600
Spilled Records=1664560
Map output bytes=26632960
Total committed heap usage (bytes)=4785434624
Map input bytes=30089506

Map-Reduce Framework

299

13/11/27 15:16:03 INFO mapred.JobClient:
13/11/27 15:16:03 INFO mapred.JobClient:
13/11/27 15:16:03 INFO mapred.JobClient:
13/11/27 15:16:03 INFO mapred.JobClient:
13/11/27 15:16:03 INFO mapred.JobClient:
13/11/27 15:16:03 INFO mapred.JobClient:
13/11/27 15:16:03 INFO mapred.JobClient:
13/11/27 15:16:03 INFO SecondarySortProjectionDriver: elapsedTime (in milliseconds): 89809

Combine input records=0
SPLIT_RAW_BYTES=2900
Reduce input records=832280
Reduce input groups=79998
Combine output records=0
Reduce output records=79998
Map output records=832280

11.3.1.6.3 Hadoop Solution 2: partial Output

...
ZSY40NVPS6 2013-01-01,110;2013-01-11,32;2013-03-04,111;2013-04-09,65;2013-05-15,100;
ZTLNF0O4LN 2013-01-16,55;2013-03-21,164;2013-05-14,66;2013-06-29,81;
ZV20AIXG8L 2013-01-13,210;2013-02-03,32;2013-02-10,48;2013-02-23,27;2013-03-08,55;2013-03-12,26;2013-03-30,51;2013-07-14,205;
ZVA9U4EQ46 2013-01-21,199;2013-01-26,34;2013-01-28,49;2013-02-18,25;2013-04-29,198;2013-06-23,52;2013-07-08,33;
ZW8612MI1V 2013-02-27,107;2013-03-14,33;2013-03-23,41;2013-04-13,30;2013-05-12,42;2013-05-24,33;2013-06-28,91;
...

11.3.2 MapReduce to Generate Markov State Transi-

tion

The goal of this MapReduce phase is to generate Markov State Transition
matrix. The input for this phase will be the ”state sequence” and will have
the following format:

customerid, State1, State2, ..., Staten

and the output will be a matrix of N × N where N is the number of
states (in our model N = 9) for Marokov Chain model. The matrix entries
will indicate the probability of going from one state to another one. The goal
of this MapReduce is to count the number of instances of state transitions.
Since the number of states for our model is 9, therefore, we will have 9×9 = 81
poossible state transitions.

11.3.2.1 Mapper

300

Listing 11.3: Markov State Transition map() Function
/**
* @param key is the Customer-ID, ignored
* @param value is sequence of states = {S1, S2, ..., Sn}
* we assume value is an array of n states (indexed from 0 to n-1)
*/
map(key, value) {

for (i=0, i < n-1, i++) {

// value[i] denotes "from state"
// value[i+1] denotes "to state"
reducerKey = pair(value[i], value[i+1]);
emit(reducerKey, 1);

}

}

11.3.2.2 Combiner

Listing 11.4: Markov State Transition combine() Function
/**
* @param key is a Pair(state1, state2)
* @param value is a list of integers (partial count of "state1" to "

state2")

*/
combine(Pair(state1, state2) key, List<integer> values) {

int partialSum = 0;
for (int count : values) {
partialSum += count;

}
emit(key, partialSum);

}

11.3.2.3 Reducer

Listing 11.5: Markov State Transition reduce() Function
/**
* @param key is a Pair(state1, state2)

301

* @param value is a list of integers (partial count of "state1" to "

state2")

*/
reduce(Pair(state1, state2) key, List<integer> value) {

int sum = 0;
for (int count : value) {

sum += count;

}
emit(key, sum);

}

11.3.2.4 Hadoop Implementation of State Transition Model

Hadoop Solution 2: Implementation Classes

Class Name
MarkovStateTransitionModelDriver
MarkovStateTransitionModelMapper
MarkovStateTransitionModelCombiner Combiner class
MarkovStateTransitionModelReducer
ReadDataFromHDFS

Description
Driver class to submit jobs
Mapper class

StateTransitionTableBuilder

TableItem

HadoopUtil

Reducer class
Reads data from HDFS and
creates List<TableItem>
builds transition table
and deﬁnes P(state1, state2)
A class to represent a triplet of
(fromState, toState, count)
Basic Hadoop Utility class

11.3.2.5 Sample Run of State Transition Model

11.3.2.5.1 Sample Run: Input

# hadoop fs -cat /markov_email_marketing/state_transition_model/input/state_seq.txt | head
000IA1PHVZ,SG,SL,SG,SL,ML,MG,SG,SL,SG,SL,ML
000KH3DK15,SG,SL,SG,ML,SG,SL,SG,SL,SG,SL,SG,ML,SG,SL,SG
001KD25DTD,SG,SL,SG,SL,SG,SL,SG
00241F24T4,SG,SL,SG,SL,SG,SL,SG,ML,SG,SL,ML,SG,ML,SG
002C11GB8Y,SG,SL,SG,SL,SG,SL,SG,ML,SG,SL,SG,ML,SG
002SG5SKJT,SG,SL,SG,ML,SG,SL,SG

302

0030B44HD0,SG,SL,SG,SL,SG,SL,SG,SL,ML,SG
004ADRKOEW,SG,SL,SG,ML,MG,SG,SL,SG,LL
004MT1M5BY,SG,SL,SG,SL,SG,ML,SG,ML,SG,SL,ML
007DI3WJ5B,SL,SL,ML,MG,SG,SE,SL,SG,SG,SL,SG

11.3.2.5.2 Sample Job Run

# ./run.sh
...
adding: HadoopUtil.class(in = 1797) (out= 840)(deflated 53%)
adding: MarkovStateTransitionModelCombiner.class(in = 1711) (out= 704)(deflated 58%)
adding: MarkovStateTransitionModelDriver.class(in = 1976) (out= 988)(deflated 50%)
adding: MarkovStateTransitionModelMapper.class(in = 2018) (out= 826)(deflated 59%)
adding: MarkovStateTransitionModelReducer.class(in = 2018) (out= 869)(deflated 56%)
adding: ReadDataFromHDFS.class(in = 3691) (out= 1848)(deflated 49%)
adding: StateTransitionTableBuilder.class(in = 1287) (out= 708)(deflated 44%)
adding: TableItem.class(in = 375) (out= 263)(deflated 29%)
...
13/11/29 21:16:17 INFO mapred.JobClient: Running job: job_201311291911_0003
13/11/29 21:16:18 INFO mapred.JobClient: map 0% reduce 0%
13/11/29 21:16:25 INFO mapred.JobClient: map 100% reduce 0%
13/11/29 21:16:32 INFO mapred.JobClient: map 100% reduce 3%
...
13/11/29 21:17:10 INFO mapred.JobClient: map 100% reduce 100%
13/11/29 21:17:11 INFO mapred.JobClient: Job complete: job_201311291911_0003
...
13/11/29 21:17:11 INFO mapred.JobClient:
13/11/29 21:17:11 INFO mapred.JobClient:
13/11/29 21:17:11 INFO mapred.JobClient:
13/11/29 21:17:11 INFO mapred.JobClient:
13/11/29 21:17:11 INFO mapred.JobClient:
13/11/29 21:17:11 INFO mapred.JobClient:
13/11/29 21:17:11 INFO mapred.JobClient:
13/11/29 21:17:11 INFO mapred.JobClient:
13/11/29 21:17:11 INFO mapred.JobClient:
13/11/29 21:17:11 INFO mapred.JobClient:

Map output materialized bytes=844
Map input records=79977
Reduce shuffle bytes=844
Spilled Records=268
Map output bytes=8067660
Total committed heap usage (bytes)=1050497024
Combine input records=672461
SPLIT_RAW_BYTES=152
Reduce input records=56

Map-Reduce Framework

303

13/11/29 21:17:11 INFO mapred.JobClient:
13/11/29 21:17:11 INFO mapred.JobClient:
13/11/29 21:17:11 INFO mapred.JobClient:
13/11/29 21:17:11 INFO mapred.JobClient:

Reduce input groups=56
Combine output records=212
Reduce output records=56
Map output records=672305

11.3.2.5.3 Sample Run: Output

# hadoop fs -ls /markov_email_marketing/state_transition_model/output/part*
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--

58 2013-11-29 21:16 /markov_email_marketing/state_transition_model/output/part-r-00000
85 2013-11-29 21:16 /markov_email_marketing/state_transition_model/output/part-r-00001
60 2013-11-29 21:16 /markov_email_marketing/state_transition_model/output/part-r-00002
43 2013-11-29 21:16 /markov_email_marketing/state_transition_model/output/part-r-00003
53 2013-11-29 21:16 /markov_email_marketing/state_transition_model/output/part-r-00004
60 2013-11-29 21:16 /markov_email_marketing/state_transition_model/output/part-r-00005
76 2013-11-29 21:16 /markov_email_marketing/state_transition_model/output/part-r-00006
54 2013-11-29 21:16 /markov_email_marketing/state_transition_model/output/part-r-00007
30 2013-11-29 21:17 /markov_email_marketing/state_transition_model/output/part-r-00008
46 2013-11-29 21:17 /markov_email_marketing/state_transition_model/output/part-r-00009

1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff

# hadoop fs -cat /markov_email_marketing/state_transition_model/output/part*
LL,MG 2990
ME,SG 172
MG,LL 803
ML,LG 59
SE,MG 5
SG,ME 606
LG,SG 1516
LL,SL 69
MG,ML 3477
ML,MG 12391
SE,SL 3014
SG,LG 69
SL,LL 7885
SL,SE 2099
LE,LG 2
LG,LE 1
MG,SG 19485

304

ML,SL 268
SG,MG 337
SL,ML 35265
LE,MG 10
ME,LG 1
SG,SL 242614
SL,SG 177254
LE,SL 140
LG,LG 1
ME,MG 31
SE,LL 62
SE,SE 2
SL,LE 24
LG,MG 327
ME,SL 606
MG,LG 18
ML,LL 2465
SE,ML 305
SL,ME 151
LG,SL 510
LL,SG 17062
MG,MG 172
SE,SG 1478
SG,LL 10975
SG,SE 3013
SL,LG 240
LL,LE 1
MG,SL 2096
ML,SG 63843
SG,ML 48428
SL,MG 1325
ME,LL 5
SG,SG 5090
SL,SL 2772
LE,SG 58
LG,LL 64
LL,LG 507
SE,LG 2

305

SG,LE 140

# javac ReadDataFromHDFS.java TableItem.java
# java ReadDataFromHDFS /markov_email_marketing/state_transition_model/output
Nov 30 2013 12:24:18 [main] [INFO ] [ReadDataFromHDFS] - path=hdfs://hnode00815.nextbiosystem.net:9000/tmp/part1
Nov 30 2013 12:24:18 [main] [INFO ] [ReadDataFromHDFS] - line=LL,MG 2990
172
Nov 30 2013 12:24:18 [main] [INFO ] [ReadDataFromHDFS] - line=ME,SG
803
Nov 30 2013 12:24:18 [main] [INFO ] [ReadDataFromHDFS] - line=MG,LL
...
Nov 30 2013 12:24:18 [main] [INFO ] [ReadDataFromHDFS] - line=LL,LG
Nov 30 2013 12:24:18 [main] [INFO ] [ReadDataFromHDFS] - line=SE,LG
Nov 30 2013 12:24:18 [main] [INFO ] [ReadDataFromHDFS] - line=SG,LE
Nov 30 2013 12:27:45 [main] [INFO ] [ReadDataFromHDFS] - list=[{LL,MG,2990}, {ME,SG,172}, {MG,LL,803}, ...

507
2
140

11.4 Using Markov Model to Predict Next

Email Marketing Date

Now that we have built the Markov Chain model from a given training data,
we can use it to predict the next email marketing date for customers.

To persist the model (model.txt) , we use the following piece of code:

# cat StateTransitionTableBuilder.java
...
public class StateTransitionTableBuilder {

...

public static void main(String[] args) {

String hdfsDirectory = args[0];
generateStateTransitionTable(hdfsDirectory);

}

}

# export hdfsDir="/markov_email_marketing/state_transition_model/output"
# java StateTransitionTableBuilder $hdfsDir > model.txt

Now that we have the model (model.txt — represented as a two-dimensional

306

table), we can use a Ruby scripts (buy_xaction.rb and mark_plan.rb) de-
veloped by Pranab Ghosh to predict the next email marketing date:

# Generate validation data
# ------------------------
./buy_xaction.rb 80000 30 .05 > validation.txt
head validation.txt
XURQDBEHME,1385141945,2013-01-01,98
3RT4PONSUP,1385141946,2013-01-01,53
4NYCEUD3YG,1385141947,2013-01-01,164
SF9KAY8F42,1385141948,2013-01-01,204
LKNCID1DRV,1385141949,2013-01-01,83
4EZJDVB4W1,1385141950,2013-01-01,116
ITJ39B3NX3,1385141951,2013-01-01,72
D8VVPAHG8I,1385141952,2013-01-01,124
21XHZJY561,1385141953,2013-01-01,103
F7LS37R08X,1385141954,2013-01-01,211

# Predict email marketing time
# ----------------------------
./mark_plan.rb validation.txt model.txt
XURQDBEHME, 2013-04-27
4NYCEUD3YG, 2013-04-14
SF9KAY8F42, 2013-04-07
LKNCID1DRV, 2013-04-30
4EZJDVB4W1, 2013-02-02
ITJ39B3NX3, 2013-04-27
D8VVPAHG8I, 2013-04-29
21XHZJY561, 2013-01-18
F7LS37R08X, 2013-02-14
...

Therefore, we are able to predict the next date for sending an email

marking based on the transation hisory of users.

307

Chapter 12

K-Means Clustering

12.1

Introduction

The main goal of this chapter is to provide a MapReduce solution for K-
Means clustering algorithm. K-Means MapReduce algorithm is interesting
and diﬀerent from othe Mapreduce algorithms. K-Means MapReduce algo-
rithm is an iterative MapReduce algorithm, you execute it many times (with
diﬀerent centroids) until it converges (meaning that all optimal K clusters are
found after many iterations of the same MapReduce job).

What is clustering? What is K-Means? In a nutshell, we can say that

• clustering is the process of grouping a set of d-dimentional (2-dimentional,

3-dimentional, ...) objects into clusters of similar objects, and

• objects should be similar to one another within the same cluster and

dissimilar with those in other clusters.

K-Means is a distance-based clustering algorithm. K-Means clustering has
many useful applications. For example, it can be used to ﬁnd a group of
consumers with common behaviors, or to cluster documents based on simi-
larity of their contents. The ﬁrst question is how do we determine the value
of K as the number of groups or clusters we want to generate from our input
data? Selection of K is speciﬁc to the application or problem domain you
are trying to solve. There is no magic formula to ﬁnd K.

An example of a K-Means for K = 3 is given below. The ﬁrst image
shows the raw data. The second image shows an application of K-Means. In

308

Figure 12.1: Raw Data

the second image, the red points represents the ﬁrst cluster and black points
represent the second cluster, and ﬁnally the green points represent the third
cluster. The goal of K-Means is how to convert the raw data (ﬁrst image)
into clusters (second image).

How does K-Means work? This is how it works: the algorithm is given as
inputs a set of N d-dimensional points and a number of desired clusters K.
For the simpliciy, we will consider points in a Euclidean space. However,
the K-Means clustering algorithm will work in any space provided a distance
metric is given as input as well. Therefore, our input of N (we use n and N
interchangeably here) d-dimensional points will be:

p1 = (a11, a12, ..., a1d)
p2 = (a21, a22, ..., a2d)

309

Figure 12.2: Clustered Data

310

...
pn = (an1, an2, ..., and)

For example, in a 2-dimentional environment, our input data can be as

follows, where each row represents a point (x, y) in a 2-dimentional space:

p1 = (1,1)
p2 = (2,1)
p3 = (1,2)
p4 = (5,5)
p5 = (6,5)
p6 = (5,6)
p7 = (7,7)
p8 = (9,6)

Initially, K points are chosen as cluster centers; these are called cluster
centroids. There are many ways to initialize the cluster centroids: one way
is to choose the K points randomly from the sample of n points. Once the
K initial cluster centroids are chosen, the distance is calculated from every
point in the input set to each of the K centers and then each point is assigned
to the speciﬁc cluster center whose distance is closest. When all objects have
been assigned, then again we recalculate the positions of the K centroids.
The above two steps are repeated until the cluster centroids no longer change
(or change very little).

Before we present our MapReduce solution, we will look at the basic def-
inition of K-Means clustering and then we will brieﬂy focus on informal and
formal algorithms of K-Means clustering.The better we understand K-Means
clustering, then it will be easier to comprehend the MapReduce solution.

12.2 What is K-Means Clustering

What is K-Means Clustering? In a nutshell, K-Means Clustering (unsuper-
vised learning) is a data mining algorithm to cluster, classify or to group your
N objects based on their attributes or features into K number of groups (so
called clusters). K is a positive integer number (K = 2, 3, 4, ...). If we apply

311

K-Means to a set of N objects, then the result will be K disjoint groups
(adding all objects in K groups will result in N objects). The next question
is how do we group these N objects into K disjoint groups? The grouping
is done by minimizing the sum of squares of distances between data and the
corresponding cluster centroid. The next two questions are: why do we use
clustering? and how to ﬁnd cluster centroids? The simple answer is: we
use K-Mean clustering to classify the data (for example to classify student’s
grades into 5 categories (K = 5): A (excellent), B (good), C (average), D
(poor), and F (failure). Another example will be: use K-Means to predict
student academic performance[22]. I will return to the question of ”how to
ﬁnd cluster centroids” in the next sections.

Next, we formalize the K-Means clustering. Given n d-dimentional points:

X1 = (x11, x12, ..., x1d)
X2 = (x21, x22, ..., x2d)
...
Xn = (xn1, xn2, ..., xnd)

The goal is to partition these {X1, X2, ..., Xn} into k clusters: {C1, C2, ..., Ck}.
K-means aims to ﬁnd the positions µi (i=1,...,k) of the clusters that minimize
the distance from the data points to the cluster. K-means clustering solves
the following cost minimization algorithm:

arg min
C

k
(cid:88)

(cid:88)

i=1

Xj∈Ci

(cid:13)
(cid:13)
(cid:13)Xj − µi

2
(cid:13)
(cid:13)
(cid:13)

where µi is the mean of points in Ci.

12.3 What are the Applications of Cluster-

ing?

Clustering algorithms have many possible applications. The following are
partial list of clustering applications:

312

• Marketing: Given a lage set of customer transactions, ﬁnding groups

of customers with similar purchase behaviors

• Document classiﬁcation: clustering web log data to discover groups of

similar access patterns.

• Insurance: identifying groups of vehicle insurance policy holders with

a high average claim cost; identifying frauds;

12.4 K-Means Clustering Method: Partition-

ing Approach

K-Means clustering algorithm is an iterative algorithm. In subsequent sec-
tions, I will provide a MapReduce algorithm, which we will continue running
until the K-Means clustering algorithm converges by ﬁnding a proper optimal
solution. Informally, we can state K-Means Clustering algorithm as:

Given a set of N objects, which has to be grouped into K clusters, the
k-means algorithm performs the following steps:

Step-1: Partition N objects into K no-nempty subsets

Step-2: Compute the centroids of the clusters in the current partition (the
centroid is the center, i.e., mean point, of the cluster). For all i =
1, 2, ..., k compute µi as:

µi =

1
|ci|

(cid:88)

j∈ci

¯j, ∀i
x

Step-3: Assign each object to the cluster with the nearest centroid. This is

simply attributing the closest cluster to each data point:

ci = {j : d(xj, µi) ≤ d(xj, µl), l (cid:54)= i, j = 1, ..., n}

where d(a, b) is the distance function for two points: a and b.

Step-4: Stop when no more new assignments. Otherwise go back to Step-2.

Basically, we repeat steps Steps 2-3 until convergence.

313

Basically, the algorithm iterates until there are no changes in the cen-
troids; and when there are no changes in the centroids, then we have found
our K clusters. K-Means algorithm is an iterative process, which means that
at each step the membership of each object in a cluster is re-evaluated based
on the current centers of each existing cluster. This process is repeated until
the desired number of clusters (or the number of objects) is reached.

12.5 K-Means Distance Function

The ﬁrst step of the K-Means clustering algorithm involves exclusive assign-
ment of data points to the closest cluster centroids. For a given data point
(of d-dimensions), how do we determine the closest cluster centroid? For
this purpose, we use a distance function, which calculates how probable (or
likely) that the centroid generated the data point. There are many distance
functions (few are mentioned here):

• Euclidean Distance

• Manhattan Distance

• Inner Product Space

• Maximum Norm

• Your Own Custom Function (any metric you deﬁne over the d-dimentional

space)

For example, Euclidean distance have been used in many K-Means algo-
rithms. The Euclidean distance between two data point instances X and
Y which are represented by d continuous attributes (d-dimensional) is:

Let

Then

X = (X1, X2, ..., Xd)
Y = (Y1, Y2, ..., Yd)

b

distance(X, Y) =

(X1 − Y1)2 + (X2 − Y2)2 + ... + (Xd − Yd)2

314

The Euclidean distance function has some interesting properties:

• distance(i,j) ≥ 0

• distance(i,i) = 0

• distance(i,j) = distance(j,i)

• distance(i,j) ≤ distance(i,k) + distance(k,j)

For example, Euclidean distance function can be expressed in Jave-like as:

public class EuclideanDistance {

// Let Vector[i] be the i’th position of the Vector
public static double calculateDistance(Vector center, Vector data) {

double sum = 0.0;
// center.length = data.length
int length = center.length;
for (int i = 0; i < length; i++) {

sum += Math.pow((center[i] - data[i]), 2.0);

}

return Math.sqrt(sum);

}

}

When implementing K-Means, we have to make sure that our algorithm
converges and we can properly calculate ”mean” and ”distance” functions
properly over the space we have.

12.6 K-Means Clustering Step-by-Step Exam-

ple

12.7 K-Means Clustering Formalized

K-Means is a simple learning algorithm for clustering analysis. The goal
of K-Means clustering algorithm is to ﬁnd the best division of n entities –
so called objects or points–in k groups, so that the total distance between

315

the group’s members and its corresponding centroid, representative of the
group, is minimized. Formally, the goal is to partition the n entities into k
sets {Si, i = 1, 2, ..., k} in order to minimize the within-cluster sum of squares
(WCSS), deﬁned as:

min

k
(cid:88)

n
(cid:88)

j=1

i=1

(cid:107) x

j
i − cj (cid:107)

where term (cid:107) x

j
i − cj (cid:107) provides the distance between an entity point

and the cluster’s centroid.

12.8 MapReduce Solution for K-Means Clus-

tering

MapReduce solution for K-Means clustering is an iterative solution, where
each iteration is implemented as a MapReduce job. K-Means needs an itera-
tive version of MapReduce, which is not an standard formulation of MapRe-
duce paradigm. To implement an iterative MapReduce soultion, we do need
a driver or control program on the client side to initialize the K centroid
positions, call the iteration of MapReduce jobs and determine whether the
iteration should continue or end. The mapper needs to fetch the data point
and all cluster centroids; the cluster centroids have to be shared among all
mappers. This can be done in many diﬀerent ways by using HDFS or a global
data structure server like Redis or memcached. The reducer recomputes new
means.

Note that each iteration of the algorithm is structured as a single MapRe-
duce job, which iteratively improves partitioning of data into k clusters. The
overall MapReduce pseudo code solution is illustrated below. The change()
function is used to terminate the MapReduce iteration when there is not
much change in centroids.

The pseudocode of the K-Means algorithm is shown below.

Listing 12.1: K-Means Algorithm

316

1 // k = number of desired clusters
2 // delta = acceptable error for convergence
3 // data = input data
4 kmeans(k, delta, data) {
5

// initialize the cluster centroids
initial_centroids = pick(k, data);

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 }

// this is how we broadcast centers to mappers
writeToHDFS(initial_centroids);

// iterate as long as necessary
current_centroids = initial_centroids;
while (true) {

1. uses current_centroids in map()
2. reduce() creates new_centroids and write it to HDFS

// map_reduce_job() does 2 tasks:
//
//
map_reduce_job();
new_centroids = readFromHDFS();
if change(new_centroids, current_centroids) <= delta {

// we are done, terminate loop-iteration
break;

}
else {

current_centroids = new_centroids;

}

}

result = readFromHDFS();
return result;

The change() method is presented below:

Listing 12.2: K-Means Algorithm: change() Method

1 change(new_centroids, current_centroids) {
2

new_distance = [sum of squared distance in the new_centroids];
current_distance = [sum of squared distance in the current_centroids];
changed = absoulteValue(new_distance - current_distance);
return changed;

3

4

5
6 }

The next three subsections provide the details of verb—map reduce job()—

(as a MapReduce job). The MapReduce job will have 3 functions: map(),
combine(), and reduce().

317

12.8.1 MapReduce Solution: map()

The map() function classiﬁes data. It uses the cluster centroids and assigns
each point p ∈ 1, 2, ..., n to the nearest center. Note that in the ﬁrst iteration,
the centroids will be the ones selected at random or created manually. The
map() accepts in-points in the data set and outputs one (Cluster-ID, Vector)
pair for each point, where the Cluster-ID is the integer ID of the cluster
which is closest to the point and Vector is a d-dimensional vector (array of
double data type).
The map() function is summarized below:

• Read the cluster centroids into memory from a SequenceFile1 (note
that we may also use Redis or memcached for persisting cluster cen-
troids). In Hadoop’s implementation, this will be done in the setup()
method of the mapper class.

• Iterate over each cluster centroid for each input key-value pair.

In
Hadoop’s implementation, for the map() function, key is generated by
Hadoop and ignored (not used)

• Compute the Euclidean distances and save the nearest center which
has the lowest distance to the input point (as a d-dimensional vector)

• Write the key − value pair to be consumed by reducers, where key is
the nearest cluster center with its input point (a d-dimensional vector
as a value). Both, key and value are Vector (as a d-dimensional vector)
type.

Listing 12.3: K-Means MapReduce: map()

1 public class KmeansMapper ... {
2

3

4

5

6

7

8

9

10

11

12

private List<Vector> centers = null;

private List<Vector> readCentersFromSequenceFile() {
// read cluster cntroids from a SequenceFile,
// which is a set of key-value pairs
...

}

// called once at the beginning of the map task
public void setup(Context context) {

1org.apache.hadoop.io.SequenceFile

318

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

this.centers = readCentersFromSequenceFile();

}

/**

* @param key is MapReduce generated, ignored here
* @param value is the d-dimentional Vector (V1, V2, ..., Vd)
*/

map(Object key, Vector value) {

Vector nearest = null;
double nearestDistance = Double.MAX_VALUE;
for (Vector center : centers) {

double distance = EuclideanDistance.calculateDistance(center, value);
if (nearest == null) {

nearest = center;
nearestDistance = distance;

}
else {

if (nearestDistance > distance) {

nearest = center;
nearestDistance = distance;

}

}

}

// prepare key-value for reducers
emit(nearest, value);

}

40
41 } // end of class KmeansMapper

12.8.2 MapReduce Solution: combine()

After each map task, a combiner is applied to mix the intermediate data of
the same map task. The combiner sums up the values–the sum is needed
for computing the mean values–for each dimension of vector objects. In the
combine() function, we partially sum the values of the points (as vectors)
assigned to the same cluster. The combiner function improves the eﬃciency
of our algorithm by avoiding network traﬃc by transferring less data between
slave nodes.

Listing 12.4: K-Means MapReduce: combine()

1 /**
2

3

* @param key is the Centroid
* @param values is a list of Vector
*/

4
5 combine(Vector key, Iterable<Vector> values) {
6

// all dimentions in sum Vector are initialized to 0.0
Vector sum = new Vector();

7

319

for (Vector value : values) {

// note that value.length = d,
// where d is the number of dimensions for input objects
for (int i = 0; i < value.length; i++) {

sum[i] += value[i];

}

}

8

9

10

11

12

13

14

15

emit(key, sum);

16
17 }

12.8.3 MapReduce Solution: reduce()

The reducer does re-centering: it re-creates the centroids for all clusters by
recalcluating the means for all clusters.
In reduce phase, the outputs of
the map() functions are grouped by Cluster-ID, and for each Cluster-ID the
centroid of the points associated with that Cluster-ID is calculated. Each
reduce function generates (Cluster-ID, Centroid) pairs, which represent the
newly calculated cluster centers.
The reduce() function is summarized below:

• The main task of the reduce() function is to re-center.

• Each reducer, iterates over each value vector and calculate the mean
vector. Once you have found the mean, then this is the new center;
ﬁnally save it into a SequenceFile.

Listing 12.5: K-Means MapReduce: reduce()

1 /**
2

3

* @param key is the Centroid
* @param values is a list of Vector
*/

4
5 reduce(Vector key, Iterable<Vector> values) {
6

// all dimentions in newCenter are initialized to 0.0
Vector newCenter = new Vector();
int count = 0;
for (Vector value : values) {

count++;
for (int i = 0; i < value.length; i++) {

newCenter[i] += value[i];

}

}

for (int i = 0; i < key.length; i++) {
// set new mean for each dimension
newCenter[i] = newCenter[i] / count;

320

7

8

9

10

11

12

13

14

15

16

17

18

}

emit(key.ID, newCenter);

19

20

21
22 }

12.9 MapReduce K-Means Clustering Step-

by-Step Example

12.10 K-Means Implementation by Spark

Spark framework provides some common machine learning (ML) functional-
ity, called MLlib. Spark’s MLlib2 supports the following types of machine
learning algorithms:

• binary classiﬁcation

• regression

• clustering (includes K-Means)

• collaborative ﬁltering

• gradient descent optimization primitive.

Spark’s MLlib supports M-Means clustering, that clusters the data points
into predﬁned number of clusters. The MLlib implementation includes a
parallelized variant of the k-means++ (new algorithm for ﬁnd the centroids)
method called kmeans|| (parallel implementation of K-Means algorithm).
Spark’s implementation of K-Means has the following parameters:

• k is the number of desired clusters.

• maxIterations is the maximum number of iterations to run.

• initializationMode speciﬁes either random initialization or initial-

ization via kmeans||.

2http://spark.apache.org/docs/0.9.1/mllib-guide.html

321

• runs is the number of times to run the k-means algorithm (note that
k-means is not guaranteed to ﬁnd a globally optimal solution, and when
run multiple times on a given dataset, the algorithm returns the best
clustering result).

• initializiationSteps determines the number of steps in the kmeans||

algorithm.

• epsilon determines the distance threshold within which we consider

k-means to have converged.

Sample implementation of K-Means is given by Spark as a JavaKMeans3
class. Below, we present JavaKMeans class, and then we will show a sample
run.

Listing 12.6: Example using MLLib KMeans from Java

1 package org.apache.spark.examples.mllib;
2
3 import java.util.regex.Pattern;
4 import org.apache.spark.SparkConf;
5 import org.apache.spark.api.java.JavaRDD;
6 import org.apache.spark.api.java.JavaSparkContext;
7 import org.apache.spark.api.java.function.Function;
8 import org.apache.spark.mllib.clustering.KMeans;
9 import org.apache.spark.mllib.clustering.KMeansModel;
10 import org.apache.spark.mllib.linalg.Vector;
11 import org.apache.spark.mllib.linalg.Vectors;
12
13 /**
14

* Example using MLLib KMeans from Java.
*/

15
16 public final class JavaKMeans {
17

18

19

20

21

22

23

24

25

26

27

28

29

30

private static class ParsePoint implements Function<String, Vector> {

private static final Pattern SPACE = Pattern.compile(" ");
@Override
public Vector call(String line) {

String[] tok = SPACE.split(line);
double[] point = new double[tok.length];
for (int i = 0; i < tok.length; ++i) {

point[i] = Double.parseDouble(tok[i]);

}
return Vectors.dense(point);

}

}

3org.apache.spark.examples.mllib.JavaKMeans

322

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

public static void main(String[] args) {

if (args.length < 3) {
System.err.println(

"Usage: JavaKMeans <input_file> <k> <max_iterations> [<runs>]");

System.exit(1);

}
String inputFile = args[0];
int k = Integer.parseInt(args[1]);
int iterations = Integer.parseInt(args[2]);
int runs = 1;

if (args.length >= 4) {

runs = Integer.parseInt(args[3]);

}

SparkConf sparkConf = new SparkConf().setAppName("JavaKMeans");
JavaSparkContext sc = new JavaSparkContext(sparkConf);
JavaRDD<String> lines = sc.textFile(inputFile);
JavaRDD<Vector> points = lines.map(new ParsePoint());
KMeansModel model = KMeans.train(points.rdd(), k, iterations, runs, KMeans.K_MEANS_PARALLEL());

System.out.println("Cluster centers:");
for (Vector center : model.clusterCenters()) {

System.out.println(" " + center);

}
double cost = model.computeCost(points.rdd());
System.out.println("Cost: " + cost);

sc.stop();

}

60
61 }

Some of the key points of the JavaKMeans class are discussed below:

• Line 47: create JavaSparkContext object, which is a connection object
to a Spark master and an entry point to run jobs in Spark cluster

• Line 48: read input ﬁle (as record of strings) and create a new JavaRDD<String>

( a set of String objects)

• Line 49: Convert and tokenize each string record in JavaRDD<String>
to a Vector of doubles. This is accomplished by using ParsePoint
class, which takes a String object and converts it to a Vector of dou-
bles.

• Line 50: The K-Means algorithm is called by the KMeans4 class, which
generates a KMeansModel5 (a clustering model for K-means, where each

4org.apache.spark.mllib.clustering.KMeans
5org.apache.spark.mllib.clustering.KMeansModel

323

point belongs to the cluster with the closest center).

• Lines 52-57: prints the results

12.10.1 Sample Run of K-Means by Spark

MP TBDL

1. Dependencies
MLlib uses the jblas linear algebra library, which itself depends on
native Fortran routines. You may need to install the gfortran runtime
library if it is not already present on your nodes. MLlib will throw a
linking error if it cannot detect these libraries automatically.

2. yum install gcc-gfortran

324

nctions

325

Chapter 13

kNN: k-Nearest-Neighbors

13.1

Introduction

This chapter focuses on one of important machine learning algorithms, called
k-nearest-neighbors (kNN), where k is an integer number greater than 0. The
kNN classiﬁcation problem is to ﬁnd the k-nearest data points in a dataset
(so called training dataset) to a given query data point. K-Nearest-Neighbors
is the same as ”kNN join”. The kNN join can be deﬁned as: given two data
sets R and S, the goal is to ﬁnd k nearest neighbors from a dataset S
for every object in dataset R. In data mining, R and S are called query and
training datasets respectively. Training dataset (S) refers to data, which has
already been classiﬁed and query dataset (R) refers to data, which is going
to be classiﬁed using S’s classiﬁcations.

The objective of this chapter is to present MapReduce solution (using
Spark/Hadoop) for kNN (especially for kNN join algorithm). The kNN algo-
rithm has been discussed extensively in many machine learning books such as
Machine Learning for Hackers[?] and Machine Learning in Action[11]. kNN
is an important clustering algorithm, which has many applications in a wide
range of data mining (such as pattern recognition) and bioinformatics (such
as Breast Cancer Diagnosis Problem[23], Weather Generating Model[?], and
product recommender systems. The kNN algorithm can be fairly expensive
especially when we have a large training set and this is why MapReduce
solution will be suitable for handling large training data set.

What is kNN? Nearest Neighbor analysis is an algorithm for classifying

326

n-dimensional objects1 based on their similarity to other n-dimensional ob-
jects.
In machine learning, Nearest Neighbor analysis has been developed
as a way to recognize patterns of data without requiring an exact match to
any stored patterns or objects. Similar n-dimensional are near each other
and dissimilar n-dimensional are distant from each other. Thus, the distance
between two cases is a measure of their dissimilarity. According to wikipedia:
”In pattern recognition, the k-nearest neighbor algorithm (kNN) is a non-
parametric method for classifying objects based on closest training examples
in the feature space. kNN is a type of instance-based learning, or lazy learn-
ing where the function is only approximated locally and all computation is
deferred until classiﬁcation. The k-nearest neighbor algorithm is amongst
the simplest of all machine learning algorithms: an object is classiﬁed by a
majority vote of its neighbors, with the object being assigned to the class
most common amongst its k nearest neighbors (k is a positive integer, typ-
ically small). If k = 1, then the object is simply assigned to the class of its
nearest neighbor.”

13.2 kNN Classiﬁcation

What is the main idea behind the kNN? The central idea of kNN is to
build a classiﬁcation method by using no assumptions about the form of the
”smooth” function f :
x = (x1, x2, ..., xn)
y = f (x)
that relates y (the response variable) to the x (predictor variables). Function
f is a non-parametric method because it does not involve estimation of pa-
rameters in any form or shape. In kNN, given a new point p = (p1, p2, ..., pn),
we dynamically identify k observations in the training dataset that are sim-
ilar to p (k nearest neighbor). In kNN, neigbors are deﬁned by a distance or
dissimilarity measure that we can compute between observations based on
the independent variables. For simplicity, we will use the Euclidean distance.
The Euclidean distance between the points (x1, x2, ..., xn) and (p1, p2, ..., pn)
is deﬁned as:

1An n-dimensional object x, which has n attributes, will be represented as

(x1, x2, ..., xn)

327

b

(x1 − p1)2 + (x2 − p2)2 + ... + (xn − pn)2

The question is how do you ﬁnd k nearest neighbors?. For each queried
n-dimensional object (an object which has n attributes), the Euclidean dis-
tances between the queried object and all the training data objects are cal-
culated and the queried object is assigned the class label that most of the
k closest training data have. Note that the kNN algorithm assumes that
all data correspond to n-dimensional metric (denoted by Rn) space, which
means that the data type of all attributes are "double." This is required
since we need to calculate the Euclidean distance between n-dimensional ob-
jects.

13.3 Distance Functions

The Euclidean distance function have been used in many data mining cluster-
ing algorithms. The Euclidean distance between two n-dimentional objects
X and Y are given below. Let X and Y deﬁned as:

X = (X1, X2, ..., Xn)
Y = (Y1, Y2, ..., Yn)

Then distance(X, Y) is deﬁned as:
b

distance(X, Y ) =

(cid:80)n

i=1(Xi − Yi)2

b

distance(X, Y ) =

(X1 − Y1)2 + (X2 − Y2)2 + ... + (Xn − Yn)2

Note that the Euclidean distance function will work only for metric data,
where all attributes have ”double” primitive data type. What if our at-
tributes are non-numeric. Take for example, ”big spender,” ”medium spender,”
”small spender,” and ”non spender.” Then we need to come up with custom
distance functions so that we can accommodate all diﬀerent data types. In
this case we need to answer distance ("big spender," "small spender")
and so on. Most of the time in real applications we do need custom distance
functions.

There are other distance functions available for kNN:

328

• Manhattan:

• Minkowski:

n
(cid:88)

|Xi − Yi|

i=1

˜g
f
f
e

n
(cid:88)

i=1

¸

1/q

¯
´
q
|Xi − Yi|

13.4 kNN Example

The kNN algorithm is an inituitive method which classiﬁes unclassiﬁed data
(called an input query) based on its similarity or distance with the data in
the training dataset. For example, let our training dataset to have 4 classes
identiﬁed as {C1, C2, C3, C4} as illustrated below:

Given k=6 and X = (X1, X2, ..., Xn), the goal is to ﬁnd a class label
from {C1, C2, C3, C4} for the unknown data X. As you can observe from
the above ﬁgure example, of the 6 (k=6) closest neighbors, 4 belongs to C1, 1
belong to C2, 1 belong to C3, and , 0 belong to C4. Therefore, by a majority
vote, X is assigned to C1, which is a predominant class.

13.5 An Informal kNN Algorithm

kNN algorithm can be summarized in the following simple steps:

• Step-1: determine k (selection of k depends on your data and project

requirements – there is no magic formula for k’s selection)

• Step-2: calculate the distances between the new input and all the train-
ing data (selection of a distance function also depends on type of data)

• Step-3: sort the distance and determine k nearest neighbors based on

the k-th minimum distance.

• Step-4: gather the categories of those neighbors.

• Step-5: determine the category based on majority vote

329

Figure 13.1: kNN Classiﬁcation with 4 Classes {C1, C2, C3, C4}

330

13.6 Formal kNN Algorithm

To deﬁne kNN algorithm in formal terms, we need some deﬁnitions.

Distance Function : The distance function depends on application do-
main, but most of the time the Euclidean distance function works for
most of metric data. The distance between two points (x1, x2, ..., xn)
and (y1, y2, ..., yn) is deﬁned as: |x, y|.

k Nearest Neighbors Given an object q (called a query object), a training
dataset S and an integer k, the k nearest neighbors of q from S, denoted
as kNN(q, S), is a set of k objects from S such that

∀o ∈ kNN(q, S), ∀s ∈ {S − kNN(q, S)}, |o, q|≤ |s, q|

kNN Join Given two data sets R and S (where S is a training dataset), and

an integer k, then kNN join of R and S is deﬁned as:

kNNjoin(R, S) = {(r, s)|∀r ∈ R, ∀s ∈ kNN(r, S)}

Basically, this combines each object r ∈ R with its k Nearest Neighbors
from S.

13.6.1 Java-like Non-MapReduce Solution for kNN

Given K > 0, query set (this is the data that we want to classify), and
training set (this is the training data that we know classiﬁcation of its data
objects), we provide a Java-like non-MapReduce solution for kNN clustering
algorithm. Below, P oint class is used to reprsent an n-dimensional data.

Listing 13.1: Classify Method

* Classify queried data using kNN Analysis
* @param k an integer > 0
* @param querySet a set of data objects that we want to classify
* @param trainingSet a set of training data (already classified)
*/

6
7 public static void classify(int k,
8

Point[] querySet,
Point[] trainingSet) {

1 /**
2

3

4

5

9

10

11

foreach (Point query : querySet) {
knn(k, query, trainingSet);

}

12
13 }

331

The kNN algorithm (non-MapReduce version) is illustrated below:

Listing 13.2: kNN Algorithm

1 /**
2

3

4

5

* kNN Analysis
* @param k an integer > 0
* @param query a data object that we want to classify
* @param trainingSet a set of training data (already classified)
*/

6
7 public static void knn(int k,
8

Point query,
Point[] trainingSet) {

foreach (Point training : trainingSet) {

// Create a fixed sized sorted map of length k,
// where we map the distance to a training point.
SortedMap<Double, Point> map = new TreeMap<Double, Point>(k);

// Calculate distance of test point to training point.
double d = calculateEuclidianDistance(query, training);

// Insert training point into sorted list, discarding
// if training point not within k nearest neighbours
// to query point.
map.put(d, training);

}

// Do majority vote on k nearest neighbours
// and assign the corresponding label to the
// query point.
query.label = majorityVote(map, k);

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27
28 }

Below is the deﬁnition of the Euclidean distance function:

Listing 13.3: Euclidean distance function

1 /**
2

3

4

* @param query an n-dimensional query data object
* @param reference an n-dimensional reference data object
* @return the quadratic Euclidean distance.
*/

5
6 public static double calculateEuclidianDistance(Point query,
7

Point reference) {

8

9

10

11

12

13

14

15

16

double sum = 0.0;

// n is the number of dimensions in the vector
// space. here n is equal to query.length, which
// is equal to reference.length
int n = query.length; // which is equal to

for (int i = 0; i < n; i++) {

double difference = reference.vector[i] - query.vector[i];

332

sum += difference * difference;

}

return Math.sqrt(sum);

17

18

19

20
21 }

13.7 kNN Implementation in Spark

Given two data sets R and S, the goal is to ﬁnd k nearest neighbors from
a dataset S for every object in dataset R. In data mining, S is called a
training dataset. The complexity of this kNN join algorithm is N 2, because
for every object r in R, you want to calculate distance(r, s) for every s
in S. Finding distance(r, s) requires the Cartesian product of R and S.
Spark provides higher level API to perform a Cartesian product between two
data sets. For example, JavaPairRDD.cartesian(JavaPairRDD) ﬁnds the
cartesian product of two data sets. The signature of cartesian() is deﬁned
as:

<U> JavaPairRDD<T,U> cartesian(JavaRDDLike<U,?> other)

Description: Return the Cartesian product of this RDD
and another one, that is, the RDD of all pairs of elements
(a, b) where a is in this and b is in other.

For example, the following example shows how to perform cartesian product
of two data sets in Spark:

// data set R
List<Tuple2<String,String>> listR = new ArrayList<Tuple2<String,String>>();
listR.add(new Tuple2<String,String>("r1", "R1"));
listR.add(new Tuple2<String,String>("r2", "R2"));
listR.add(new Tuple2<String,String>("r3", "R3"));

// data set S
List<Tuple2<String,String>> listS = new ArrayList<Tuple2<String,String>>();
listS.add(new Tuple2<String,String>("s1", "S1"));
listS.add(new Tuple2<String,String>("s2", "S2"));
listS.add(new Tuple2<String,String>("s3", "S3"));

333

listS.add(new Tuple2<String,String>("s4", "S4"));

JavaPairRDD<String,String> R = ctx.parallelizePairs(listR);
JavaPairRDD<String,String> S = ctx.parallelizePairs(listS);

// perform the Cartesian product of this R and S
JavaPairRDD<Tuple2<String,String>, Tuple2<String,String>> cart = R.cartesian(S);

// save output
cart.saveAsTextFile("/output/z");

The output of cartesian product of R and S are shown below.

# hadoop fs -cat /output/z/part*
((r1,R1),(s1,S1))
((r1,R1),(s2,S2))
((r1,R1),(s3,S3))
((r1,R1),(s4,S4))
((r2,R2),(s1,S1))
((r2,R2),(s2,S2))
((r2,R2),(s3,S3))
((r2,R2),(s4,S4))
((r3,R3),(s1,S1))
((r3,R3),(s2,S2))
((r3,R3),(s3,S3))
((r3,R3),(s4,S4))

13.7.1 Formalizing kNN for Spark Implementation

Let R (called query data set) and S (called training data set) be d-dimensional
data sets, which we want to ﬁnd the kNN(R, S). Further assume that all
training data (S) has been classiﬁed into C = {C1, C2, ...}, where C denotes
all available classiﬁcations. We deﬁne R, S, and C as:

• R = {R1, R2, ..., Rm}
• S = {S1, S2, ..., Sn}
• C = {C1, C2, ..., Cp}

334

where

• Ri = (ri, a1, a2, ..., ad)
• Sj = (sj, b1, b2, ..., bd, Cj)
• ri is a unique record ID for Ri
• a1, a2, ..., ad are attributes of Ri
• sj is a unique record ID for Sj
• b1, b2, ..., bd are attributes of Sj
• Cj is a classiﬁcation identiﬁer for Sj

The goal is to ﬁnd kNN(R, S). To ﬁnd this, we will perform a cartesian
product of R and S, and then group the data by ri ( a unique record ID
for Ri). After grouping, we will ﬁnd the k-nearest-data-points from
S (by sorting distances ascendingly and then picking the ﬁrst k elements).
Once the k-nearest-data-points from S are found, then we will select the
classiﬁcation by a majority rule.

13.7.2

Input Data Set Formats

We are assuming that R and S both represent d-dimensional data points.
The input record for query data set (R) will have the following format:

<unique-record-id><;><a-1><,><a-2><,>...<,><a-d>

The input record for training data set (S) will have the following format:

<unique-record-id><;><classification-id><;><b-1><,><b-2><,>...<,><b-d>

335

Figure 13.2: kNN Implementation in Spark

336

13.7.3 kNN Implementation in Spark

13.7.3.1 High Level Steps

Listing 13.4: High Level Steps

1 // STEP-0: Import required classes and interfaces
2
3 public class kNN {
4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

static JavaSparkContext createJavaSparkContext() throws Exception {...}
static List<Double> splitOnToListOfDouble(String str, String delimiter) {...}
static double calculateDistance(String rAsString, String sAsString, int d) {...}
static SortedMap<Double, String> findNearestK(Iterable<Tuple2<Double,String>> neighbors, int k) {...}
static Map<String, Integer> buildClassificationCount(Map<Double, String> nearestK) {...}
static String classifyByMajority(Map<String, Integer> majority) {...}

public static void main(String[] args) throws Exception {

// STEP-1: Handle input parameters
// STEP-2: Create a Spark context object
// STEP-3: Broadcast shared objects
// STEP-4: Create RDDs for query and training datasets
// STEP-5: Perform cartesian product of (R, S)
// STEP-6: Find distance(r, s) for r in R and s in S
// STEP-7: Group distances by r in R
// STEP-8: find the k-nearest-neigbors and classify r
System.exit(0);

}

22
23 }

13.7.3.2 STEP-0: Import required classes and interfaces

Most of the Spark classes and interfaces are imported from two packages:
org.apache.spark.api.java and org.apache.spark.api.java.function.
The Broadcast class is used to broadcast shared objects and data structures
to all cluster nodes (this is similar to Hadoop’s Configuration object which
you can set() and get() objects in mappers and reducers).

Listing 13.5: STEP-0: Import required classes and interfaces

1 // STEP-0: Import required classes and interfaces
2 import scala.Tuple2;
3 import org.apache.spark.SparkConf;
4 import org.apache.spark.broadcast.Broadcast;
5 import org.apache.spark.api.java.JavaRDD;
6 import org.apache.spark.api.java.JavaPairRDD;
7 import org.apache.spark.api.java.JavaSparkContext;
8 import org.apache.spark.api.java.function.Function;

337

9 import org.apache.spark.api.java.function.PairFunction;
10
11 import java.util.Map;
12 import java.util.HashMap;
13 import java.util.SortedMap;
14 import java.util.TreeMap;
15 import java.util.List;
16 import java.util.ArrayList;
17 import com.google.common.base.Splitter;

13.7.3.3 High Level Steps

The createJavaSparkContext() method creates an instance of a JavaSpark-
Context objects, which is a factory class for creating RDDs. Notes that I
have hard coded the YARN’s resource manager (as myserver100), but for
production deployment, you should read and load all your conﬁgurations
from a conﬁguration ﬁle (such as XML).

Listing 13.6: Create a Spark context Object

static JavaSparkContext createJavaSparkContext() throws Exception {

SparkConf conf = new SparkConf();
conf.set("yarn.resourcemanager.hostname", "myserver100");
conf.set("yarn.resourcemanager.scheduler.address", "myserver100:8030");
conf.set("yarn.resourcemanager.resource-tracker.address", "myserver100:8031");
conf.set("yarn.resourcemanager.address",
conf.set("mapreduce.framework.name", "yarn");
conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
conf.set("spark.executor.memory", "1g");
JavaSparkContext ctx = new JavaSparkContext("yarn-cluster", "kNN", conf);
return ctx;

"myserver100:8032");

}

13.7.3.4 Method splitOnToListOfDouble()

The splitOnToListOfDouble() method accepts all attributes as a String
object and returns a List<Double>.

Listing 13.7: Method splitOnToListOfDouble()

/**

* @param str a comma (or semicolon) separated list of double values
* str is like "1.1,2.2,3.3" or "1.1;2.2;3.3"
*
* @param delimiter a delimiter such as ",", ";", ...

338

1

2

3

4

5

6

7

8

9

10

11

12

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

* @return a List<Double> (all attributes for a dataset record)
*/
static List<Double> splitOnToListOfDouble(String str, String delimiter) {

Splitter splitter = Splitter.on(delimiter).trimResults();
Iterable<String> tokens = splitter.split(str);
if (tokens == null) {

return null;

}
List<Double> list = new ArrayList<Double>();
for (String token: tokens) {

double data = Double.parseDouble(token);
list.add(data);

}
return list;

}

13.7.3.5 Method calculateDistance()

The calculateDistance() accepts two vectors of R and S and computes
the Euclidean distance between them. The Euclidean distance between
two points r = (r1, r2, ..., rd) and s = (s1, s2, ..., sd) is deﬁned as

b

distance(r, s) =

(r1 − s1)2 + (r2 − s2)2 + ... + (rd − sd)2

Based on your project and data requirements, you may select and use

other distance functions2.

Listing 13.8: Method calculateDistance()

/**

* @param rAsString = "r.1,r.2,...,r.d"
* @param sAsString = "s.1,s.2,...,s.d"
* @param d dimension of R and S
*/

static double calculateDistance(String rAsString, String sAsString, int d) {

List<Double> r = splitOnToListOfDouble(rAsString, ",");
List<Double> s = splitOnToListOfDouble(sAsString, ",");

// d is the number of dimensions in the vector
if (r.size() != d) {

return Double.NaN;

}
if (s.size() != d) {

return Double.NaN;

}

2For details on distance functions, refer to http://www.saedsayad.com/k_nearest_

neighbors.htm

339

18

19

20

21

22

23

24

25

// here we have (r.size() == s.size() == d)
double sum = 0.0;
for (int i = 0; i < d; i++) {

double difference = r.get(i) - s.get(i);
sum += difference * difference;

}
return Math.sqrt(sum);

}

13.7.3.6 Method ﬁndNearestK()

Given {(distance, classification)}, it ﬁnds the k-nearest-neighbors based
on the distance.

Listing 13.9: Method buildClassiﬁcationCount()

1 static SortedMap<Double, String> findNearestK(Iterable<Tuple2<Double,String>> neighbors, int k) {
2

// keep only k-nearest-neighbors
SortedMap<Double, String>
for (Tuple2<Double,String> neighbor : neighbors) {

nearestK = new TreeMap<Double, String>();

3

4

5

6

7

8

9

10

11

12

13

Double distance = neighbor._1;
String classificationID = neighbor._2;
nearestK.put(distance, classificationID);
// keep only k-nearest-neighbors
if (nearestK.size() > k) {

// remove the last highest distance neighbor from nearestK
nearestK.remove(nearestK.lastKey());

}

}
return nearestK;

14
15 }
16
17 \subsubsection{Method buildClassificationCount()}
18 The {\tt buildClassificationCount()} is a simple method, which counts the
19 classifications (will be used to select the classifiaction based on
20 a mority count).
21
22 \begin{pyglist}[numbers=left,numbersep=5pt,language=java,
23 caption={Method buildClassificationCount()},%
24 listingnamefont=\sffamily\bfseries\color{white},fontsize=\scriptsize,%
25 captionfont=\sffamily\color{white},captionbgcolor=gray,%
26 fvset={frame=bottomline,framerule=4pt,rulecolor=\color{gray}}]
27

28

29

30

31

32

33

34

35

36

Map<String, Integer> majority = new HashMap<String, Integer>();
for (Map.Entry<Double, String> entry : nearestK.entrySet()) {

String classificationID = entry.getValue();
Integer count = majority.get(classificationID);
if (count == null){

majority.put(classificationID, 1);

}
else {

majority.put(classificationID, count+1);

340

static Map<String, Integer> buildClassificationCount(Map<Double, String> nearestK) {

37

38

39

40

}

}

}
return majority;

13.7.3.7 Method classifyByMajority()

The classifyByMajority() method select a classiﬁcation based on a major-
ity rule. For example, for a given query point r, if k=6 and classiﬁcations are
{C1, C2, C3, C3, C3, C4} (total of 6), then C3 is selected based on a majority
rule.

Listing 13.10: Method classifyByMajority()

static String classifyByMajority(Map<String, Integer> majority) {

int votes = 0;
String selectedClassification = null;
for (Map.Entry<String, Integer> entry : majority.entrySet()) {

if (selectedClassification == null) {

selectedClassification = entry.getKey();
votes = entry.getValue();

}
else {

int count = entry.getValue();
if (count > votes) {

selectedClassification = entry.getKey();
votes = count;

}

}

}
return selectedClassification;

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

13.7.3.8 STEP-1: Handle input parameters

This step reads 4 input parameters:

1. k as an integer for kNN

2. d as an integer for dimension of R and S vectors

3. Query data set R (as an HDFS ﬁle)

4. Training data set S (as an HDFS ﬁle)

341

Listing 13.11: STEP-1: Handle input parameters

1

2

3

4

5

6

7

8

9

// STEP-1: Handle input parameters
if (args.length < 4) {

System.err.println("Usage: kNN <k-knn> <d-dimension> <R> <S>");
System.exit(1);

}
Integer k = Integer.valueOf(args[0]); // k for kNN
Integer d = Integer.valueOf(args[1]); // d-dimension
String datasetR = args[2];
String datasetS = args[3];

13.7.3.9 STEP-2: Create a Spark context object

This step creates a JavaSparkContext object, which is a factory class for
creating new RDDs.

Listing 13.12: STEP-2: Create a Spark context object

1

2

// STEP-2: Create a Spark context object
JavaSparkContext ctx = createJavaSparkContext();

13.7.3.10 STEP-3: Broadcast shared objects

To access shared objects and data structures from all cluster nodes, Spark
oﬀers a Broadcast class, which you can register objects and read them from
all cluster nodes. Below, we broadcast two integer values (k and d), which
are accessed by all cluster nodes.

Listing 13.13: STEP-3: Broadcast shared objects

1

2

3

4

5

// STEP-3: Broadcast shared objects
// broadcast k and d as global shared objects,
// which can be accessed from all cluster nodes
final Broadcast<Integer> broadcastK = ctx.broadcast(k);
final Broadcast<Integer> broadcastD = ctx.broadcast(d);

13.7.3.11 STEP-4: Create RDDs for query and training datasets

This step create two RDDs (one for R and another one for S). These RDDs
represent raw data as String objects.

342

Listing 13.14: STEP-4: Create RDDs for query and training datasets

1

2

3

4

5

// STEP-4: Create RDDs for query and training datasets
JavaRDD<String> R = ctx.textFile(datasetR, 1);
R.saveAsTextFile("/output/R");
JavaRDD<String> S = ctx.textFile(datasetS, 1);
S.saveAsTextFile("/output/S");

For debugging/understanding purposes, this step creates the following

outputs.

Query Data Set (R)

# hadoop fs -cat /output/R/part*
1000;3.0,3.0
1001;10.1,3.2
1003;2.7,2.7
1004;5.0,5.0
1005;13.1,2.2
1006;12.7,12.7

Training Data Set (S)

# hadoop fs -cat /output/S/part*
100;c1;1.0,1.0
101;c1;1.1,1.2
102;c1;1.2,1.0
103;c1;1.6,1.5
104;c1;1.3,1.7
105;c1;2.0,2.1
106;c1;2.0,2.2
107;c1;2.3,2.3
208;c2;9.0,9.0
209;c2;9.1,9.2
210;c2;9.2,9.0
211;c2;10.6,10.5
212;c2;10.3,10.7
213;c2;9.6,9.1
214;c2;9.4,10.4
215;c2;10.3,10.3

343

300;c3;10.0,1.0
301;c3;10.1,1.2
302;c3;10.2,1.0
303;c3;10.6,1.5
304;c3;10.3,1.7
305;c3;10.0,2.1
306;c3;10.0,2.2
307;c3;10.3,2.3

13.7.3.12 STEP-5: Perform cartesian product of (R, S)

This step creates the cartesian product of query data set (R) with training
data set (S). This step creates the following RDD:

{(r, s)/r ∈ R, s ∈ S}

Listing 13.15: STEP-5: Perform cartesian product of (R, S)

1

2

3

4

5

6

7

// STEP-5: Perform cartesian product of (R, S)
//<U> JavaPairRDD<T,U> cartesian(JavaRDDLike<U,?> other)
// Return the Cartesian product of this RDD and another
// one, that is, the RDD of all pairs of elements (a, b)
// where a is in this and b is in other.
JavaPairRDD<String,String> cart = R.cartesian(S);
cart.saveAsTextFile("/output/cart");

For debugging/understanding purposes, this step creates the following

outputs:

# hadoop fs -cat /output/cart/part*
(1000;3.0,3.0,100;c1;1.0,1.0)
(1000;3.0,3.0,101;c1;1.1,1.2)
(1000;3.0,3.0,102;c1;1.2,1.0)
(1000;3.0,3.0,103;c1;1.6,1.5)
(1000;3.0,3.0,104;c1;1.3,1.7)
(1000;3.0,3.0,105;c1;2.0,2.1)
(1000;3.0,3.0,106;c1;2.0,2.2)
(1000;3.0,3.0,107;c1;2.3,2.3)
(1000;3.0,3.0,208;c2;9.0,9.0)
(1000;3.0,3.0,209;c2;9.1,9.2)
(1000;3.0,3.0,210;c2;9.2,9.0)
(1000;3.0,3.0,211;c2;10.6,10.5)
(1000;3.0,3.0,212;c2;10.3,10.7)
(1000;3.0,3.0,213;c2;9.6,9.1)
(1000;3.0,3.0,214;c2;9.4,10.4)
(1000;3.0,3.0,215;c2;10.3,10.3)
(1000;3.0,3.0,300;c3;10.0,1.0)
(1000;3.0,3.0,301;c3;10.1,1.2)
(1000;3.0,3.0,302;c3;10.2,1.0)
(1000;3.0,3.0,303;c3;10.6,1.5)
(1000;3.0,3.0,304;c3;10.3,1.7)
(1000;3.0,3.0,305;c3;10.0,2.1)
(1000;3.0,3.0,306;c3;10.0,2.2)
(1000;3.0,3.0,307;c3;10.3,2.3)

344

(1001;10.1,3.2,100;c1;1.0,1.0)
(1001;10.1,3.2,101;c1;1.1,1.2)
(1001;10.1,3.2,102;c1;1.2,1.0)
(1001;10.1,3.2,103;c1;1.6,1.5)
(1001;10.1,3.2,104;c1;1.3,1.7)
(1001;10.1,3.2,105;c1;2.0,2.1)
(1001;10.1,3.2,106;c1;2.0,2.2)
(1001;10.1,3.2,107;c1;2.3,2.3)
(1001;10.1,3.2,208;c2;9.0,9.0)
(1001;10.1,3.2,209;c2;9.1,9.2)
(1001;10.1,3.2,210;c2;9.2,9.0)
(1001;10.1,3.2,211;c2;10.6,10.5)
(1001;10.1,3.2,212;c2;10.3,10.7)
(1001;10.1,3.2,213;c2;9.6,9.1)
(1001;10.1,3.2,214;c2;9.4,10.4)
(1001;10.1,3.2,215;c2;10.3,10.3)
(1001;10.1,3.2,300;c3;10.0,1.0)
(1001;10.1,3.2,301;c3;10.1,1.2)
(1001;10.1,3.2,302;c3;10.2,1.0)
(1001;10.1,3.2,303;c3;10.6,1.5)
(1001;10.1,3.2,304;c3;10.3,1.7)
(1001;10.1,3.2,305;c3;10.0,2.1)
(1001;10.1,3.2,306;c3;10.0,2.2)
(1001;10.1,3.2,307;c3;10.3,2.3)
(1003;2.7,2.7,100;c1;1.0,1.0)
(1003;2.7,2.7,101;c1;1.1,1.2)
(1003;2.7,2.7,102;c1;1.2,1.0)
(1003;2.7,2.7,103;c1;1.6,1.5)
(1003;2.7,2.7,104;c1;1.3,1.7)
(1003;2.7,2.7,105;c1;2.0,2.1)
(1003;2.7,2.7,106;c1;2.0,2.2)
(1003;2.7,2.7,107;c1;2.3,2.3)
(1003;2.7,2.7,208;c2;9.0,9.0)
(1003;2.7,2.7,209;c2;9.1,9.2)
(1003;2.7,2.7,210;c2;9.2,9.0)
(1003;2.7,2.7,211;c2;10.6,10.5)
(1003;2.7,2.7,212;c2;10.3,10.7)
(1003;2.7,2.7,213;c2;9.6,9.1)
(1003;2.7,2.7,214;c2;9.4,10.4)
(1003;2.7,2.7,215;c2;10.3,10.3)
(1003;2.7,2.7,300;c3;10.0,1.0)
(1003;2.7,2.7,301;c3;10.1,1.2)
(1003;2.7,2.7,302;c3;10.2,1.0)
(1003;2.7,2.7,303;c3;10.6,1.5)
(1003;2.7,2.7,304;c3;10.3,1.7)
(1003;2.7,2.7,305;c3;10.0,2.1)
(1003;2.7,2.7,306;c3;10.0,2.2)
(1003;2.7,2.7,307;c3;10.3,2.3)
(1004;5.0,5.0,100;c1;1.0,1.0)
(1004;5.0,5.0,101;c1;1.1,1.2)
(1004;5.0,5.0,102;c1;1.2,1.0)
(1004;5.0,5.0,103;c1;1.6,1.5)
(1004;5.0,5.0,104;c1;1.3,1.7)
(1004;5.0,5.0,105;c1;2.0,2.1)
(1004;5.0,5.0,106;c1;2.0,2.2)
(1004;5.0,5.0,107;c1;2.3,2.3)
(1004;5.0,5.0,208;c2;9.0,9.0)
(1004;5.0,5.0,209;c2;9.1,9.2)
(1004;5.0,5.0,210;c2;9.2,9.0)
(1004;5.0,5.0,211;c2;10.6,10.5)
(1004;5.0,5.0,212;c2;10.3,10.7)
(1004;5.0,5.0,213;c2;9.6,9.1)
(1004;5.0,5.0,214;c2;9.4,10.4)
(1004;5.0,5.0,215;c2;10.3,10.3)
(1004;5.0,5.0,300;c3;10.0,1.0)
(1004;5.0,5.0,301;c3;10.1,1.2)
(1004;5.0,5.0,302;c3;10.2,1.0)
(1004;5.0,5.0,303;c3;10.6,1.5)
(1004;5.0,5.0,304;c3;10.3,1.7)
(1004;5.0,5.0,305;c3;10.0,2.1)
(1004;5.0,5.0,306;c3;10.0,2.2)
(1004;5.0,5.0,307;c3;10.3,2.3)
(1005;13.1,2.2,100;c1;1.0,1.0)
(1005;13.1,2.2,101;c1;1.1,1.2)
(1005;13.1,2.2,102;c1;1.2,1.0)
(1005;13.1,2.2,103;c1;1.6,1.5)
(1005;13.1,2.2,104;c1;1.3,1.7)

345

(1005;13.1,2.2,105;c1;2.0,2.1)
(1005;13.1,2.2,106;c1;2.0,2.2)
(1005;13.1,2.2,107;c1;2.3,2.3)
(1005;13.1,2.2,208;c2;9.0,9.0)
(1005;13.1,2.2,209;c2;9.1,9.2)
(1005;13.1,2.2,210;c2;9.2,9.0)
(1005;13.1,2.2,211;c2;10.6,10.5)
(1005;13.1,2.2,212;c2;10.3,10.7)
(1005;13.1,2.2,213;c2;9.6,9.1)
(1005;13.1,2.2,214;c2;9.4,10.4)
(1005;13.1,2.2,215;c2;10.3,10.3)
(1005;13.1,2.2,300;c3;10.0,1.0)
(1005;13.1,2.2,301;c3;10.1,1.2)
(1005;13.1,2.2,302;c3;10.2,1.0)
(1005;13.1,2.2,303;c3;10.6,1.5)
(1005;13.1,2.2,304;c3;10.3,1.7)
(1005;13.1,2.2,305;c3;10.0,2.1)
(1005;13.1,2.2,306;c3;10.0,2.2)
(1005;13.1,2.2,307;c3;10.3,2.3)
(1006;12.7,12.7,100;c1;1.0,1.0)
(1006;12.7,12.7,101;c1;1.1,1.2)
(1006;12.7,12.7,102;c1;1.2,1.0)
(1006;12.7,12.7,103;c1;1.6,1.5)
(1006;12.7,12.7,104;c1;1.3,1.7)
(1006;12.7,12.7,105;c1;2.0,2.1)
(1006;12.7,12.7,106;c1;2.0,2.2)
(1006;12.7,12.7,107;c1;2.3,2.3)
(1006;12.7,12.7,208;c2;9.0,9.0)
(1006;12.7,12.7,209;c2;9.1,9.2)
(1006;12.7,12.7,210;c2;9.2,9.0)
(1006;12.7,12.7,211;c2;10.6,10.5)
(1006;12.7,12.7,212;c2;10.3,10.7)
(1006;12.7,12.7,213;c2;9.6,9.1)
(1006;12.7,12.7,214;c2;9.4,10.4)
(1006;12.7,12.7,215;c2;10.3,10.3)
(1006;12.7,12.7,300;c3;10.0,1.0)
(1006;12.7,12.7,301;c3;10.1,1.2)
(1006;12.7,12.7,302;c3;10.2,1.0)
(1006;12.7,12.7,303;c3;10.6,1.5)
(1006;12.7,12.7,304;c3;10.3,1.7)
(1006;12.7,12.7,305;c3;10.0,2.1)
(1006;12.7,12.7,306;c3;10.0,2.2)
(1006;12.7,12.7,307;c3;10.3,2.3)

13.7.3.13 STEP-6: Find distance(r, s) for r in R and s in S

This step ﬁnds an Euclidian distance between every pair of (R, S). Based
on your data and project requirements, you may select and use diﬀerent
distance algorithms (such as Minkowski). Note that the selection of the
distance algorithm will inﬂuence the bias of kNN classiﬁcation. This step
creates the following RDD:

{(r, (distance, classiﬁcation)}

Listing 13.16: STEP-6: Find distance(r, s) for r in R and s in S

1

2

3

4

5

// STEP-6: Find distance(r, s) for r in R and s in S
// (K,V), where K = unique-record-id-of-R, V=Tuple2(distance, classification)
// distance = distance(r, s) where r in R and s in S
// classification is extracted from s
JavaPairRDD<String,Tuple2<Double,String>> knnMapped =

346

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

//
cart.mapToPair(new PairFunction<Tuple2<String,String>, String, Tuple2<Double,String>>() {

input

K

V

public Tuple2<String,Tuple2<Double,String>> call(Tuple2<String,String> cartRecord) {

r.1, r.2, ..., r.d

String rRecord = cartRecord._1;
String sRecord = cartRecord._2;
String[] rTokens = rRecord.split(";");
String rRecordID = rTokens[0];
String r = rTokens[1]; //
String[] sTokens = sRecord.split(";");
// sTokens[0] = s.recordID
String sClassificationID = sTokens[1];
String s = sTokens[2]; // s.1, s.2, ..., s.d
Integer d = broadcastD.value();
double distance = calculateDistance(r, s, d);
String K = rRecordID; //
Tuple2<Double,String> V = new Tuple2<Double,String>(distance, sClassificationID);
return new Tuple2<String,Tuple2<Double,String>>(K, V);

r.recordID

}
});
knnMapped.saveAsTextFile("/output/knnMapped");

For debugging/understanding purposes, this step creates the following

outputs:

# hadoop fs -cat /output/knnMapped/part*
(1000,(2.8284271247461903,c1))
(1000,(2.6172504656604803,c1))
(1000,(2.6907248094147422,c1))
(1000,(2.0518284528683193,c1))
(1000,(2.1400934559032696,c1))
(1000,(1.345362404707371,c1))
(1000,(1.2806248474865696,c1))
(1000,(0.9899494936611668,c1))
(1000,(8.48528137423857,c2))
(1000,(8.697700845625812,c2))
(1000,(8.627861844049196,c2))
(1000,(10.67754653466797,c2))
(1000,(10.61037228376083,c2))
(1000,(8.987213138676527,c2))
(1000,(9.783659846908007,c2))
(1000,(10.323759005323595,c2))
(1000,(7.280109889280518,c3))
(1000,(7.3246160308919945,c3))
(1000,(7.472616676907761,c3))
(1000,(7.746612162745725,c3))
(1000,(7.414849964766652,c3))
(1000,(7.057619995437555,c3))
(1000,(7.045565981523415,c3))
(1000,(7.333484846919642,c3))
(1001,(9.362157870918434,c1))
(1001,(9.219544457292887,c1))
(1001,(9.167878707749137,c1))
(1001,(8.668333173107735,c1))
(1001,(8.926925562588723,c1))
(1001,(8.174350127074323,c1))
(1001,(8.161494961096281,c1))
(1001,(7.85175139698144,c1))
(1001,(5.903388857258177,c2))
(1001,(6.082762530298219,c2))
(1001,(5.869412236331676,c2))
(1001,(7.3171032519706865,c2))
(1001,(7.502666192761076,c2))
(1001,(5.921148537234984,c2))
(1001,(7.23394774656273,c2))
(1001,(7.102816342831906,c2))
(1001,(2.202271554554524,c3))

347

(1001,(2.0,c3))
(1001,(2.202271554554524,c3))
(1001,(1.7720045146669352,c3))
(1001,(1.513274595042156,c3))
(1001,(1.104536101718726,c3))
(1001,(1.004987562112089,c3))
(1001,(0.9219544457292893,c3))
(1003,(2.4041630560342617,c1))
(1003,(2.193171219946131,c1))
(1003,(2.267156809750927,c1))
(1003,(1.6278820596099708,c1))
(1003,(1.7204650534085255,c1))
(1003,(0.9219544457292889,c1))
(1003,(0.8602325267042628,c1))
(1003,(0.5656854249492386,c1))
(1003,(8.909545442950499,c2))
(1003,(9.121951545584968,c2))
(1003,(9.052071586106685,c2))
(1003,(11.101801655587257,c2))
(1003,(11.034491379306976,c2))
(1003,(9.411163583744573,c2))
(1003,(10.206860437960342,c2))
(1003,(10.748023074035522,c2))
(1003,(7.495331880577404,c3))
(1003,(7.5504966724050675,c3))
(1003,(7.690253571892151,c3))
(1003,(7.99061950038919,c3))
(1003,(7.66550715869472,c3))
(1003,(7.3246160308919945,c3))
(1003,(7.3171032519706865,c3))
(1003,(7.610519036176179,c3))
(1004,(5.656854249492381,c1))
(1004,(5.445181356024793,c1))
(1004,(5.517245689653488,c1))
(1004,(4.879549159502341,c1))
(1004,(4.957822102496216,c1))
(1004,(4.172529209005013,c1))
(1004,(4.1036569057366385,c1))
(1004,(3.818376618407357,c1))
(1004,(5.656854249492381,c2))
(1004,(5.869412236331675,c2))
(1004,(5.8,c2))
(1004,(7.849203781276162,c2))
(1004,(7.783315488916019,c2))
(1004,(6.161980201201558,c2))
(1004,(6.9656299069072,c2))
(1004,(7.495331880577405,c2))
(1004,(6.4031242374328485,c3))
(1004,(6.360031446463138,c3))
(1004,(6.56048778674269,c3))
(1004,(6.603786792439623,c3))
(1004,(6.243396511515186,c3))
(1004,(5.78013840664737,c3))
(1004,(5.730619512757761,c3))
(1004,(5.948108943185221,c3))
(1005,(12.159358535712318,c1))
(1005,(12.041594578792296,c1))
(1005,(11.960351165413163,c1))
(1005,(11.52128465059344,c1))
(1005,(11.81058846967415,c1))
(1005,(11.10045044131093,c1))
(1005,(11.1,c1))
(1005,(10.800462953040487,c1))
(1005,(7.940403012442126,c2))
(1005,(8.06225774829855,c2))
(1005,(7.8390050389064045,c2))
(1005,(8.668333173107735,c2))
(1005,(8.94930164873215,c2))
(1005,(7.736924453553879,c2))
(1005,(8.996110270555825,c2))
(1005,(8.570297544426332,c2))
(1005,(3.3241540277189316,c3))
(1005,(3.1622776601683795,c3))
(1005,(3.1384709652950433,c3))
(1005,(2.596150997149434,c3))
(1005,(2.8442925306655775,c3))
(1005,(3.101612483854164,c3))

348

(1005,(3.0999999999999996,c3))
(1005,(2.801785145224379,c3))
(1006,(16.54629867976521,c1))
(1006,(16.33431969810803,c1))
(1006,(16.405486887014355,c1))
(1006,(15.76863976378432,c1))
(1006,(15.84171707865028,c1))
(1006,(15.06154042586614,c1))
(1006,(14.991330828181999,c1))
(1006,(14.707821048680186,c1))
(1006,(5.23259018078045,c2))
(1006,(5.020956084253276,c2))
(1006,(5.093132631298737,c2))
(1006,(3.0413812651491092,c2))
(1006,(3.124099870362661,c2))
(1006,(4.75078940808788,c2))
(1006,(4.0224370722237515,c2))
(1006,(3.3941125496954263,c2))
(1006,(12.0074976577137,c3))
(1006,(11.79025020938911,c3))
(1006,(11.964113005150026,c3))
(1006,(11.395174417269795,c3))
(1006,(11.258774356030056,c3))
(1006,(10.938464243210744,c3))
(1006,(10.84158659975559,c3))
(1006,(10.673331251301065,c3))

13.7.3.14 STEP-7: Group distances by r in R

After ﬁnding the distances for {(r, s)}, to ﬁnd the k-nearest-neighbors, we
group data by r. Once data is grouped by r, then we scan (STEP-8) the
group values and ﬁnd the k-smallest (or k-nearest) distances.

Listing 13.17: STEP-7: Group distances by r in R

1

2

3

// STEP-7: Group distances by r in R
// now group the results by r.recordID and then find the k-nearest-neigbors.
JavaPairRDD<String, Iterable<Tuple2<Double,String>>> knnGrouped = knnMapped.groupByKey();

This step creates the following RDD:

{(r, {(distance, classiﬁcation)}}

13.7.3.15 STEP-8: ﬁnd the k-nearest-neigbors and classify R

This step scans the group values and ﬁnd the k-smallest (or k-nearest)
distances. To ﬁnd k elements, which have the smallest distances, we use
SortedMap, which keeps only k nearest neighbors. At every iteration, we
make sure that we keep only k nearest elements. Once the k-nearest-neighbors
found, then we classify the query data by the majority rule.

349

Listing 13.18: STEP-8: ﬁnd the k-nearest-neigbors and classify R

// STEP-8: find the k-nearest-neigbors and classify r
// mapValues[U](f: (V) => U): JavaPairRDD[K, U]
// Pass each value in the key-value pair RDD through a
// map function without changing the keys;
// this also retains the original RDD’s partitioning.
// Generate (K,V) pairs where K=r.recordID, V = classificationID
JavaPairRDD<String, String> knnOutput =

knnGrouped.mapValues(new Function<Iterable<Tuple2<Double,String>>, // input
String

// output (classification)

>() {

public String call(Iterable<Tuple2<Double,String>> neighbors) {

Integer k = broadcastK.value();
SortedMap<Double, String> nearestK = findNearestK(neighbors, k);
// now we have the k-nearest-neighbors in nearestK
// we need to find out the classification by majority
// by counting classifications
Map<String, Integer> majority = buildClassificationCount(nearestK);

// find a classificationID with majority of vote
String selectedClassification = classifyByMajority(majority);
return selectedClassification;

}
});
knnOutput.saveAsTextFile("/output/knnOutput");

System.exit(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 }

This step creates the ﬁnal output, which includes classiﬁcation of all query

dataset:

# hadoop fs -cat /output/knnOutput/part*
(1005,c3)
(1001,c3)
(1000,c1)
(1004,c1)
(1006,c2)
(1003,c1)

13.7.3.16 YARN Shell Script

Listing 13.19: YARN Shell Script

350

CLASSPATH=$CLASSPATH:$j

1 hadoop@hnode01319:~/spark_mahmoud_examples# cat run_knn.sh
2 #!/bin/bash
3 source /home/hadoop/conf/env_2.4.0.sh
4 export SPARK_HOME=/home/hadoop/spark-1.0.0
5 source /home/hadoop/spark_mahmoud_examples/spark_env_yarn.sh
6 source $SPARK_HOME/conf/spark-env.sh
7
8 # system jars:
9 CLASSPATH=$CLASSPATH:$HADOOP_HOME/etc/hadoop
10 #
11 jars=‘find $SPARK_HOME -name ’*.jar’‘
12 for j in $jars ; do
13
14 done
15
16 # app jar:
17 export MP=/home/hadoop/spark_mahmoud_examples
18 export CLASSPATH=$MP/mp.jar:$CLASSPATH
19 export CLASSPATH=$MP/commons-math3-3.0.jar:$CLASSPATH
20 export CLASSPATH=$MP/commons-math-2.2.jar:$CLASSPATH
21 export SPARK_CLASSPATH=$CLASSPATH
22 export HADOOP_HOME=/usr/local/hadoop/hadoop-2.4.0
23 export SPARK_LIBRARY_PATH=$HADOOP_HOME/lib/native
24 export JAVA_HOME=/usr/java/jdk7
25 export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop
26 export YARN_CONF_DIR=$HADOOP_HOME/etc/hadoop
27 export MY_JAR=$MP/mp.jar
28 export SPARK_JAR=$MP/spark-assembly-1.0.0-hadoop2.4.0.jar
29 export YARN_APPLICATION_CLASSPATH=$CLASSPATH:$HADOOP_HOME/etc/hadoop
30 k=4
31 d=2
32 R=/knn/R.txt
33 S=/knn/S.txt
34 $SPARK_HOME/bin/spark-submit --class kNN \
35

--master yarn-cluster \
--num-executors 12 \
--driver-memory 3g \
--executor-memory 7g \
--executor-cores 12 \
$MY_JAR $k $d $R $S

36

37

38

39

40

351

Chapter 14

Naive Bayes

14.1

Introduction

In data mining and machine learning, there are many classiﬁcation algo-
rithms. One of the simplest, but eﬀective algorithms is Naive Bayesian clas-
siﬁer that uses the Bayes1. The main focus of this chapter is to present a
distributed MapReduce solution (using Spark/Hadoop) to Naive Bayesian
classiﬁer, which is a combination of a supervised learning method and prob-
abilistic classiﬁcation. The Naive Bayes classiﬁer is a linear classiﬁer. To
understand Naive Bayes, we need to understand some basic probabilities
and conditional probabilities. When we are dealing with numeric data, it is
better to use clustering (such as K-means2 and nearest-neighbour methods
and algorithms), but for classiﬁcation of names, symbols, emails, and texts,
it may be better to use a probabilistic method, such as the Naive Bayes Clas-
siﬁer (NBC). In some cases, NBC is used to classify numeric data as well.
In the following sections, we will have an example of symbolic and numeric
data.

A naive Bayes classiﬁer is a probabilistic classiﬁer based on applying Bayes’
theorem with strong (naive) independence assumptions.
In a nutshell, a
naive Bayes classiﬁer assigns inputs into one of the k classes {C1, C2, ..., Ck}
based on some properties (features) of inputs. Naive Bayes Classiﬁers have
applications such as e-mail spam ﬁltering and classiﬁcation of documents.

1For details, see http://en.wikipedia.org/wiki/Thomas_Bayes
2For details, see http://en.wikipedia.org/wiki/K-means_clustering

352

Figure 14.1: Naive Bayes: Training Phase

For example, a spam ﬁlter (using Naive Bayes classiﬁer) will assign each
e-mail to one of the two clusters: "spam mail" or "not a spam mail".
Since Naive Bayes is a supervised learning method, it has two distinct stages:

• STAGE-1: Training (see Figure 14.1):

This stage trains data from a set of ﬁnite instances of data samples -
this is the so called supervised learning method - learn from a set of
samples and then use this learning information for the new data clas-
siﬁcation). The main goal at this stage is to use training data and to
build a classiﬁer (to be used in STAGE-2).

• STAGE-2: Classiﬁcation (see Figure 14.2):

Given a new instance of data, we want to classify this data; using Train-
ing data and Naive Bayes theorem we classify new data to one of the

353

Figure 14.2: Naive Bayes: Classiﬁcation

categories identiﬁed in Training.

14.2 Training and Learning Stage

Let each data set have m attributes (X = (x1, x2, ..., xm)), the size of train-
ing data be n, and our classiﬁcation has k distinct categories {C1, C2, ..., Ck}
where k ≤ n, then we will have:

(X11, X12, ..., X1m),
(X21, X22, ..., X2m),
...
(Xn1, Xn2, ..., Xnm),

(c1)
(c2)

(cn)

where ci is a member of {C1, C2, ..., Ck}.

354

14.2.1 Example: Training Data (Numeric Data)

The following is an example of training numeric data3 (the classiﬁcation col-
umn (Sex) is shown in blue and orange colors). Note that the ﬁrst column
is a meta data (not part of an actual data).

Person

1
2
3
4
5
6
7
8

Height
(feet)
6.00
5.92
5.58
5.92
5.00
5.50
5.42
5.75

Weight
(lbs)
180
190
170
165
100
150
130
150

Foot Siz
(inches)
12
11
12
10
6
8
7
9

Classiﬁcation
(sex)
male
male
male
male
female
female
female
female

Here are the facts about this numeric training data:

• The Sex column is the classiﬁcation column (in blue and orange colors).
There are 2 (k = 2) classiﬁcation classes: { male, female }, where
C1 = male and C2 = f emale.

• There are 3 attributes (m = 3) per data set: (Heigh, Weight, Foot
Size). We consider each data instance to be an m-dimensional vector
of attribute values: X = (X1, X2, ..., Xm).

• Training data size is 8 (n = 8) identiﬁed by ﬁrst column (numbers

1, 2, ..., 8).

• The goal is to use this training data and build a classiﬁer system (using
Naive Bayes thorem) which will enable us to decide whether or not a
person is male or female. This classiﬁcation will be based on the values
of the three attributes "height", "weight", and "foot size".

3http://www.ic.unicamp.br/˜rocha/teaching/2011s2/mc906/aulas/naive-bayes-

classiﬁer.pdf

355

14.2.2 Example: Training Data (Symbolic Data)

The following is an example of training data from Tom Mitchell’s book[17].
Note that the ﬁrst column is a meta data (not part of an actual data).

Day

Outlook

Temperature

Humidity Wind

D1
D2
D3
D4
D5
D6
D7
D8
D9
Dl0
D11
D12
D13
D14

Sunny
Sunny
Overcast
Rain
Rain
Rain
Overcast
Sunny
Sunny
Rain
Sunny
Overcast
Overcast
Rain

Hot
Hot
Hot
Mild
Cool
Cool
Cool
Mild
Cool
Mild
Mild
Mild
Hot
Mild

High
High
High
High
Normal
Normal
Normal
High
Normal
Normal
Normal
High
Normal
High

Weak
Strong
Weak
Weak
Weak
Strong
Strong
Weak
Weak
Weak
Strong
Strong
Weak
Strong

PlayTennis
Classiﬁcation
No
No
Yes
Yes
Yes
No
Yes
No
Yes
Yes
Yes
Yes
Yes
No

Here are the facts about this symbolic training data:

• The PlayTennis column is the classiﬁcation column (in blue and red
colors). There are 2 (k = 2) classiﬁcation classes: { Yes, No }, where
C1 = Y es and C2 = N o.

• There are 4 attributes (m = 4) per data set: (Outlook, Tempera-
ture, Humidity, Wind). We consider each data instance to be an m-
dimensional vector of attribute values: X = (X1, X2, ..., Xm).
• Training data size is 14 (n = 14) identiﬁed by {D1, D2, ..., D14}.
• The goal is to use this training data and build a classiﬁer system (using
Naive Bayes theorem) which will enable us to decide whether or not to
play the tennis game on the basis of the weather conditions, i.e. we wish
to classify the data into two classes, one where the attribute PlayTennis
has the value ”Yes”, and the other where it has the value ”No.” This

356

classiﬁcation will be based on the values of the four attributes outlook,
temperature, humidity, and windy.

Now the real question is: if input data is the following

X = (X1 = u1, X2=u2, X3=u3, X4=u4)

= (Outlook = Overcast,

Temperature = Hot,
Humidity = High,
Wind = Strong)

then what will be our classiﬁcation to PlayTennis? Will it be ”Yes” or
”No”? Naive Bayes classiﬁer (using Bayes Theorem) can answer this question
based on the data given in the training/learning phase. Here, Naive refers
to the fact that we assume that all probabilities for our data attributes are
independent. This means that for a given data X = (X1, X2, ..., Xm), we
will assume that these attributes are independent of each other and therefore
probabilities for each attribute will be independent. This is a very strong
(”naive”) assumption. Some statisticians are somewhat disturbed by use of
the Naive Bayes Classiﬁer because the ”naive” assumption of independence
is almost always invalid in the real world. But in real-world examples, the
Naive Bayes method has been shown to perform surprisingly well in a wide
variety of contexts.

14.3 Conditional Probability

Since Naive Bayes is based on Probabilistic Classiﬁcation (especially on con-
ditional probability), we will have a very short introduction to probability
and conditional probability.

The conditional probability (denoted by P ) of event A given event B is

dened as follows:

P (A|B) =

P (A∩B)
P (B)

Furthermore we say that if the events A and B are independent if and only
if

P (A ∩ B) = P (A)P (B)

357

14.4 The Naive Bayes Classiﬁer

The Naive Bayes Classiﬁer is a simple and stable method for classiﬁcation
and predictor selection. A Bayes classiﬁer is a probabilistic classiﬁer based
on applying Bayes’ theorem (from Bayesian statistics) with strong (naive)
independence assumptions. The general form of Bayes’ theorem is stated
next. Let A be a sequence of mutually exclusive events {A1, A2, ..., An}
whose union is the sample space, and let E be any event. It is assumed that
all of the events have non-zero probability (P (E) > 0) and (P (Ai) > 0 for
all i). The Bayes’ Theorem states:

P (Aj|E) =

P (Aj)P (E|Aj)
n
(cid:80)
i=1

P (Ai)P (E|Ai)

for any j ∈ {1, 2, ..., n}.

A simpler formulation of Bayes’s theorem can be stated as: Let A and B be
two events (with some attribute values in a given statistical space). Then,
Bayes’ theorem gives the relationship between the probabilities of A and B,
P (A) and P (B), and the conditional probabilities of A given B (denoted
by P (A|B)) and B given A (denoted by P (B|A)). Bayes’ theorem can be
stated as (for both events, A and B, we assume with non-zero probability):

P (A|B) =

P (B|A)P (A)
P (B)

For more details on Bayes’ formula/theorem, see [3].

Next, we formalize Bayes’ therorm for classiﬁcation: let X = (X1 = u1, ..., Xm =
um) be an instance of data, which needs to be classiﬁed, let C = {C1, C2, ..., Ck}
be a set of ﬁnite distinct classes (generated/deducted by training data).
Then, using Bayes’s theorem, we can predict a class Cpredict ∈ {C1, C2, ..., Ck}
for a given X as:

358

Cpredict = argmax

c

P (C = c|X1 = u1, ..., Xm = um)

= argmax

c

P (C=c,X1=u1,...,Xm=um)
P (X1=u1,...,Xm=um)

= argmax

c

P (X1=u1,...,Xm=um|C=c)P (C=c)
P (X1=u1,...,Xm=um)

= argmax

c

P (X1 = u1, ..., Xm = um|C = c)P (C = c)

= argmax

c

P (C = c)

m
(cid:81)
j=1

P (Xj = uj|C = c)

Note that we dropped the denominator P (X1 = u1, ..., Xm = um) from
our classiﬁcation algorithm since it is the same constant for all calculations,
and it does not change the outcome of classiﬁcation algorithm. Therefore,
constructing a classiﬁer from the probability model can be expressed as:

classif y(X1 = u1, ..., Xm = um) = Cpredict

Cpredict = argmax

c

P (C = c)

m
(cid:81)
j=1

P (Xj = uj|C = c)

14.4.1 The Naive Bayes Classiﬁer Example

Now the real question is if input data is the following

X = (Outlook = Overcast,

Temperature = Hot,
Humidity = High,
Wind = Strong)

X = (Overcast, Hot, High, Strong)

359

X = (X1, X2, X3, X4)

Then how do we classify this data? Will the answer be ”Yes” (play tennis)
or ”No” (do not play tennis). For our example, we have two classes:

• C = (C1, C2) = (”Y es”, ”N o”)
• P (C1) = P (”Y es”) = 9/14
• P (C2) = P (”N o”) = 5/14
Now, following Bayes’s classiﬁer, we will have:

Cpredict = argmax

P (C = c)

c
= max{v1, v2}

m
(cid:81)
j=1

P (Xj = uj|C = c)

where
v1
v2

= {P (C = C1)P (X1|C = C1)P (X2|C = C1)P (X3|C = C1)P (X4|C = C1)}
= {P (C = C2)P (X1|C = C2)P (X2|C = C2)P (X3|C = C2)P (X4|C = C2)}

If v1 > v2, then our classiﬁcation of X will be C1 = ”Y es”, otherwise it
will be C2 = ”N o”. The following are calculations of conditional probabilities
for C1 = ”Y es”:

• P (X1|C = C1) = P (”Overcast”|C = ”Y es”) =?

Of the 9 cases where P layT ennis = ”Y es”, there are 4 where Outlook =
”Overcast”, thus P (outlook = Overcast|play = Y es) = 4/9. In the
notation of equation, we may write P (X1 = Overcast|C1) = 4/9.

• P (X2|C = C1) = P (”Hot”|C = ”Y es”) =?

Of the 9 cases where P layT ennis = ”Y es”, there are 2 where T emperature =
”Hot”, thus P (T emperature = ”Hot”|P layT ennis = Y es) = 2/9. In
the notation of equation, we may write P (X2 = Hot|C1) = 2/9.

• P (X3|C = C1) = P (”High”|C = ”Y es”) =?

Of the 9 cases where P layT ennis = ”Y es”, there are 3 where Humidity =
”High”, thus P (Humidity = ”High”|P layT ennis = Y es) = 3/9. In
the notation of equation, we may write P (X3 = High|C1) = 3/9.

360

• P (X4|C = C1) = P (”Strong”|C = ”Y es”) =?

Of the 9 cases where P layT ennis = ”Y es”, there are 3 where W ind =
”Strong”, thus P (W ind = ”Strong”|P layT ennis = Y es) = 3/9. In
the notation of equation, we may write P (X4 = Strong|C1) = 3/9.

The following are calculations of conditional probabilities for C2 = ”N o”:

• P (X1|C = C2) = P (”Overcast”|C = ”N o”) =?

Of the 5 cases where P layT ennis = ”N o”, there are 0 where Outlook =
”Overcast”, thus P (outlook = Overcast|play = N o) = 0/5.
In the
notation of equation, we may write P (X1 = Overcast|C2) = 0/5.

• P (X2|C = C2) = P (”Hot”|C = ”N o”) =?

Of the 5 cases where P layT ennis = ”N o”, there are 2 where T emperature =
”Hot”, thus P (T emperature = ”Hot”|P layT ennis = N o) = 2/5. In
the notation of equation, we may write P (X2 = Hot|C2) = 2/5.

• P (X3|C = C2) = P (”High”|C = ”N o”) =?

Of the 5 cases where P layT ennis = ”N o”, there are 4 where Humidity =
”High”, thus P (Humidity = ”High”|P layT ennis = N o) = 4/5. In
the notation of equation, we may write P (X3 = High|C2) = 4/5.

• P (X4|C = C2) = P (”Strong”|C = ”N o”) =?

Of the 5 cases where P layT ennis = ”N o”, there are 3 where W ind =
”Strong”, thus P (W ind = ”Strong”|P layT ennis = N o) = 3/5. In
the notation of equation, we may write P (X4 = Strong|C2) = 3/5.

Plugging the values, we will have:
9)(2
14)( 4
5)(2
14)( 0

V1 = ( 9

V2 = ( 5

9 )(3
5 )(4

9 )(3
5 )(3

9) = 648
91854

5) = 0

Since V1 > V2, therefore, we classify X as C1 = ”Y es”.

361

14.5 The Naive Bayes Classiﬁer: MapReduce

Solution for Symbolic Data

This section will present a MapReduce solution for classifying millions or
billions of data for symbolic (non-numeric) data. For building a MapReduce
solution, we will assume that we have a proper training data (this training
data will enable use to use the Bayes’ theorem for computing probabilities and
conditional probabilities). The goal of MapReduce solution is to classify data
into a set of k well-deﬁned classes (deﬁned by training data) and identiﬁed
by {C1, C2, ..., Ck}

14.5.1 STAGE-1: Building Classiﬁer Using Symbolic

Training Data

The goal of building a classiﬁer is to build a function (using training data),
which will accept an instance of data X = (X1 = u1, ..., Xm = um) and
outputs a class c ∈ {C1, C2, ..., Ck} (assuming that all of our training data
maps into one of these classes). So we need to compute P (Xi = ui|C = Cj)
for all distinct Xi and all distinct Cj(j = 1, 2, ..., k) in the training data.
When the size of training data is small, we can write a non-MapReduce
program to build the classiﬁer, but for big training data, we should write a
MapReduce job to compute P (Xi = ui|C = Cj).

14.5.1.1 Mapper for Building Classiﬁer Using Symbolic Data

Listing 14.1: map() for Building Classiﬁer

1 /**
2

3

4

8

9

10

11

12

13

* @param key is generated by MapReduce framework, ignored here
* @paran value as a String has the the following format:
*
*/

<Data1><,><Data2><,><...><DataM><,><Class>

5
6 map(key, value) {
7

String[] tokens = value.split(",");
int classIndex = tokens.length -1;
String theClass = tokens[classIndex];
for(int i=0, i < (classIndex-1); i++) {

String reducerKey = tokens[i] + "," + theClass;
emit(reducerKey, 1);

}

362

14

15

16
17 }

String reducerKey = "CLASS," + theClass;
emit(reducerKey, 1);

To understand the mapper, next we apply the map() function to all of our
training data, which generates a set of input to be consumed by the reduce()
function. The map() function just wants to count the attributes and their
associations to the classiﬁcation classes.

map(Sunny, Hot, High, Weak, No) will generate:

<Sunny,No>, <1>
<Hot,No>, <1>
<High,No>, <1>
<Weak,No>, <1>
<CLASS,No>, <1>

map(Sunny, Hot, High, Strong, No)

<Sunny,No>, <1>
<Hot,No>, <1>
<High,No>, <1>
<Strong,No>, <1>
<CLASS,No>, <1>

map(Overcast, Hot, High, Weak, Yes)

<Overcast,Yes>, <1>
<Hot,Yes>, <1>
<High,Yes>, <1>
<Weak,Yes>, <1>
<CLASS,Yes>, <1>

map(Rain, Mild, High, Weak, Yes)

<Rain,Yes>, <1>
<Mild,Yes>, <1>
<High,Yes>, <1>
<Weak,Yes>, <1>
<CLASS,Yes>, <1>

363

map(Rain, Cool, Normal, Weak, Yes)

<Rain,Yes>, <1>
<Cool,Yes>, <1>
<Normal,Yes>, <1>
<Weak,Yes>, <1>
<CLASS,Yes>, <1>

map(Rain, Cool, Normal, Strong, No)

<Rain,No>, <1>
<Cool,No>, <1>
<Normal,No>, <1>
<Strong,No>, <1>
<CLASS,No>, <1>

map(Overcast, Cool, Normal, Strong, Yes)

<Overcast,Yes>, <1>
<Cool,Yes>, <1>
<Normal,Yes>, <1>
<Strong,Yes>, <1>
<CLASS,Yes>, <1>

map(Sunny, Mild, High, Weak, No)

<Sunny,No>, <1>
<Mild,No>, <1>
<High,No>, <1>
<Weak,No>, <1>
<CLASS,No>, <1>

map(Sunny, Cool, Normal, Weak, Yes)

<Sunny,Yes>, <1>
<Cool,Yes>, <1>
<Normal,Yes>, <1>
<Weak,Yes>, <1>
<CLASS,Yes>, <1>

map(Rain, Mild, Normal, Weak, Yes)

364

<Rain,Yes>, <1>
<Mild,Yes>, <1>
<Normal,Yes>, <1>
<Weak,Yes>, <1>
<CLASS,Yes>, <1>

map(Sunny, Mild, Normal, Strong, Yes)

<Sunny,Yes>, <1>
<Mild,Yes>, <1>
<Normal,Yes>, <1>
<Strong,Yes>, <1>
<CLASS,Yes>, <1>

map(Overcast, Mild, High, Strong, Yes)

<Overcast,Yes>, <1>
<Mild,Yes>, <1>
<High,Yes>, <1>
<Strong,Yes>, <1>
<CLASS,Yes>, <1>

map(Overcast, Hot, Normal, Weak, Yes)

<Overcast,Yes>, <1>
<Hot,Yes>, <1>
<Normal,Yes>, <1>
<Weak,Yes>, <1>
<CLASS,Yes>, <1>

map(Rain, Mild, High, Strong, No)

<Rain,No>, <1>
<Mild,No>, <1>
<High,No>, <1>
<Strong,No>, <1>
<CLASS,No>, <1>

365

14.5.1.2 Reducer for Building Classiﬁer Using Symbolic Data

Below, we present the reducer for building the classiﬁer. Since, we are only
aggregating values (the counts), the reduce() can be used as a combiner too.
For our example, the reducers will receive the following (key, value) pairs:

Key
<CLASS,No>
<CLASS,Yes>
<Cool,No>
<Cool,Yes>
<High,No>
<High,Yes>
<Hot,No>
<Hot,Yes>
<Mild,No>
<Mild,Yes>
<Normal,No>
<Normal,Yes>
<Overcast,Yes>
<Rain,No>
<Rain,Yes>
<Strong,No>
<Strong,Yes>
<Sunny,No>
<Sunny,Yes>
<Weak,No>
<Weak,Yes>

Reducer Input

Value
[<1>,<1>,<1>,<1>,<1>]
[<1>,<1>,<1>,<1>,<1>,<1>,<1>,<1>,<1>]
[<1>]
[<1>,<1>,<1>]
[<1>,<1>,<1>,<1>]
[<1>,<1>,<1>]
[<1>,<1>]
[<1>,<1>]
[<1>,<1>]
[<1>,<1>,<1>,<1>]
[<1>]
[<1>,<1>,<1>,<1>,<1>,<1>]
[<1>,<1>,<1>,<1>]
[<1>,<1>]
[<1>,<1>,<1>]
[<1>,<1>,<1>]
[<1>,<1>,<1>]
[<1>,<1>,<1>]
[<1>,<1>]
[<1>,<1>]
[<1>,<1>,<1>,<1>,<1>,<1>]

Listing 14.1: reduce() for Building Classiﬁer
/**
* @param key is <Data, Class> or <CLASS, Class>
* @paran values as list of Integer
*/
reduce(key, values) {
int total = 0;
for(int value : values) {

366

total += value;

}

emit(key, total);

}

The reduce() function just adds up frequencies (basically tallys the coun-

ters). The reducers will generate the following output:

Reducer Output

Key
<CLASS,No>
<CLASS,Yes>
<Cool,No>
<Cool,Yes>
<High,No>
<High,Yes>
<Hot,No>
<Hot,Yes>
<Mild,No>
<Mild,Yes>
<Normal,No>
<Normal,Yes>
<Overcast,Yes>
<Rain,No>
<Rain,Yes>
<Strong,No>
<Strong,Yes>
<Sunny,No>
<Sunny,Yes>
<Weak,No>
<Weak,Yes>

Value
5
9
1
3
4
3
2
2
2
4
1
6
4
2
3
3
3
3
2
2
6

We will customize our reducers in such a way to generate two type of outputs,
one for emitting data for classes, and one for emitting conditional proba-
bilities. Therefore, our customized reducers will create the following two
outputs:

• Class Output

367

• Conditional Probabilities Output

Class Output is presented beow:

CLASS OUTPUT

Key
<CLASS,No>
<CLASS,Yes>

Value
5
9

Conditional Probabilities Output is presented beow:

CONDITIONAL PROBABILITIES OUTPUT
Key
<Cool,No>
<Cool,Yes>
<High,No>
<High,Yes>
<Hot,No>
<Hot,Yes>
<Mild,No>
<Mild,Yes>
<Normal,No>
<Normal,Yes>
<Overcast,Yes>
<Rain,No>
<Rain,Yes>
<Strong,No>
<Strong,Yes>
<Sunny,No>
<Sunny,Yes>
<Weak,No>
<Weak,Yes>

Value
1
3
4
3
2
2
2
4
1
6
4
2
3
3
3
3
2
2
6

From the output of reducers (CLASS OUTPUT and CONDITIONAL PROB-
ABILITIES OUTPUT), we will generate a ﬁnal probability table, which will
be used to classify new data:

368

Probability Table

Key
<CLASS,No>
<CLASS,Yes>
<Cool,No>
<Cool,Yes>
<High,No>
<High,Yes>
<Hot,No>
<Hot,Yes>
<Mild,No>
<Mild,Yes>
<Normal,No>
<Normal,Yes>
<Overcast,Yes>
<Rain,No>
<Rain,Yes>
<Strong,No>
<Strong,Yes>
<Sunny,No>
<Sunny,Yes>
<Weak,No>
<Weak,Yes>

Probability
5/14
9/14
1/5
3/9
4/5
3/9
2/5
2/9
2/5
4/9
1/5
6/9
4/9
2/5
3/9
3/5
3/9
3/5
2/9
2/5
6/9

If any key is not in our Probability Table, then its probability is zero. Typi-
cally, training data should cover all attributes in such a way that probability
of zero will not happen, this requirement truly depends on the project and
data mining requirements.

14.5.2 STAGE-2: Using Classiﬁer To Classify New Sym-

bolic Data

Now that we have built our classiﬁer (generated Probability Table), we can
use it to classify new data. The goal is to classify X = {x1 = u1, x2 =
u2, ..., xm = um} into one of the classes in {C1, C2, ..., Ck}. We will assume
that each record of MapReduce input is an instance of data, which needs to
be classiﬁed.

For classiﬁcation, the map() is an identity mapper, which helps us not to

369

classify the same (duplicate) data more than once. Because classiﬁcation is an
expensive operation, we eliminate duplicate calculations. Now that we have
built the ”Probability Table” from the given training data, all classiﬁcations
will be done by reducers.

14.5.2.1 Mapper to Classify New Symbolic Data

Listing 14.2: map() for Naive Bayes Classiﬁer

1 public class NaiveBayesClassifierMapper ... {

2

3

4

5

6

7

8

9

10

11

12

/**

* @param key is generated by MapReduce framework, ignored here
* @paran value as a String has the the following format:
*
*/

X = (X1, X2, ..., Xm) = <Data1><,><Data2><,><...><,><DataM>

map(key, value) {

// if desired, we can find out how many
// times each input data is duplicated
emit(value, 1);

}

14.5.2.2 Reducer to Classify New Symbolic Data

Listing 14.3: reduce() for Naive Bayes Classiﬁer

1 public class NaiveBayesClassifierReducer ... {
2

3

4

5

6

7

8

9

10

11

12

13

14

15

private theProbabilityTable = ...;
// classifications = {C1, C2, ..., Ck}
private List<String> classifications = ...;
public void setup() {

theProbabilityTable = buildTheProbabilityTable();
classifications = buildClassifications();

}

/**

* @param key is X = (X1, X2, ..., Xm)
*
*
* @param values as a list of integers (shows duplicate records)

= <Data1><,><Data2><,><...><,><DataM>

370

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

*
*/

reduce(key, values) {

// key = (X1, X2, ..., Xm)
String[] attributes = key.split(",");
String selectedClass = null;
double maxPosterior = 0.0;
for(String aClass : classifications) {

double posterior = theProbabilityTable.getClassProbability(aClass);
for (int i=0; i < attributes.length; i++) {

posterior *= theProbabilityTable.getConditionalProbability(attributes[i], aClass);

}
if (selectedClass == null) {

// computing values for the first classification
selectedClass = aClass;
maxPosterior = posterior;

}
else {

if (posterior > maxPosterior) {
selectedClass = aClass;
maxPosterior = posterior;

}

}

}

reducerOutputValue = selectedClass + "," + maxPosterior;
emit(key, reducerOutputValue);

}

14.6 The Naive Bayes Classiﬁer: MapReduce

Solution for Numeric Data

This section will present a MapReduce solution for classifying millions or
billions of data for numeric data or so called continuous data. For building
a MapReduce solution, we will assume that we have a proper training data
(this training data will enable use to use the Bayes’ theorem for computing
probabilities and conditional probabilities). The goal of MapReduce solution
is to classify data into a set of k well-deﬁned classes (deﬁned by training
data) and identiﬁed by {C1, C2, ..., Ck}

To work with numeric data, we do need to calculate the mean and variance
of the training data. Then we will use these values (mean and variance) in
the classiﬁer to classify new numeric data. In this numeric example, we have
two classes: {C1, C2} = {male, f emale}. The classiﬁer created from the
training set using a Gaussian distribution assumption would be:

371

Sex
Class
male
female

mean
(height)
5.8550
5.4175

variance
(height)
0.035033
0.097225

mean variance
(weight)
122.92
558.33

(weight)
176.25
132.50

mean
(foot size)
11.25
7.50

variance
(foot size)
0.9167
1.6667

Since we have 4 males and 4 females in our training data, then we have

equiprobable classes so P (male) = P (f emale) = 0.5.
For numeric data (continuous attribute such as height, weight, and foot size)
it is recommended to use a Gaussian Normal Distribution as outlined below.
Let x be continuous attribute (i.e., numeric value). Then ﬁrst, we segment
the data by the class, and then compute the mean (µ) and variance (σ2) of x
in each class. Gaussian Normal Distribution for conditional probability can
be expressed as:

P (x = v|c) =

(v−µc)2
(2σ2
c )

−
e

1
?

2π

σc

where

• µc is the mean of values in x associated with class c
• σ2

c is the variance of values in x associated with class c (σc is the
standard deviation of values in x associated with class c).

Following [7], let’s classify a new data:

Height (feet)
6.00

Weight (lbs)
130

Foot Size (inches)
8

Sex
?

The goal is to classify this data as male/female (in plain English: we want
to determine which posterior is greater, male or female). Following Bayes’s
theorem, we may write:

posterior(male) = evidenceMale / evidence
posterior(female) = evidenceFemale / evidence

372

The evidenceMale, evidenceFemale, and evidence (also termed nor-
malizing constant) may be calculated since the sum of the posteriors equals
one.

evidenceMale = P(male) *

P(height|male) *
P(weight|male) *
P(footsize|male)

evidenceFemale = P(female) *

P(height|female) *
P(weight|female) *
P(footsize|female)

evidence = evidenceMale + evidenceFemale

The evidence may be ignored since it is a positive constant. We now deter-
mine the sex (classiﬁcation) of the sample.

P(male) = 0.5
P(height|male) = 1.5789 (A probability density greater

than 1 is OK. It is the area
under the bell curve that is
equal to 1.)

P(weight|male) = 5.9881e-06
P(footsize|male) = 1.3112e-3
posterior numerator (male) = their product = 6.1984e-09

P(female) = 0.5
P(height|female) = 2.2346e-1
P(weight|female) = 1.6789e-2
P(footsize|female) = 2.8669e-1
posterior numerator (female) = their product = 5.3778e-04

Since posterior numerator (female) > posterior numerator (male),

then we conclude that the sample is female.

373

Figure 14.3: Naive Bayes: Training Phase

14.7 Naive Bayes Classiﬁer Implementation

in Spark

Spark implementation has two parts, which are illustrated in the following
ﬁgure.

• Build Naive Bayes Classiﬁer using Training Data. This is implemented
by the BuildNaiveBayesClassifier class. This class reads training
data and builds the Naive Bayes classiﬁer. Let C = {C1, C2, ..., Ck}
be a set of classiﬁcations and let our training data to be

– Let X = {X1, X2, ..., Xn} be a raw data

374

– Each Xi has m attributes and classiﬁed as:

X1 = {X11, X12, ..., X1m} → c1 ∈ C

X2 = {X21, X22, ..., X2m} → c2 ∈ C

...

Xn = {Xn1, Xn2, ..., Xnm} → cn ∈ C

– The goal is to create the following probabilistic table (pt) func-

tions:

pt(Ci) = p-value

pt(Aj, Ci) = p-value

where Aj is an attribute of X and 0.00 ≤ p-value ≤ 1.00.

• Use the Built Classiﬁer to Classify New Data

Once the Naive Bayes classiﬁer is built, we will use the pt() functions to
classify new data. This is implemented by the NaiveBayesClassifier
class. This class reads the classiﬁer (expressed as pt() functions) and
new data and classiﬁes new data using the classiﬁer.

14.7.1 STAGE-1: Building Classiﬁer Using Training

Data

This stage is implemented by the BuildNaiveBayesClassifier class, which
accepts taining data (which is already classiﬁed), and builds a Naive Bayes
Classiﬁer. Naive Bayes classiﬁer is a set of probability tables (pt), discussed
in the preceding section. First, we present the BuildNaiveBayesClassifier
class as a set of high-level steps, then we explain each step in a detailed
manner.

375

14.7.1.1 Building Classiﬁer: High-Level Steps

Listing 14.4: Building Classiﬁer: High-Level Steps

1 // STEP-0: import required classes and interfaces
2 /**
3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Let C = {C1, C2, ..., Ck} be set of classifications,
and let each training data element to have m attributes: A = {A1, A2, ..., Am}
then we will build

ProbabilityTable(c) = p-value where c in C
ProbabilityTable(c, a) = p-value where c in C and a in A

* Build Naive Bayes Classifier. The goal is to build the following
* data strucures (probabilities and conditional probabilities) to
* be used in classifying new data:
*
*
*
*
*
*
*
*
*
*
*
* @author Mahmoud Parsian
*/

Record example in training data :

1 >= p-value >=0

where

<attribute_1><,><attribute_2><,>...<,><attribute_m><,><classification>

18
19 public class BuildNaiveBayesClassifier implements java.io.Serializable {
20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

static List<Tuple2<PairOfStrings, DoubleWritable>>

toWritableList(Map<Tuple2<String,String>, Double> PT) {...}

public static void main(String[] args) throws Exception {

// STEP-1: handle input parameters
// STEP-2: create a Spark context object
// STEP-3: read training data
// STEP-4: implement map() function to all elements of training data
// STEP-5: implement reduce() function to all elelments of training data
// STEP-6: collect reduced data as Map
// STEP-7: build the classifier
// STEP-8: save the classifier
//
//

8.1: the PT (probability table) for classification of new entries
8.2: the Classification List (CLASSIFICATIONS)

System.exit(0);

}

36
37 }

14.7.1.2 STEP-0: import required classes and interfaces

Listing 14.5: STEP-0: import required classes and interfaces

1 // STEP-0: import required classes and interfaces
2 import java.util.Map;
3 import java.util.HashMap;
4 import java.util.List;

376

5 import java.util.ArrayList;
6 import scala.Tuple2;
7 import org.apache.spark.api.java.JavaRDD;
8 import org.apache.spark.api.java.JavaPairRDD;
9 import org.apache.spark.api.java.JavaSparkContext;
10 import org.apache.spark.api.java.function.PairFunction;
11 import org.apache.spark.api.java.function.PairFlatMapFunction;
12 import org.apache.spark.api.java.function.FlatMapFunction;
13 import org.apache.spark.api.java.function.Function;
14 import org.apache.spark.api.java.function.Function2;
15 import org.apache.spark.broadcast.Broadcast;
16 import edu.umd.cloud9.io.pair.PairOfStrings;
17 import org.apache.hadoop.mapred.SequenceFileOutputFormat;
18 import org.apache.hadoop.io.DoubleWritable;

14.7.1.3 Method: toWritableList()

The toWritableList() prepares the classiﬁer to be saved in HDFS. To per-
sist data types, they have to implement the Hadoop’s Writable interface.

Listing 14.6: STEP-0: import required classes and interfaces

static List<Tuple2<PairOfStrings, DoubleWritable>>

toWritableList(Map<Tuple2<String,String>, Double> PT) {
List<Tuple2<PairOfStrings, DoubleWritable>> list =

new ArrayList<Tuple2<PairOfStrings, DoubleWritable>>();

for (Map.Entry<Tuple2<String,String>, Double> entry : PT.entrySet()) {

list.add(new Tuple2<PairOfStrings, DoubleWritable>(

new PairOfStrings(entry.getKey()._1, entry.getKey()._2),
new DoubleWritable(entry.getValue())

));

}
return list;

}

1

2

3

4

5

6

7

8

9

10

11

12

14.7.1.4 STEP-1: handle input parameters

This section reads 2 input parameters:

• <training-data-filename>: this is an HDFS ﬁle to represent the
training data, to be used for building the BNaive Bayes Classiﬁer

• <resource-manager-host>: this is the host name for YARN’s resource

manager (will be used to create a SparkContextObject

377

Listing 14.7: STEP-1: handle input parameters

System.err.println("Usage: BuildNaiveBayesClassifier <training-data-filename> <resource-manager-host>");
System.exit(1);

1 // STEP-1: handle input parameters
2 if (args.length < 2) {
3

4
5 }
6 final String trainingDataFilename = args[0];
7 final String resourceManagerHost = args[1];

14.7.1.5 STEP-2: create a Spark context object

This steps creates a SparkContextObject, which is a factory class for creat-
ing new RDDs. SparkUtil class has static methods for creating instances of
SparkContextObject by using YARN’s resource manager or by using Spark
master URL.

Listing 14.8: STEP-2: create a Spark context object

1 // STEP-2: create a Spark context object
2 JavaSparkContext ctx = SparkUtil.createJavaSparkContext(resourceManagerHost);

14.7.1.6 STEP-3: read training data

This steps uses an instance of SparkContextObject, to read our training data
and create JavaRDD<String>, where each element is a record of training data
set. Each record has the following format:

<attribute_1><,><attribute_2><,>...<,><attribute_m><,><classification>

Listing 14.9: STEP-3: read training data

1 // STEP-3: read training data
2 JavaRDD<String> training = ctx.textFile(trainingDataFilename, 1);
3 training.saveAsTextFile("/output/1");
4 // get the training data size, which will be
5 // used in calculating the conditional probabilities
6 long trainingDataSize = training.count();

To debug, we can view the created RDD:

378

# hadoop fs -cat /output/1/part*
Sunny,Hot,High,Weak,No
Sunny,Hot,High,Strong,No
Overcast,Hot,High,Weak,Yes
Rain,Mild,High,Weak,Yes
Rain,Cool,Normal,Weak,Yes
Rain,Cool,Normal,Strong,No
Overcast,Cool,Normal,Strong,Yes
Sunny,Mild,High,Weak,No
Sunny,Cool,Normal,Weak,Yes
Rain,Mild,Normal,Weak,Yes
Sunny,Mild,Normal,Strong,Yes
Overcast,Mild,High,Strong,Yes
Overcast,Hot,Normal,Weak,Yes
Rain,Mild,High,Strong,No

14.7.1.7 STEP-4:

implement map() function to all elements of

training data

This steps maps all elements of training data, so that we can create count
of attributes with respect to classiﬁcations. Then these counts are used to
calculate conditional probabilities.

Listing 14.10: STEP-4: implement map() function

1 // STEP-4: implement map() function to all elelments of training data
2 // PairFlatMapFunction<T, K, V>
3 // T => Iterable<Tuple2<K, V>>
4 // K = <CLASS,classification> or <attribute,classification>
5 JavaPairRDD<Tuple2<String,String>,Integer> pairs =
6

training.flatMapToPair(new PairFlatMapFunction<
String,
Tuple2<String,String>,

// A1,A2, ...,An,classification
// K = Tuple2(CLASS,classifcation)
//
// V = 1

or
Tuple2(attribute,classifcation)

Integer
>() {
public Iterable<Tuple2<Tuple2<String,String>,Integer>> call(String rec) {

List<Tuple2<Tuple2<String,String>,Integer>> result =

new ArrayList<Tuple2<Tuple2<String,String>,Integer>>();

String[] tokens = rec.split(",");
// tokens[0] = A1
// tokens[1] = A2
// ...
// tokens[m-1] = Am
// token[m] = classification

379

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

int classificationIndex = tokens.length -1;
String theClassification = tokens[classificationIndex];
for(int i=0; i < (classificationIndex-1); i++) {

Tuple2<String,String> K = new Tuple2<String,String>(tokens[i], theClassification);
result.add(new Tuple2<Tuple2<String,String>,Integer>(K, 1));

}

Tuple2<String,String> K = new Tuple2<String,String>("CLASS", theClassification);
result.add(new Tuple2<Tuple2<String,String>,Integer>(K, 1));
return result;

}

31
32 });
33 pairs.saveAsTextFile("/output/2");

To debug, we can view the created RDD:

# hadoop fs -cat /output/2/part*
((Sunny,No),1)
((Hot,No),1)
((High,No),1)
((CLASS,No),1)
((Sunny,No),1)
((Hot,No),1)
((High,No),1)
((CLASS,No),1)
((Overcast,Yes),1)
((Hot,Yes),1)
((High,Yes),1)
((CLASS,Yes),1)
((Rain,Yes),1)
((Mild,Yes),1)
((High,Yes),1)
((CLASS,Yes),1)
((Rain,Yes),1)
((Cool,Yes),1)
((Normal,Yes),1)
((CLASS,Yes),1)
((Rain,No),1)
((Cool,No),1)
((Normal,No),1)
((CLASS,No),1)
((Overcast,Yes),1)
((Cool,Yes),1)
((Normal,Yes),1)
((CLASS,Yes),1)
((Sunny,No),1)
((Mild,No),1)
((High,No),1)
((CLASS,No),1)
((Sunny,Yes),1)
((Cool,Yes),1)
((Normal,Yes),1)
((CLASS,Yes),1)
((Rain,Yes),1)
((Mild,Yes),1)
((Normal,Yes),1)
((CLASS,Yes),1)
((Sunny,Yes),1)
((Mild,Yes),1)
((Normal,Yes),1)
((CLASS,Yes),1)
((Overcast,Yes),1)
((Mild,Yes),1)
((High,Yes),1)
((CLASS,Yes),1)
((Overcast,Yes),1)
((Hot,Yes),1)
((Normal,Yes),1)
((CLASS,Yes),1)
((Rain,No),1)

380

((Mild,No),1)
((High,No),1)
((CLASS,No),1)

14.7.1.8 STEP-5: implement reduce() function

This steps reduces the counts for preparation to calculate conditional prob-
abilities, which will be used by the classiﬁer.

Listing 14.11: STEP-5: implement reduce() function

1 // STEP-5: implement reduce() function to all elelments of training data
2 JavaPairRDD<Tuple2<String,String>, Integer> counts =
3

pairs.reduceByKey(new Function2<Integer, Integer, Integer>() {
public Integer call(Integer i1, Integer i2) {

4

5

return i1 + i2;

}

6
7 });
8 counts.saveAsTextFile("/output/3");

To debug, we can view the created RDD:

# hadoop fs -cat /output/3/part*
((Rain,Yes),3)
((Mild,No),2)
((Cool,No),1)
((Mild,Yes),4)
((Sunny,Yes),2)
((High,Yes),3)
((Hot,No),2)
((Sunny,No),3)
((Overcast,Yes),4)
((CLASS,No),5)
((High,No),4)
((Cool,Yes),3)
((Rain,No),2)
((Hot,Yes),2)
((CLASS,Yes),9)
((Normal,Yes),6)
((Normal,No),1)

381

14.7.1.9 STEP-6: collect reduced data as Map

This steps uses a powerful feature of Spark API to collect JavaPairRDD<K,V>
as a Map<K,V>. Next we use the generated Map<K,V> to build the classiﬁer.

Listing 14.12: STEP-6: collect reduced data as Map

1 // STEP-6: collect reduced data as Map
2 // java.util.Map<K,V> collectAsMap()
3 // Return the key-value pairs in this RDD to the master as a Map.
4 Map<Tuple2<String,String>, Integer> countsAsMap = counts.collectAsMap();

14.7.1.10 STEP-7: build the classiﬁer data structures

This steps builds the classiﬁer, which consists of

• The Probability Table (PT)

• The Classiﬁcation List (CLASSIFICATIONS)

Listing 14.13: STEP-7: build the classiﬁer data structures

1. the Probability Table (PT)
2. the Classification List (CLASSIFICATIONS)

1 // STEP-7: build the classifier data structures, which will be used
2 // to classify new data; need to build the following
3 //
4 //
5 Map<Tuple2<String,String>, Double> PT = new HashMap<Tuple2<String,String>, Double>();
6 List<String> CLASSIFICATIONS =
7 for (Map.Entry<Tuple2<String,String>, Integer> entry : countsAsMap.entrySet()) {
8

new ArrayList<String>();

Tuple2<String,String> k = entry.getKey();
String classification = k._2;
if (k._1.equals("CLASS")) {

PT.put(k, ( (double) entry.getValue() ) / ( (double) trainingDataSize) );
CLASSIFICATIONS.add(k._2);

}
else {

Tuple2<String,String> k2 = new Tuple2<String,String>("CLASS", classification);
Integer count = countsAsMap.get(k2);
if (count == null) {
PT.put(k, 0.0);

}
else {

PT.put(k, ( (double) entry.getValue() ) / ( (double) count.intValue()) );

}

9

10

11

12

13

14

15

16

17

18

19

20

21

22

}

23
24 }
25 System.out.println("PT="+PT);

To debug, we can view the created PT:

382

PT={

(Normal,No)=0.2,
(Mild,Yes)=0.4444444444444444,
(Normal,Yes)=0.6666666666666666,
(Overcast,Yes)=0.4444444444444444,
(CLASS,No)=0.35714285714285715,
(CLASS,Yes)=0.6428571428571429,
(Hot,Yes)=0.2222222222222222,
(Hot,No)=0.4,
(Cool,No)=0.2,
(Sunny,No)=0.6,
(High,No)=0.8,
(Rain,No)=0.4,
(Sunny,Yes)=0.2222222222222222,
(Cool,Yes)=0.3333333333333333,
(Rain,Yes)=0.3333333333333333,
(Mild,No)=0.4,
(High,Yes)=0.3333333333333333

}

14.7.1.11 STEP-8: Save the classiﬁer data structures

This steps saves the classiﬁer, which consists of

• The Probability Table (PT)

• The Classiﬁcation List (CLASSIFICATIONS)

To save any data in Hadoop, your persisting class must implement the
Hadoop’s org.apache.hadoop.io.Writable4 interface. In the code, I used
PairOfStrings and DoubleWritable classes, which both implement the
Hadoop’s Writable interface.

Listing 14.14: STEP-8: Save the classiﬁer data structures

1 // STEP-8: save the following, which will be used to classify new data
2 //
3 //

1. the PT (probability table) for classification of new entries
2. the Classification List (CLASSIFICATIONS)

4A serializable object which implements a simple, eﬃcient, serialization protocol, based

on DataInput and DataOutput.

383

4
5 // STEP 8.1: save the PT
6 // public <K,V> JavaPairRDD<K,V> parallelizePairs(java.util.List<scala.Tuple2<K,V>> list)
7 // Distribute a local Scala collection to form an RDD.
8 List<Tuple2<PairOfStrings, DoubleWritable>> list =
9 JavaPairRDD<PairOfStrings, DoubleWritable> ptRDD = ctx.parallelizePairs(list);
10 ptRDD.saveAsHadoopFile("/naivebayes/pt",
PairOfStrings.class,
11
DoubleWritable.class,
SequenceFileOutputFormat.class
);

// name of path
// key class
// value class
// output format class

toWritableList(PT);

12

13

14

15
16 // STEP 8.2: save the Classification List (CLASSIFICATIONS)
17 // List<Text> writableClassifications = toWritableList(CLASSIFICATIONS);
18 JavaRDD<String> classificationsRDD = ctx.parallelize(CLASSIFICATIONS);
19 classificationsRDD.saveAsTextFile("/naivebayes/classes"); // name of path

To debug, we can view the content of the saved classiﬁer:

# hadoop fs -text /classifier.seq/part*
0.2
(Normal, No)
0.4444444444444444
(Mild, Yes)
0.6666666666666666
(Normal, Yes)
(Overcast, Yes) 0.4444444444444444
(CLASS, No)
(CLASS, Yes)
(Hot, Yes)
(Hot, No)
(Cool, No)
(Sunny, No)
(High, No)
(Rain, No)
(Sunny, Yes)
(Cool, Yes)
(Rain, Yes)
(Mild, No)
(High, Yes)

0.35714285714285715
0.6428571428571429
0.2222222222222222
0.4
0.2
0.6
0.8
0.4
0.2222222222222222
0.3333333333333333
0.3333333333333333
0.4
0.3333333333333333

# hadoop fs -cat /naivebayes/classes/part*
Yes
No

384

14.7.1.12 YARN Script to Build Naive Bayes Classiﬁer

The following shell script builds Naive Bayes Classiﬁer using YARN.

Listing 14.15: YARN Script to Build Naive Bayes Classiﬁer

1 # cat run_build_naive_bayes_classifier.sh
2 #!/bin/bash
3
4 #... set the CLASSPATH accordingly...
5 # mp.jar contains all classes need to run in YARN/Spark environment
6 export MY_JAR=$MP/mp.jar
7 export THE_JARS=$MP/cloud9-1.3.2.jar
8 INPUT=/naivebayes/training_data.txt
9 RESOURCE_MANAGER_HOST=masternode100
10 $SPARK_HOME/bin/spark-submit --class $prog \
11

--master yarn-cluster \
--num-executors 12 \
--driver-memory 3g \
--executor-memory 7g \
--executor-cores 12 \
--jars $THE_JARS \
$MY_JAR $INPUT $RESOURCE_MANAGER_HOST

12

13

14

15

16

17

14.7.2 STAGE-2: Using Classiﬁer To Classify New Data

In STAGE-1, we built a Naive Bayes Classiﬁer using the provided training
data. The goal of STAGE-2 is to classify new data using the classiﬁer built
by STAGE-1. In STAGE-2, we read the classiﬁer from HDFS and the classify
according to the built classiﬁer. I will use the following for the Naive Bayes
classiﬁcation of new data:

Cpredict = argmax

c

P (C = c)

m
(cid:81)
j=1

P (Xj = uj|C = c)

The classiﬁcation is implemented by a single driver class (NaiveBayesClassifier)

using Spark API. First, a high-level steps are presented, then each step is
discussed in detail.

14.7.2.1 STAGE-2: High-Level Solution

Listing 14.16: STEP-8: Save the classiﬁer data structures

385

1 // STEP-0: import required classes and interfaces
2 /**
3

4

5

6

7

8

9

10

11

12

13

14

15

16

* Naive Bayes Classifier, wchich classifies (using the
* classifier built by the BuildNaiveBayesClassifier class)
* new data.
*
* Now for a given X = (X1, X2, ..., Xm), we will classify it
* by using the following data structures (built by the
* BuildNaiveBayesClassifier class):
*
*
*
*
* Therefore, given X, we will classify it as C where C in {C1, C2, ..., Ck}
*
* @author Mahmoud Parsian
*/

ProbabilityTable(c) = p-value where c in C
ProbabilityTable(c, a) = p-value where c in C and a in A

17
18 public class NaiveBayesClassifier implements java.io.Serializable {
public static void main(String[] args) throws Exception {
19

// STEP-1: handle input parameters
// STEP-2: create a Spark context object
// STEP-3: read new data to be classified
// STEP-4: read the classifier from hadoop
// STEP-5: cache the classifier components,
//
// STEP-6: classify new data
System.exit(0);

which can be used from any node in the cluster.

20

21

22

23

24

25

26

27

}

28
29 }

14.7.2.2 STEP-0: import required classes and interfaces

Listing 14.17: STEP-8: Save the classiﬁer data structures

1 // STEP-0: import required classes and interfaces
2 import java.util.Map;
3 import java.util.HashMap;
4 import java.util.List;
5 import java.util.ArrayList;
6 import scala.Tuple2;
7 import org.apache.spark.api.java.JavaRDD;
8 import org.apache.spark.api.java.JavaPairRDD;
9 import org.apache.spark.api.java.JavaSparkContext;
10 import org.apache.spark.api.java.function.PairFunction;
11 import org.apache.spark.api.java.function.PairFlatMapFunction;
12 import org.apache.spark.api.java.function.FlatMapFunction;
13 import org.apache.spark.api.java.function.Function;
14 import org.apache.spark.api.java.function.Function2;
15 import org.apache.spark.broadcast.Broadcast;
16 import edu.umd.cloud9.io.pair.PairOfStrings;
17 import org.apache.hadoop.mapred.SequenceFileInputFormat;
18 import org.apache.hadoop.io.DoubleWritable;

386

14.7.2.3 STEP-1: handle input parameters

Listing 14.18: STEP-1: handle input parameters

1 // STEP-1: handle input parameters
2 if (args.length != 4) {
3

System.err.println("Usage: NaiveBayesClassifier <input-data-filename> "+

4

"<NB-PT-path> <NB-CLASS-path> <resource-manager-host>");

System.exit(1);

5
6 }
7 final String inputDataFilename = args[0];
8 final String nbProbabilityTablePath = args[1];
9 final String nbClassesPath = args[2];
10 final String resourceManagerHost = args[3];

// data to be classified
// part of classifier
// part of classifier
// YARN’s resource manager host

14.7.2.4 STEP-2: create a Spark context object

Using YARN’s resource manager host, SparkUtil class creates an instance
of JavaSparkContext, which will be used to create new RDDs.

Listing 14.19: STEP-2: create a Spark context object

1 // STEP-2: create a Spark context object
2 JavaSparkContext ctx = SparkUtil.createJavaSparkContext(resourceManagerHost);

14.7.2.5 STEP-3: read new data to be classiﬁed

The raw data to be classiﬁed has the following record format:

<attribute_1><,><attribute_2><,>...<,><attribute_m>

Listing 14.20: STEP-3: read new data to be classiﬁed

1 // STEP-3: read new data to be classified
2 JavaRDD<String> newdata = ctx.textFile(inputDataFilename, 1);

387

14.7.2.6 STEP-4: read the classiﬁer from hadoop

This step reads the classiﬁer components and data structures built by the
BuildNaiveBayesClassifier class (STAGE-1). Once the classiﬁer compo-
nents are read, then we are ready to classify new data.

Listing 14.21: STEP-4: read the classiﬁer from hadoop

JavaPairRDD<K,V> hadoopFile(String path,

Class<F> inputFormatClass,
Class<K> keyClass,
Class<V> valueClass)

1 // STEP-4: read the classifier from hadoop
2 //
3 //
4 //
5 //
6 // Get an RDD for a Hadoop file with an arbitrary InputFormat
7 // ’’’Note:’’’ Because Hadoop’s RecordReader class re-uses the
8 // same Writable object for each record, directly caching the
9 // returned RDD will create many references to the same object.
10 // If you plan to directly cache Hadoop writable objects, you
11 // should first copy them using a map function.
12 JavaPairRDD<PairOfStrings, DoubleWritable> ptRDD = ctx.hadoopFile(
13

nbProbabilityTablePath,
SequenceFileInputFormat.class,
PairOfStrings.class,
DoubleWritable.class

// "/naivebayes/pt"
// input format class
// key class
// value class

14

15

16

17

);

18
19 // <K2,V2> JavaPairRDD<K2,V2> mapToPair(PairFunction<T,K2,V2> f)
20 // Return a new RDD by applying a function to all elements of this RDD.
21 JavaPairRDD<Tuple2<String,String>, Double> classifierRDD = ptRDD.mapToPair(
22

new PairFunction<

23

24

25

26

27

28

29

30

31

32

33

Tuple2<PairOfStrings,DoubleWritable>, // T
Tuple2<String,String>,
Double

// K2,
// V2

>() {
public Tuple2<Tuple2<String,String>,Double>

call(Tuple2<PairOfStrings,DoubleWritable> rec) {
PairOfStrings pair = rec._1;
Tuple2<String,String> K2 =

new Tuple2<String,String>(pair.getLeftElement(), pair.getRightElement());

Double V2 = new Double(rec._2.get());
return new Tuple2<Tuple2<String,String>,Double>(K2, V2);

}

34
35 });

14.7.2.7 STEP-5: cache the classiﬁer components

This step caches the classiﬁer components (using Spark’s Broadcast class)
so that they can be accessed and used from any cluster nodes.

388

Listing 14.22: STEP-5: cache the classiﬁer components

which can be used from any node in the cluster.

1 // STEP-5: cache the classifier components,
2 //
3 Map<Tuple2<String,String>, Double> classifier = classifierRDD.collectAsMap();
4 final Broadcast<Map<Tuple2<String,String>, Double>> broadcastClassifier =
5

ctx.broadcast(classifier);

6
7 // we need all classifications classes, which was created by the
8 // BuildNaiveBayesClassifier class.
9 JavaRDD<String> classesRDD = ctx.textFile("/naivebayes/classes", 1);
10 List<String> CLASSES = classesRDD.collect();
11 final Broadcast<List<String>> broadcastClasses =
12

ctx.broadcast(CLASSES);

14.7.2.8 STEP-6: classify new data

This step uses the classiﬁer components to classify new data.

Listing 14.23: STEP-6: classify new data

1 // STEP-6: classify new data
2 // Now, we have Naive Bayes classifier and new data
3 // Use the classifier to classify new data
4 // PairFlatMapFunction<T, K, V>
5 // T => Iterable<Tuple2<K, V>>
6 // K = <CLASS,classification> or <attribute,classification>
7 JavaPairRDD<String,String> classified = newdata.mapToPair(new PairFunction<
8

// T = A1,A2, ...,Am (data to be classified)
// K = A1,A2, ...,Am (data to be classified)
// V = classification for T

String,
String,
String
>() {
public Tuple2<String,String>

call(String rec) {

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

// get the classifer from the Spark cache
Map<Tuple2<String,String>, Double> CLASSIFIER = broadcastClassifier.value();
// get the classes from the Spark cache
List<String> CLASSES = broadcastClasses.value();

// rec = (A1, A2, ..., Am)
String[] attributes = rec.split(",");
String selectedClass = null;
double maxPosterior = 0.0;
for (String aClass : CLASSES) {

double posterior = CLASSIFIER.get(new Tuple2<String,String>("CLASS", aClass));
for (int i=0; i < attributes.length; i++) {

Double probability = CLASSIFIER.get(new Tuple2<String,String>(attributes[i], aClass));
if (probability == null) {

posterior = 0.0;
break;

}
else {

posterior *= probability.doubleValue();

389

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

}

}
if (selectedClass == null) {

// computing values for the first classification
selectedClass = aClass;
maxPosterior = posterior;

}
else {

if (posterior > maxPosterior) {
selectedClass = aClass;
maxPosterior = posterior;

}

}

}

return new Tuple2<String,String>(rec, selectedClass);

}

48
49 });
50 classified.saveAsTextFile("/output/classified");

Input and output for classiﬁed data are given below:

• Input: data to be classiﬁed:

# hadoop fs -cat /naivebayes/new_data_to_be_classified.txt
Rain,Hot,High,Strong
Overcast,Mild,Normal,Weak
Sunny,Mild,Normal,Week

• Output: classiﬁed data:

# hadoop fs -cat /output/classified/part*
(Rain,Hot,High,Strong,Yes)
(Overcast,Mild,Normal,Weak,Yes)
(Sunny,Mild,Normal,Week,Yes)

14.7.2.9 YARN Script for Spark

Listing 14.24: STEP-6: classify new data

1 # cat run_classify_new_data.sh
2 #... set up required CLASSPATH
3 export MY_JAR=$MP/mp.jar
4 export THE_JARS=$MP/cloud9-1.3.2.jar
5 NEW_DATA=/naivebayes/new_data_to_be_classified.txt

390

6 RESOURCE_MANAGER_HOST=masternode100
7 CLASSIFIER_PT=/naivebayes/pt
8 CLASSIFIER_CLASSES=/naivebayes/classes
9 $SPARK_HOME/bin/spark-submit --class $prog \
10

--master yarn-cluster \
--num-executors 12 \
--driver-memory 3g \
--executor-memory 7g \
--executor-cores 12 \
--jars $THE_JARS \
$MY_JAR $NEW_DATA $CLASSIFIER_PT $CLASSIFIER_CLASSES $RESOURCE_MANAGER_HOST

11

12

13

14

15

16

14.8 Using Apache Mahout

If you do not want to roll out your own machine learning algorithms, then you
may use Apache Mahout5. The Apache Mahout project’s goal is to build a
scalable machine learning library. There are some examples on classiﬁcation
of tweets by Mahout:

• Using the Mahout Naive Bayes Classiﬁer to automatically classify Twit-

ter messages
http://chimpler.wordpress.com/2013/03/13/using-the-mahout-naive-bayes-
classiﬁer-to-automatically-classify-twitter-messages/

• Using the Mahout Naive Bayes Classiﬁer to automatically classify Twit-

ter messages (part 2: distribute classiﬁcation with hadoop)
http://chimpler.wordpress.com/2013/06/24/using-the-mahout-naive-bayes-
classiﬁer-to-automatically-classify-twitter-messages-part-2-distribute-classiﬁcation-
with-hadoop/

5http://mahout.apache.org/

391

Chapter 15

Sentiment Analysis

15.1

Introduction

Sentiment means ”a general thought, feeling, emotion, opinion, or sense,”
and ”sentiment analysis” (also known as opinion mining) refers to the use
of natural language processing, text analysis and computational linguistics
to identify and extract subjective information in source materials (source
Wikipedia).” Bo Pang and Lillian Lee[19] deﬁne sentiment analysis as ”sen-
timent analysis seeks to identify the viewpoint(s) underlying a text span; an
example application is classifying a movie review as thumbs up or thumbs
down.” To perform a sentiment analysis about some event, we do need to
teach computers what a sentiment is (how to deﬁne a ”positive” or ”nega-
tive” how to deﬁne ”good” or ”bad”) since computers don’t know about a
sentiment unless they learn it from examples that a human has labeled as
positive or negative. The is where ”machine learning” comes: we do teach
computers the meaning of ”positive” and ”negative” and so on. The ﬁrst
step is to build a model from a training data. After model is built, then we
may use the model to analyze new data.

What is a sentiment data? Typically, sentiment data is an unstructured
data that represents opinions and emotions contained in sources such as
special news bulletins, customer support emails, social media posts (such as
Tweets and Facebook blogs) and online product reviews.

To perform a good sentiment analysis, the sentiment analysis engine has
to perform some level of speech analysis and word-sense-disambiguation to
improve performance. Therefore, a sentiment analysis of a text/document

392

is more than tokenizing words and checking the words against ”positive”
and ”negative” words. Sometimes, we do need to understand the intensity of
words, and factor things like negation and diminishers. For example, consider
the following sentence:

... movie was not good ...

If you just look at individual words without their relationships, you might
indicate that the sentiment is ”neutral” (since ”not” is negative and ”good”
is positive. But if you look at the whole semantics of the sentence, clearly it
is a negative sentiment.

15.1.1 Sentiment Examples

The following are some sentiment analysis examples:

• What bloggers are saying about a brand like Toyota when there was a

problem with breaking system in some Toyota cars.

• What is the sentiment of people seeing the Iron Man III movie before
and after view (this can be done by analyzing tweets before and after)?
Did people really like the movie?

• What is the sentiment of customers before and after announcement of

a new IPhone?

• What is the sentiment of people before and after a presidential debate?

Is sentiment toward a Democratic or Republican party?

• What is the sentiment of people (happy or sad) about the customer
service? Here, for sentiment analysis, we do need customer service log
data and a dictionary of happy and sad words.

15.1.2 Sentiment Scores: Positive or Negative

Given a short sentence (such as a tweet, which is 140 chracters long), how
do you determine whether it is positive or negative sentiment. To score syn-

393

tactically (by ignoring contextual semantics), you can tokenize the sentence
into words and then check these words against positive and negative words1
For example, given the following sentences (green color words are positive

and red color words are negative):

• Sentence-1: ”movie was great and I loved it”

• Sentence-2: ”hamburger had a bad taste and terrible, but I loved

fries”

What is sentiment score of Sentence-1 and Sentence-2:?

setimentScore(Sentence-1) = 1 positive +

1 positive

= 2 positives (Positive sentiment)

setimentScore(Sentence-2) = 1 negative +
1 negative +
1 positive

= 1 negative (Negative sentiment)

In most of the sentiment analysis situations, checking/examining the in-
vidual words against ”positive” and ”negative” words is not enough and
might not give proper expected results. In real sentiment analysis, it is bet-
ter just not to rely on pure syntax, but to understand the semantics: intensity
of words, and to factor things like negation and diminishers. For example,
consider the following sentence:

”movie was not great and I did not love it”

In a real world sentiment analysis, checking pure syntax will not yield
great results.
If you just look at individual words without their relation-
ships, your pure syntactical algorithm might indicate that the sentiment is

1Hu and Liu have published an ”opinion lexicon” which categorizes approximately 6,800
words as positive or negative and which can be downloaded from http://www.cs.uic.
edu/~liub/FBS/opinion-lexicon-English.rar. For example positive words are: love,
best, cool, great, good, ..., and negative words are: terrible, bad, hate, worst, sucks, ...

394

”neutral” (since ”not” is negative and {”good”, ”love”} are positive). But
if you look at the whole semantics of the sentence, clearly it is a negative
sentiment.

Now, after seeing the sentiment scores, we should ask what is sentiment
analysis? In a nutshell, we can say that sentiment analysis is the task
of ﬁnding whether the statement/opinion expressed in a text sentense is
positive, negative, or neutral about a particular topic or trend.

15.2 Steps for Sentiment Analysis

What are the steps for performing Sentiment Analysis for a given set to
tweets?

15.3 A Simple MapReduce for Sentiment Anal-

ysis

Let our keyword of interest be ”Obama” and ”Romney” and further assume
that it is an election year and you want to know the sentiment of people
tweeting about the two presidential candidates Obama and Romney. Let’s
assume that you want to ﬁnd the sentiment trend for each candidate per day.
The mapper accepts a tweet, normalizing the text, looking for a keyword of
interest (”Obama” or ”Romney”), counting the positive and negative key-
words, then subtracting the ratio of negative words from the ratio of positive
words. To perform map(), we do need two distinct set of words:

• set of positive words (such as ”good”, ”like”, ”enjoy”, ...)

• set of negative words (such as ”hate”, ”bad”, ”terrible”, ...)

These two sets are passed to mappers by the driver program and in
hadoop we can accomplish this by using a distributed cache (DistributedCache2
class).

2DistributedCache (org.apache.hadoop.ﬁlecache.DistributedCache) is a facility pro-
vided by the Hadoop’s MapReduce framework to cache text and archive ﬁles needed by
applications.

395

15.3.1 map() for Sentiment Analysis

We assume that there exist a nomalizer and tokenizer function for a given
tweet:

Listing 15.1: The Mapper Function

1 private static List<String> normalizeAndTokenize(String tweet) {
2

List<String> tokens = <normalize and tokenize all

3

4
5 }

return tokens;

the words in the tweet text>;

Using the normalizeAndTokenize() method, we can complete the map()

method:

Listing 15.2: The Mapper Function

1 private Set<String> positiveWords = null;
2 private Set<String> negativeWords = null;
3 // default candidates values
4 private Set<String> allCandidates = {"obama", "romney"};
5
6 setup() {
7

8

positiveWords = <load positive words from distributed cache>;
negativeWords = <load negative words from distributed cache>;
allCandidates = <load all candidates from distributed cache>;

9
10 }
11
12 /**
13 * @param key is the date of a tweet: YYYY-MM-DD:hh:mm:ss
14 * @param value is a single tweet
15 */
16 map(key, value) {
17

date = key; // date of a tweet as YYYY-MM-DD
List<String> tweetWords = normalizeAndTokenize(value);
int positiveCount = 0;
int negativeCount = 0;
for (String candidate : allCandidates) {

if (candidate is in the tweetWords) {

int positiveCount = <count of positive words in tweetWords>;
int negativeCount = <count of negative words in tweetWords>;
double positiveRatio = positiveCount / tweetWords.size();
double negativeRatio = negativeCount / tweetWords.size();

396

18

19

20

21

22

23

24

25

26

outputKey = Pair(date, candidate);
outputValue = positiveRatio - negativeRatio;
emit (outputKey, outputValue);

27

28

29

30

}

31
32 }

}

15.3.2

reduce() for Sentiment Analysis

Listing 15.3: The Reducer Function

where

1 /**
2 * @param key is the Pair(Date, String)
3 *
4 *
5 *
6 * @param values is a List<Double> where Double represents a ratio
7 */
8 reduce(key, values) {
9

Date=YYYY-MM-DD
String= a candidate ("obama" or "romney")

10

11

12

13

14

15
16 }

double sumOfRatio = 0.0;
int n = 0; // number ratios
for (Double ratio : values) {

n++;
sumOfRatio += ratio;

}
emit (key, sumOfRatio / n);

397

Chapter 16

Finding, Counting and Listing all
Triangles in Large Graphs

16.1

Introduction

Graphs and matrices are used by social network analysts to represent and
analyze information about patterns of ties among social actors (users, friends,
and ”friends of friends”). In network analysis, data are usually modeled as
a graph or set of graphs. A graph is a data structure, which has a ﬁnite set
of nodes, called vertices, together with a ﬁnite set of lines, called edges, that
join some or all of these nodes. Before we deﬁne some metrics using the count
of triangles, we do need to deﬁne a triplet and a triangle: Let T=(a,b,c) be
a set of three distinct nodes in a graph (identiﬁed by G), Then T is a triplet
if two of nodes are connected ({(a,b), (a,c)}) and it is a triangle if all
three nodes are connected ({(a,b), (a,c), (b,c)}).

In analysis of graphs, there are three important metrics

• Global Clustering Coeﬃcient

• Transitivity Ratio deﬁned as

T (G) =

3×(number of triangles on the graph)
(number of connected triples of vertices)

• Local Clustering Coeﬃcient

398

In order to calculate these three metrics in a large graph, we need to know
the number of triangles in a graph. For details on these metrics, see [5], [25],
and [32].

Typically a graph might have hundreds of millions of nodes (a node can be
a user in a social network) and edges (the relationship between these users)
and counting the number of triangles is very time consuming. This chapter
provides two MapReduce solutions, which ﬁnds, counts, and lists all tringles
for a given graph or set of graphs. The solutions are given in Hadoop and
Spark:

• Hadoop solution: The MapReduce/Hadoop solution is comprised of 3

steps and each step is a separate MapReduce job.

• Spark solution: The MapReduce/Spark solution is comprised of a single
Java driver class, which manipulates several JavaRDD objects. Spark’s
API is higher level than MapReduce/Hadoop API and this why we can
ﬁt all map() and reduce() functions in a single Java class.

16.2 Basic Graph Concepts

Let V be a ﬁnite set of nodes (a node can represent a user, a computer, or a
tangible/intangible object) and E be ﬁnite set of edges (an edge represents
a relationship and connectivity between 2 nodes), then an undirected simple
graph can be deﬁned as: G = (V, E).
We use the symbol n for the number of nodes and the symbol m for the
number of edges. The degree d(v) = |u ∈ V : ∃{v, u} ∈ E| of node v is
deﬁned to be the number of nodes in V that are adjacent to v. A triangle
(cid:52) = (VŸ, EŸ) of a graph G = (V, E) is a three node subgraph with VŸ =
{u, v, w} ⊂ V and EŸ = {{u, v}, {v, w}, {w, u}} ⊂ E. We use the symbol
T (G) to denote the number of triangles in graph G.
For example, the following graph
has 2 triangles:

• {{2, 3}, {3, 4}, {4, 2}}

• {{2, 4}, {4, 5}, {5, 2}}

399

Figure 16.1: Graph Triangles

400

Let’s formalize some of these graph metrices. Given an undirected graph G
= (V, E), social metrics for graph can be deﬁned. But, ﬁrst we need some
basic deﬁnitions:

• Degree of a node v denoted by d(v) is the number of nodes in V that

are adjacent to v

• Number of triangles of node v

θ(v) = |(u, w) ∈ E : (v, u) ∈ E and (v, w) ∈ E|

• Number of triangles of graph G

θ(G) =

1
3

(cid:88)

v∈V

θ(v)

• The number of triples of node v deﬁned as t(v)

t(v) =

ˆ

˙

d(v)
2

• The number of triples of graph G deﬁned as t(G)

t(G) =

t(v)

(cid:88)

v∈V

Using these basic deﬁnition, now we can deﬁne clustering coecient :

• Clustering coecient for a node v deﬁned as c(v) (where d(v) ≥ 2):

c(v) = θ(v)/t(v)

• The clustering coecient of a graph G (denoted as C(G)) is the average

over the clustering coecients of its nodes:

C(G) =

1
|W |

(cid:88)

c(w)

w∈W

where W is the set of nodes w with d(w) ≥ 2.

401

16.3

Importance of Counting Triangles

Why is counting the number of triangles in a graph important? Identifying
and counting triagles help us to measure two important metics (clustering
coeﬃcient and transitive ratio) about large graphs. Also, counting triangles
help us in ﬁnding patterns (such as intrusion detection, spamming, and com-
munity detection) in social graphs. Also, triangle detections in biological
networks help us to ﬁnd protein-protein interaction networks.

It is shown that triangles and clustering coeﬃcients play important roles
in the analysis of complex networks using graph data structures. The exis-
tence of triangles and the resulting high clustering coeﬃcient reveals impor-
tant characteristics of social, biological, web and diﬀerent other networks.

Given that counting the number of triangles in a graph is very time con-
suming (for details see [24]), distributing graph data and its computation
can be done by MapReduce solutions. The goal of this chapter is to provide
a MapReduce solution for ﬁnding, listing, and counting Triangles in Large
Graphs. A sequential (non-MapReduce) algorithm [24] is provided for ﬁnding
and counting all triangles in large graphs.

16.4 MapReduce Solution

We present a MapReduce solution in three steps (each step is a separate
MapReduce job):

• STEP-1: Generate paths through u of length 2 and copy of all edges
from u as keys, no associated data. From these paths we will generate
possible triangles. This step can be solved by a map() and reduce()
functions as:

mapper1 : (u, v) → (u, v), (v, u)

reducer1 : {(u, v1), (u, v2), ..., (u, vd)} → {[(v1, v2), (u)],
[(v1, v3), (u)],
...,
[(vd−1, vd), (u)]},
{[(u, v1), (−)], ..., [(u, vd), (−)]}

• STEP-2: Identify triangles as {{u, v}, {v, w}, {w, u}}. This step will
generate duplicate tringles and can be implemented by the following

402

map() and reduce() functions:

reducer2 : {[(u, v)(−)], [(u, v)(w1)], ..., [(u, v)(wr)]} → {[(u, v, w1)], ..., [(u, v, wr)]}

reducer2 : {[(u, v)(w1)], ..., [(u, v)(wr)]} → N oOutput

mapper2 : [(u, v), (w)] → [(u, v), (w)]

• STEP-3: This step removes duplicate triangles: (a, b, c) is the same
as (a, c, b). This step can be solved by a map() and reduce() func-
tions as:

reducer3 : {(k3, v31), (k3, v32), (k3, v33), ...} → {(k3, null)

mapper3 : (k3, v3) → (sort(k3), v3)

16.5 MapReduce in Action

The input to the ﬁrst step (i.e., mapper1 of STEP-1) will be the edges in a
given undirected graph. Each line of input will be in the (u, v) format such
that u < v ({u, v} is an edge of a graph). For our graph illustrated above,
we will have the following records:

Input to mapper1 of STEP-1

key (begin-node)
1
2
2
2
3
4

value (end-node)
2
3
4
5
4
5

The mapper1 of STEP-1 generates the following output (which will be
an input to reducer1 of STEP-1). Note that edges must be reciprocal, that
is every {startNode, endNode} edge must have a corresponding {endNode,
startNode}.

403

Output of mapper1 of STEP-1

key (start node)
1
2
2
3
2
4
2
5
3
4
4
5

value (end node)
2
1
3
2
4
2
5
2
4
3
5
4

After shuﬄe and sort phase, the following data will be ready as an input to
reducer1 of STEP-1:

Input of reducer1 of STEP-1

key
1
2
3
4
5

value (as list of nodes)
[2]
[1, 3, 4, 5]
[2, 4]
[2, 3, 5]
[2, 4]

The reducer1 of STEP-1 is deﬁned as:

reducer1 : {(u), (v1, v2, ..., vd)} → {[(v1, v2), (u)],
[(v1, v3), (u)],
...,
[(vd−1, vd), (u)]},
{[(u, v1), (−)], ..., [(u, vd), (−)]}

The reducer1 of STEP-1 will behave as:

404

reducer1 Input/Output

Input
[1],[2]

Output
[(1, 2), (-)]
[(2, 1), (-)]
[(2, 3), (-)]
[(2, 4), (-)]
[(2, 5), (-)]
[(1, 3), (2)]
[(1, 4), (2)]
[(1, 5), (2)]
[(3, 4), (2)]
[(3, 5), (2)]
[(4, 5), (2)]
[(3, 2), (-)]
[(3, 4), (-)]
[(2, 4), (3)]
[(4, 2), (-)]
[(4, 3), (-)]
[(4, 5), (-)]
[(2, 3), (4)]
[(2, 5), (4)]
[(3, 5), (4)]
[(5, 2), (-)]
[(5, 4), (-)]
[(2, 4), (5)]

[2],[1, 3, 4, 5]

[3],[2, 4]

[4],[2, 3, 5]

[5],[2, 4]

The mapper2 of STEP-2 is an identity mapper; it just passes keys and values
without any further processing. This enables us to generate proper keys
and values for reducer2 of STEP-2. The reducer2 of STEP-2 will have the
following input/output:

405

reducer2 Input/Output

Output (as a triangle(s))

(2, 3, 4)
(2, 4, 3) , (2, 4, 5)
(2, 4, 5)

(3, 4, 2)

(4, 5, 2)

Input
(1, 2) [-]
(2, 1) [-]
(2, 3) [-, 4]
(2, 4) [-, 3, 5]
(2, 5) [-, 4]
(1, 3) [2]
(1, 4) [2]
(1, 5) [2]
(3, 4) [2, -]
(3, 5) [2, 4]
(4, 5) [2, -]
(3, 2) [-]
(4, 2) [-]
(4, 3) [-]
(5, 4) [-]
(5, 2) [-]

As you can observe, we have listed each triangle 3 times; this is to highlight
the deﬁnition of a triangle. For example, a single triangle with 3 nodes of
u, v, w can be equivalently expressed as:

{{u, v},{v, w},{w, u}}
{{v, w},{w, u},{u, v}}
{{w, u},{u, v},{v, w}}

16.6 STEP-3: Remove Duplicate Triangles

This step removes duplicate triangles and the result will be unique triangles.
The input for this step will be in the form of (a, b, c), where a, b, and c
represent a vertex of a triangle.

16.6.1 STEP-3: Mapper

The mapper will accept a triangle in the form of (a, b, c) and will emit
sorted vertexes. For example,

406

(1, 2, 3) will emit (1, 2, 3)
(1, 3, 2) will emit (1, 2, 3)
(2, 1, 3) will emit (1, 2, 3)
(2, 3, 1) will emit (1, 2, 3)
(3, 1, 2) will emit (1, 2, 3)
(3, 2, 1) will emit (1, 2, 3)

Therefore, the mapper is deﬁned as:

// key is not used
// value = (a, b, c)
map(key, value) {

triangle = sort(value);
// triangle = (x, y, z)
// x < y < z
// x, y, z in {a, b, c}
emit(triangle, null)

}

16.6.2 STEP-3: Reduer

Since output of mappers will be grouped by key of mappers. The reducer will
will just emit the received key. This will generate unique triangles. We really
do not care about the values of this reducer at all (since a key represents a
unique triangle).

// key is a triangle (a, b, c)
where a < b < c
//
// values = list of nulls
reduce(key, values) {

emit(key, null)

}

407

16.7 Hadoop Implementation

Hadoop implementation classes are given below.

Implementation Classes in Hadoop

Phase-1

Class Name

Class Description

Phase
Job Submitter TriangleCounterDriver Dirver to submit job for 3 phases
GeneratePathsMapper Generate possible triangle paths
GeneratePathsReducer
TriadsMapper
TriadsReducer
UniqueTriadsMapper
UniqueTriadsReducer

Identiﬁes possible triangles
Identity mapper
Identiﬁes triangles with duplicates
Identity mapper
Generates unique triangles

Phase-3

Phase-2

16.7.1 Sample Run

16.7.1.1 The Script

# cat run.sh
#/bin/bash
export HADOOP_HOME=/Users/mahmoud/zmp/zs/hadoop
export HADOOP_HOME_WARN_SUPPRESS=true
export JAVA_HOME=‘/usr/libexec/java_home‘
echo "JAVA_HOME=$JAVA_HOME"

PATH=.:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
export PATH=$PATH:$HADOOP_HOME/bin:$JAVA_HOME/bin

CLASSPATH=.:$HADOOP_HOME/conf
HADOOP_JAR_FILES=‘find $HADOOP_HOME -name ’hadoop*.jar’‘
for hadoopjarfile in $HADOOP_JAR_FILES ; do
CLASSPATH=$CLASSPATH:$hadoopjarfile
done

export TESTS=/Users/mahmoud/zmp/map_reduce_book/hadooptests
LIB_DIR=$TESTS/lib
JAR_FILES=‘find $LIB_DIR -name ’*.jar’‘
for jarfile in $JAR_FILES ; do

408

CLASSPATH=$CLASSPATH:$jarfile
done
echo "CLASSPATH=$CLASSPATH"

export JAR=$TESTS/find_count_list_triangles/triangles.jar
export CLASSPATH=$CLASSPATH:$JAR
export HADOOP_CLASSPATH=$CLASSPATH

javac *.java
jar cvf $JAR *.class
$HADOOP_HOME/bin/hadoop fs -rm /lib/triangles.jar
$HADOOP_HOME/bin/hadoop fs -put $JAR /lib/
export INPUT=/triangles/input
export OUTPUT=/triangles/output
$HADOOP_HOME/bin/hadoop fs -rmr $OUTPUT
$HADOOP_HOME/bin/hadoop fs -rmr /triangles/tmp1
$HADOOP_HOME/bin/hadoop fs -rmr /triangles/tmp2
$HADOOP_HOME/bin/hadoop jar $JAR TriangleCounterDriver $INPUT $OUTPUT

16.7.1.2 HDFS Input

1 mahmoud staff

# hadoop fs -ls /triangles/input/
Found 1 items
-rw-r--r--
# hadoop fs -cat /triangles/input/sample_graph.txt
1 2
2 3
2 4
2 5
3 4
4 5

24 2014-05-25 11:06 /triangles/input/sample_graph.txt

16.7.1.3 Log of Sample Run

# ./run.sh
...

409

Map-Reduce Framework

Deleted hdfs://localhost:9000/lib/triangles.jar
Deleted hdfs://localhost:9000/triangles/output
Deleted hdfs://localhost:9000/triangles/tmp1
Deleted hdfs://localhost:9000/triangles/tmp2
14/05/25 13:40:17 INFO input.FileInputFormat: Total input paths to process : 1
...
14/05/25 13:40:17 INFO mapred.JobClient: Running job: job_201405251213_0025
14/05/25 13:40:18 INFO mapred.JobClient: map 0% reduce 0%
14/05/25 13:40:23 INFO mapred.JobClient: map 100% reduce 0%
14/05/25 13:40:32 INFO mapred.JobClient: map 100% reduce 20%
...
14/05/25 13:40:59 INFO mapred.JobClient: map 100% reduce 80%
14/05/25 13:41:08 INFO mapred.JobClient: map 100% reduce 100%
14/05/25 13:41:09 INFO mapred.JobClient: Job complete: job_201405251213_0025
...
14/05/25 13:41:09 INFO mapred.JobClient:
14/05/25 13:41:09 INFO mapred.JobClient:
14/05/25 13:41:09 INFO mapred.JobClient:
14/05/25 13:41:09 INFO mapred.JobClient:
14/05/25 13:41:09 INFO mapred.JobClient:
14/05/25 13:41:09 INFO mapred.JobClient:
14/05/25 13:41:09 INFO mapred.JobClient:
14/05/25 13:41:09 INFO mapred.JobClient:
14/05/25 13:41:09 INFO mapred.JobClient:
14/05/25 13:41:09 INFO mapred.JobClient:
14/05/25 13:41:09 INFO mapred.JobClient:
14/05/25 13:41:09 INFO mapred.JobClient:
14/05/25 13:41:09 INFO mapred.JobClient:
14/05/25 13:41:09 INFO mapred.JobClient:
14/05/25 13:41:10 INFO input.FileInputFormat: Total input paths to process : 10
14/05/25 13:41:10 INFO mapred.JobClient: Running job: job_201405251213_0026
14/05/25 13:41:11 INFO mapred.JobClient: map 0% reduce 0%
14/05/25 13:41:17 INFO mapred.JobClient: map 50% reduce 0%
...
14/05/25 13:42:05 INFO mapred.JobClient: map 100% reduce 93%
14/05/25 13:42:06 INFO mapred.JobClient: map 100% reduce 100%
14/05/25 13:42:06 INFO mapred.JobClient: Job complete: job_201405251213_0026
...

Map output materialized bytes=276
Map input records=6
Reduce shuffle bytes=276
Spilled Records=24
Map output bytes=192
Total committed heap usage (bytes)=1034620928
Combine input records=0
SPLIT_RAW_BYTES=119
Reduce input records=12
Reduce input groups=5
Combine output records=0
Reduce output records=23
Map output records=12

410

Map-Reduce Framework

Map output materialized bytes=922
Map input records=23
Reduce shuffle bytes=922
Spilled Records=46
Map output bytes=276
Total committed heap usage (bytes)=2696192000
Combine input records=0
SPLIT_RAW_BYTES=1140
Reduce input records=23
Reduce input groups=16
Combine output records=0
Reduce output records=6
Map output records=23

14/05/25 13:42:06 INFO mapred.JobClient:
14/05/25 13:42:06 INFO mapred.JobClient:
14/05/25 13:42:06 INFO mapred.JobClient:
14/05/25 13:42:06 INFO mapred.JobClient:
14/05/25 13:42:06 INFO mapred.JobClient:
14/05/25 13:42:06 INFO mapred.JobClient:
14/05/25 13:42:06 INFO mapred.JobClient:
14/05/25 13:42:06 INFO mapred.JobClient:
14/05/25 13:42:06 INFO mapred.JobClient:
14/05/25 13:42:06 INFO mapred.JobClient:
14/05/25 13:42:06 INFO mapred.JobClient:
14/05/25 13:42:06 INFO mapred.JobClient:
14/05/25 13:42:06 INFO mapred.JobClient:
14/05/25 13:42:06 INFO mapred.JobClient:
14/05/25 13:42:06 INFO input.FileInputFormat: Total input paths to process : 10
14/05/25 13:42:06 INFO mapred.JobClient: Running job: job_201405251213_0027
14/05/25 13:42:07 INFO mapred.JobClient: map 0% reduce 0%
14/05/25 13:42:13 INFO mapred.JobClient: map 50% reduce 0%
...
14/05/25 13:42:59 INFO mapred.JobClient: map 100% reduce 86%
14/05/25 13:43:00 INFO mapred.JobClient: map 100% reduce 100%
14/05/25 13:43:01 INFO mapred.JobClient: Job complete: job_201405251213_0027
14/05/25 13:43:01 INFO mapred.JobClient: Counters: 26
...
14/05/25 13:43:01 INFO mapred.JobClient:
14/05/25 13:43:01 INFO mapred.JobClient:
14/05/25 13:43:01 INFO mapred.JobClient:
14/05/25 13:43:01 INFO mapred.JobClient:
14/05/25 13:43:01 INFO mapred.JobClient:
14/05/25 13:43:01 INFO mapred.JobClient:
14/05/25 13:43:01 INFO mapred.JobClient:
14/05/25 13:43:01 INFO mapred.JobClient:
14/05/25 13:43:01 INFO mapred.JobClient:
14/05/25 13:43:01 INFO mapred.JobClient:
14/05/25 13:43:01 INFO mapred.JobClient:
14/05/25 13:43:01 INFO mapred.JobClient:
14/05/25 13:43:01 INFO mapred.JobClient:
14/05/25 13:43:01 INFO mapred.JobClient:

Map output materialized bytes=654
Map input records=6
Reduce shuffle bytes=654
Spilled Records=12
Map output bytes=42
Total committed heap usage (bytes)=2696192000
Combine input records=0
SPLIT_RAW_BYTES=1140
Reduce input records=6
Reduce input groups=2
Combine output records=0
Reduce output records=2
Map output records=6

Map-Reduce Framework

411

16.7.1.4

Inspecting Outputs

# hadoop fs -cat /triangles/tmp1/part*
1,2 0
2,1 0
2,3 0
2,4 0
2,5 0
1,3 2
1,4 2
1,5 2
3,4 2
3,5 2
4,5 2
3,2 0
3,4 0
2,4 3
4,2 0
4,3 0
4,5 0
2,3 4
2,5 4
3,5 4
5,2 0
5,4 0
2,4 5

# hadoop fs -cat /triangles/tmp2/part*
4,5,2
2,3,4
2,4,3
2,4,5
2,5,4
3,4,2

# hadoop fs -cat /triangles/output/part*
2,3,4
2,4,5

412

16.8 Spark Implementation

Hadoop implementation for ﬁnding all unique triangles comprised of 3 dis-
tinct MapReduce jobs (each job had a map() and reduce() functions). Since
Spark oﬀers a high-level API for mappers and reducers, we present the Spark
solution in a single Java class, which has 9 steps. First, we present all these
9 steps and then we will dissect each step.

For Spark implementation, we closely follow the 3-phase MapReduce al-

gorithms presented for the Hadoop implementation.

Listing 16.1: Spark’s High Level Solution

1 // STEP-0: import required classes and interfaces
2 public class CountTriangles {
3

4

5

6

7

8

9

10

11

12

13

14

15

16

public static void main(String[] args) throws Exception {

// STEP-1: Read and validate input parameters
// STEP-2: create a JavaSparkContext object
// STEP-3: read an HDFS input text file representing a graph,
//
records are represented as JavaRDD<String>
// STEP-4: crete a new JavaPairRDD for all edges, which includes
//
// STEP-5: crete a new JavaPairRDD, which will generate triads
// STEP-6: crete a new JavaPairRDD, representing all possible triads
// STEP-7: crete a new JavaPairRDD, which will generate triangles
// STEP-8: crete a new JavaPairRDD, representing all triangles
// Step-9: eliminate duplicate triangles and create unique triangles
System.exit(0);

(source, destination) and (destination, source)

}

17
18 }

Next, we present each step in detail. and ﬁnally we will have a sample

run of the Spark solution.

16.8.1 STEP-0: Import Required Classes and Inter-

faces

Spark’s binary distribution provides required JAR ﬁles. We import required
classes and interfaces from theses JAR ﬁles. Most of the classes and interfaces
are deﬁned in the org.apache.spark.api.java package.

413

Listing 16.2: STEP-0: import required classes and interfaces

1 // STEP-0: import required classes and interfaces
2 import scala.Tuple2;
3 import scala.Tuple3;
4
5 import org.apache.spark.api.java.JavaRDD;
6 import org.apache.spark.api.java.JavaPairRDD;
7 import org.apache.spark.api.java.JavaSparkContext;
8 import org.apache.spark.api.java.function.PairFlatMapFunction;
9 import org.apache.spark.api.java.function.FlatMapFunction;
10
11 import java.util.Arrays;
12 import java.util.List;
13 import java.util.ArrayList;
14 import java.util.Collections;

16.8.2 STEP-1: Read Input Parameters

This step reads the ”spark master node” (to connect to Spark cluster) and
”HDFS input ﬁle”, which represents our input graph as a set of edges in the
form of (source, destination) and (destination, source).

Listing 16.3: STEP-1: Read and validate input parameters

// STEP-1: Read and validate input parameters
if (args.length < 2) {

System.err.println("Usage: CountTriangles <spark-master> <hdfs-file>");
System.exit(1);

}
String sparkMaster = args[0];
String hdfsFile = args[1];

1

2

3

4

5

6

7

16.8.3 STEP-2: Create a Spark Context Object

Using the spark master node name, we create a JavaSparkContext object,
that returns JavaRDDs and works with Java collections. For this step, you
need to deﬁne two environment variables: SPARK_HOME and SPARK_EXAMPLES_JAR.
Once we create a JavaSparkContext object, we next will be able to cre-
ate and manipulate our data with RDDs. For example, if your spark clus-
ter is comprised of 4 servers { myserver100, myserver200, myserver300,
myserver400 } and spark master is represented by myserver100, then your
args[0] might have the value: spark://myserver100:7077. Note that port
number 7077 is conﬁgurable parameter in the spark cluster enviroment.

414

1

2

3

4

5

6

7

1

2

3

4

Listing 16.4: STEP-2: Create a Spark Context Object

// STEP-2: create a JavaSparkContext object
// This is the object for creating the first RDD
JavaSparkContext ctx = new JavaSparkContext(

sparkMaster, // spark master
"MyJavaWordCount",
System.getenv("SPARK_HOME"),
System.getenv("SPARK_EXAMPLES_JAR"));

16.8.4 STEP-3: Read Graph via HDFS Input

In this step, our input graph (represented by args[1]) is read by JavaSparkContext
object and the ﬁrst JavaRDD<String> is created. For example, we used
HDFS ﬁle /triangles/sample graph.txt as an input ﬁle to represent our
input graph. Spark’s main abstraction is a distributed collection of items
called a Resilient Distributed Dataset (RDD). RDDs can be created from
Hadoop InputFormats (such as HDFS ﬁles) or by transforming other RDDs.
Spark’s RDDs have actions (such as reduce() and collect()), which return
values, and transformations (such as map(), ﬂatMap(), ﬂatMapToPair(),
union(), and ﬁlter()), which return pointers to new RDDs.

Listing 16.5: STEP-3: read an hdfs input text ﬁle representing a graph

// STEP-3: read an hdfs input text file representing a graph,
//
// args[1] = HDFS text file: /triangles/sample_graph.txt
JavaRDD<String> lines = ctx.textFile(hdfsFile, 1);

records are represented as JavaRDD<String>

16.8.5 STEP-4: Create All Graph Edges

This step creates a new JavaPairRDD<Long,Long> from a set of edges repre-
sented as lines (as JavaRDD<String>). So we convert each edge (as ”nodeA
nodeB”) into two pairs as

(nodeA, nodeB)
(nodeB, nodeA)

415

Note that edges must be reciprocal, that is every source, destination edge
must have a corresponding destination, source. To accomplish our mapping
we use PairFlatMapFunction<T, K, V>, where T is input and K and V are
outputs (creating a (key=K, value=V) pair). Using Spark’s JavaRDD.flatMapToPair()
method, we generate all required (key,value) pairs (represented as JavaPairRDD<Long,Long>).

Listing 16.6: STEP-4: crete a new JavaPairRDD for all edges

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

// STEP-4: crete a new JavaPairRDD for all edges, which
// includes (source, destination) and (destination, source)
// PairFlatMapFunction<T, K, V>
// T => Iterable<Tuple2<K, V>>
JavaPairRDD<Long,Long> edges =

//

T

K

V

lines.flatMapToPair(new PairFlatMapFunction<String, Long, Long>() {

public Iterable<Tuple2<Long,Long>> call(String s) {

String[] nodes = s.split(" ");
long start = Long.parseLong(nodes[0]);
long end = Long.parseLong(nodes[1]);
// Note that edges must be reciprocal, that is every
// {source, destination} edge must have a corresponding {destination, source}.

return Arrays.asList(new Tuple2<Long, Long>(start, end),

new Tuple2<Long, Long>(end, start));

}
});

16.8.6 STEP-5: Create RDD To Generate Triads

Now that we have all edges, we try to form data structures, which eventu-
ally will create triangles. For every node, we ﬁnd all corresponding desti-
nations, which might form possible triads. To accomplish this task, we use
JavaPairRDD.groupByKey(). The new RDD will be denoted by JavaPairRDD<Long, Iterable<Long>>.
Note that values are returned as Iterable<Long> instead of List<Long>.
This is another high-level abstraction by Spark to keep implementation hid-
den from users (for possible optimizations by Spark platform – Spark can im-
plement Iterable<Long> by ArrayList, LinkedList, or other proper data
structures.

// STEP-5: crete a new JavaPairRDD, which will generate triads
JavaPairRDD<Long, Iterable<Long>> triads = edges.groupByKey();

For debugging STEP-5, we collect all triads objects and display them:

416

// STEP-5.1: debug1
List<Tuple2<Long, Iterable<Long>>> debug1 = triads.collect();
for (Tuple2<Long, Iterable<Long>> t2 : debug1) {

System.out.println("debug1 t2._1="+t2._1);
System.out.println("debug1 t2._2="+t2._2);

}

16.8.7 STEP-6: Create All Possible Triads

This step create all possible triads (candidates for further checking that they
form a triangle). To implement this step, we use JavaPairRDD.flatMapToPair()
function to create proper (key,value) pairs, where key is an edge (represented
by a Tuple2<node1,node2> and value is a node (as a Long data type). One
thing you should note that all RDDs are immutable, this means that they
are READ-ONLY and can not be modiﬁed, altered, sorted in any way. If you
want to sort your RDD’s then clone them and then do your transformation
or action.

Listing 16.7: STEP-6: crete a new JavaPairRDD, which will generate possible

triads

// STEP-6: crete a new JavaPairRDD, which will generate possible triads

JavaPairRDD<Tuple2<Long,Long>, Long> possibleTriads =

triads.flatMapToPair(

new PairFlatMapFunction<Tuple2<Long, Iterable<Long>>, // input

Tuple2<Long,Long>,
Long
>() {

// key (output)
// value (output)

public Iterable<Tuple2<Tuple2<Long,Long>, Long>>

call(Tuple2<Long, Iterable<Long>> s) {

// s._1 = Long (as a key)
// s._2 = Iterable<Long> (as a values)
Iterable<Long> values = s._2;
// we assume that no node has an ID of zero
List<Tuple2<Tuple2<Long,Long>, Long>> result =

new ArrayList<Tuple2<Tuple2<Long,Long>, Long>>();

// Generate possible triads.
for (Long value : values) {

Tuple2<Long,Long> k2 = new Tuple2<Long,Long>(s._1, value);
Tuple2<Tuple2<Long,Long>, Long> k2v2 =

new Tuple2<Tuple2<Long,Long>, Long>(k2, 0l);

result.add(k2v2);

417

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

}

// RDD’s values are immutable, so we have to copy the values
// copy values to valuesCopy
List<Long> valuesCopy = new ArrayList<Long>();
for (Long item : values) {
valuesCopy.add(item);

}
Collections.sort(valuesCopy);

// Generate possible triads.
for (int i=0; i< valuesCopy.size() -1; ++i) {

for (int j=i+1; j< valuesCopy.size(); ++j) {

Tuple2<Long,Long> k2 =

new Tuple2<Long,Long>(valuesCopy.get(i), valuesCopy.get(j));

Tuple2<Tuple2<Long,Long>, Long> k2v2 =

new Tuple2<Tuple2<Long,Long>, Long>(k2, s._1);

result.add(k2v2);

}

}

return result;

}

});

For debugging STEP-6, we collect all possibleTriads objects and dis-

play them:

// STEP-6.1: debug2
List<Tuple2<Tuple2<Long,Long>, Long>> debug2 =

possibleTriads.collect();

for (Tuple2<Tuple2<Long,Long>, Long> t2 : debug2) {

System.out.println("debug2 t2._1="+t2._1);
System.out.println("debug2 t2._2="+t2._2);

}

16.8.8 STEP-7: Create RDD To Generate Triangles

This step create an RDD, which will be used to generate the actual triangles.
The resulting JavaPairRDD will have an edge (represented as Tuple2<Long,Long>)
and a set of nodes (represented as Iterable<Long>) for possible triangle for-
mation.

418

Listing 16.8: STEP-7: crete a new JavaPairRDD, which will generate trian-

gles

1

2

3

4

5

6

7

8

9

// STEP-7: crete a new JavaPairRDD, which will generate triangles

JavaPairRDD<Tuple2<Long,Long>, Iterable<Long>> triadsGrouped =

possibleTriads.groupByKey();

// STEP-7.1: debug3

List<Tuple2<Tuple2<Long,Long>, Iterable<Long>>> debug3 = triadsGrouped.collect();
for (Tuple2<Tuple2<Long,Long>, Iterable<Long>> t2 : debug3) {

System.out.println("debug3 t2._1="+t2._1);
System.out.println("debug3 t2._2="+t2._2);

10

}

16.8.9 STEP-8: Create All Triangles

This step generates all possible triangles, but it will include duplicates. We
use a FlatMapFunction, which works as:

FlatMapFunction<T, R>
T => Iterable<R>

where T is an input and Iterable<R> is an output. In our case:

T = Tuple2<Tuple2<Long,Long>, Iterable<Long>>
R = Tuple3<Long,Long,Long>

T = Tuple2 (Tuple2(nodeA,nodeB), <node1,node2, ...>)
R = Tuple3(nodeA,nodeB,nodeC> as a triangle
where nodeC in {node1, node2, ...}

This step is accomplished by calling JavaPairRDD.flatMap() function.

Listing 16.9: STEP-8: crete a new JavaPairRDD, which will generate all tri-

angles

1

2

3

// STEP-8: crete a new JavaPairRDD, which will generate all triangles

JavaRDD<Tuple3<Long,Long,Long>> trianglesWithDuplicates =

triadsGrouped.flatMap(new FlatMapFunction<

419

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

Tuple2<Tuple2<Long,Long>, Iterable<Long>>, // input
Tuple3<Long,Long,Long>

// output

>() {

public Iterable<Tuple3<Long,Long,Long>>

call(Tuple2<Tuple2<Long,Long>, Iterable<Long>> s) {

// s._1 = Tuple2<Long,Long> (as a key) = "<nodeA><,><nodeB>"
// s._2 = Iterable<Long> (as a values) = {0, n1, n2, n3, ...} or {n1, n2, n3, ...}
// note that 0 is a fake node, which does not exist
Tuple2<Long,Long> key = s._1;
Iterable<Long> values = s._2;
// we assume that no node has an ID of zero

List<Long> list = new ArrayList<Long>();
boolean haveSeenSpecialNodeZero = false;
for (Long node : values) {

if (node == 0) {

haveSeenSpecialNodeZero = true;

}
else {

list.add(node);

}

}

List<Tuple3<Long,Long,Long>> result =

new ArrayList<Tuple3<Long,Long,Long>>();

if (haveSeenSpecialNodeZero) {

if (list.isEmpty()) {

// no triangles found
return result;

}
// emit triangles
for (long node : list) {

long[] aTraingle = {key._1, key._2, node};
Arrays.sort(aTraingle);
Tuple3<Long,Long,Long> t3 =

new Tuple3<Long,Long,Long>(aTraingle[0], aTraingle[1], aTraingle[2]);

result.add(t3);

}

}
else {

// no triangles found
return result;

}

return result;

}

});

To debug this step, we use JavaRDD.collect() method.

// STEP-8.1: debug4: print all triangles (includes duplicates)
System.out.println("=== Triangles with Duplicates ===");

420

List<Tuple3<Long,Long,Long>> debug4 = trianglesWithDuplicates.collect();
for (Tuple3<Long,Long,Long> t3 : debug4) {

//System.out.println(t3._1 + "," + t3._2+ "," + t3._3);
System.out.println("t3="+t3);

}

16.8.10 Step-9: Create Unique Triangles

Spark provides a very powerful API to ﬁnd distinct elements for a given
RDD. JavaRDD<Tuple3<Long,Long,Long>>.distinct() will create a new
JavaRDD<Tuple3<Long,Long,Long>>, where are elements are distinct.

Listing 16.10: Step-9: eliminate duplicate triangles and create unique trian-

gles

// Step-9: eliminate duplicate triangles and create unique triangles
JavaRDD<Tuple3<Long,Long,Long>> uniqueTriangles = trianglesWithDuplicates.distinct();

// Step-9.1: print unique triangles
System.out.println("=== Unique Triangles ===");
List<Tuple3<Long,Long,Long>> output = uniqueTriangles.collect();
for (Tuple3<Long,Long,Long> t3 : output) {

//System.out.println(t3._1 + "," + t3._2+ "," + t3._3);
System.out.println("t3="+t3);

1

2

3

4

5

6

7

8

9

10

}

16.9 Spark Sample Run

Here we show a complete run of Spark’s program for counting triangles.

16.9.1

Input

We use HDFS as an input medium:

# hadoop fs -ls /triangles/
Found 1 items
-rw-r--r--

3 hadoop root,hadoop

24 2014-05-25 17:45 /triangles/sample_graph.txt

# hadoop fs -cat /triangles/sample_graph.txt
1 2
2 3
2 4

421

2 5
3 4
4 5

16.9.2 Script

We use a convenient shell script to run our Spark program:

# cat run_count_triangles.sh
#!/bin/bash
source /home/hadoop/conf/env_2.3.0.sh
export SPARK_HOME=/home/hadoop/spark-1.0.0
source /home/hadoop/spark_mahmoud_examples/spark_env_yarn.sh
source $SPARK_HOME/conf/spark-env.sh

# system jars:
CLASSPATH=$CLASSPATH:$HADOOP_HOME/etc/hadoop
#
jars=‘find $SPARK_HOME -name ’*.jar’‘
for j in $jars ; do

CLASSPATH=$CLASSPATH:$j

done

# app jar:
export CLASSPATH=/home/hadoop/spark_mahmoud_examples/mp.jar:$CLASSPATH
export SPARK_CLASSPATH=$CLASSPATH
export SPARK_MASTER=spark://myserver100:7077
export INPUT=/triangles/sample_graph.txt
export OPTIONS="-Dsun.lang.ClassLoader.allowArraySyntax=true -Dspark.master=$SPARK_MASTER"
$JAVA_HOME/bin/java -cp $CLASSPATH

$OPTIONS CountTriangles $SPARK_MASTER $INPUT

16.9.3 Running Script

The output log is trimmed to ﬁt the page.

# ./run_count_triangles.sh
...
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
14/06/03 15:15:49 WARN spark.SparkConf: null jar passed to SparkContext constructor
...
14/06/03 15:15:59 INFO scheduler.DAGScheduler: Completed ResultTask(0, 0)
14/06/03 15:15:59 INFO scheduler.TaskSetManager: Finished TID 1 in 112 ms on myserver100 (progress: 1/1)
14/06/03 15:15:59 INFO scheduler.TaskSchedulerImpl: Removed TaskSet 0.0, whose tasks have all completed, from pool
14/06/03 15:15:59 INFO scheduler.DAGScheduler: Stage 0 (collect at CountTriangles.java:45) finished in 0.145 s
14/06/03 15:15:59 INFO spark.SparkContext: Job finished: collect at CountTriangles.java:45, took 4.383103788 s
debug1 t2._1=4
debug1 t2._2=[2, 3, 5]
debug1 t2._1=1
debug1 t2._2=[2]
debug1 t2._1=3
debug1 t2._2=[2, 4]

422

debug1 t2._1=5
debug1 t2._2=[2, 4]
debug1 t2._1=2
debug1 t2._2=[1, 3, 4, 5]
14/06/03 15:15:59 INFO spark.SparkContext: Starting job: collect at CountTriangles.java:92
...
14/06/03 15:15:59 INFO scheduler.DAGScheduler: Stage 2 (collect at CountTriangles.java:92) finished in 0.040 s
14/06/03 15:15:59 INFO scheduler.TaskSchedulerImpl: Removed TaskSet 2.0, whose tasks have all completed, from pool
14/06/03 15:15:59 INFO spark.SparkContext: Job finished: collect at CountTriangles.java:92, took 0.05745656 s
debug2 t2._1=(4,2)
debug2 t2._2=0
debug2 t2._1=(4,3)
debug2 t2._2=0
debug2 t2._1=(4,5)
debug2 t2._2=0
debug2 t2._1=(2,3)
debug2 t2._2=4
debug2 t2._1=(2,5)
debug2 t2._2=4
debug2 t2._1=(3,5)
debug2 t2._2=4
debug2 t2._1=(1,2)
debug2 t2._2=0
debug2 t2._1=(3,2)
debug2 t2._2=0
debug2 t2._1=(3,4)
debug2 t2._2=0
debug2 t2._1=(2,4)
debug2 t2._2=3
debug2 t2._1=(5,2)
debug2 t2._2=0
debug2 t2._1=(5,4)
debug2 t2._2=0
debug2 t2._1=(2,4)
debug2 t2._2=5
debug2 t2._1=(2,1)
debug2 t2._2=0
debug2 t2._1=(2,3)
debug2 t2._2=0
debug2 t2._1=(2,4)
debug2 t2._2=0
debug2 t2._1=(2,5)
debug2 t2._2=0
debug2 t2._1=(1,3)
debug2 t2._2=2
debug2 t2._1=(1,4)
debug2 t2._2=2
debug2 t2._1=(1,5)
debug2 t2._2=2
debug2 t2._1=(3,4)
debug2 t2._2=2
debug2 t2._1=(3,5)
debug2 t2._2=2
debug2 t2._1=(4,5)
debug2 t2._2=2
14/06/03 15:15:59 INFO spark.SparkContext: Starting job: collect at CountTriangles.java:100
14/06/03 15:15:59 INFO scheduler.DAGScheduler: Registering RDD 7 (flatMapToPair at CountTriangles.java:51)
...
14/06/03 15:16:02 INFO scheduler.DAGScheduler: Stage 4 (collect at CountTriangles.java:100) finished in 2.552 s
14/06/03 15:16:02 INFO spark.SparkContext: Job finished: collect at CountTriangles.java:100, took 3.305817554 s
debug3 t2._1=(4,5)
debug3 t2._2=[0, 2]
debug3 t2._1=(1,4)
debug3 t2._2=[2]
debug3 t2._1=(4,2)
debug3 t2._2=[0]
debug3 t2._1=(3,5)
debug3 t2._2=[4, 2]
debug3 t2._1=(2,3)
debug3 t2._2=[4, 0]
debug3 t2._1=(5,4)
debug3 t2._2=[0]
debug3 t2._1=(2,4)
debug3 t2._2=[3, 5, 0]
debug3 t2._1=(1,2)
debug3 t2._2=[0]
debug3 t2._1=(3,2)

423

debug3 t2._2=[0]
debug3 t2._1=(2,5)
debug3 t2._2=[4, 0]
debug3 t2._1=(1,5)
debug3 t2._2=[2]
debug3 t2._1=(3,4)
debug3 t2._2=[0, 2]
debug3 t2._1=(4,3)
debug3 t2._2=[0]
debug3 t2._1=(2,1)
debug3 t2._2=[0]
debug3 t2._1=(1,3)
debug3 t2._2=[2]
debug3 t2._1=(5,2)
debug3 t2._2=[0]
=== Triangles with Duplicates ===
14/06/03 15:16:02 INFO spark.SparkContext: Starting job: collect at CountTriangles.java:158
...
14/06/03 15:16:02 INFO scheduler.DAGScheduler: Stage 7 (collect at CountTriangles.java:158) finished in 0.050 s
14/06/03 15:16:02 INFO spark.SparkContext: Job finished: collect at CountTriangles.java:158, took 0.063394393 s
t3=(2,4,5)
t3=(2,3,4)
t3=(2,3,4)
t3=(2,4,5)
t3=(2,4,5)
t3=(2,3,4)
=== Unique Triangles ===
14/06/03 15:16:02 INFO spark.SparkContext: Starting job: collect at CountTriangles.java:168
14/06/03 15:16:02 INFO scheduler.DAGScheduler: Registering RDD 14 (distinct at CountTriangles.java:165)
...
14/06/03 15:16:02 INFO scheduler.DAGScheduler: Stage 10 (collect at CountTriangles.java:168) finished in 0.044 s
14/06/03 15:16:02 INFO spark.SparkContext: Job finished: collect at CountTriangles.java:168, took 0.147241806 s
t3=(2,3,4)
t3=(2,4,5)

424

Chapter 17

K-mer Counting

17.1

Introduction to K-mers

A K-mer is a substring of length k, and counting the occurrences of all
such substrings is a central step in many analyses of DNA sequence data.
Counting K-mers for a DNA sequence means ﬁnding frquencies of K-mers
for the entire sequence.
In bioinformatics, counting K-mers is used for
genome and transcriptome assembly, metagenomic sequencing, and for er-
ror correction of sequence reads. Although simple in principle, counting
K-mers is a big data problem, since DNA sequnces can total up to sev-
eral billions DNA code. K-mer counting problem has been deﬁned in http:
//schatzlab.cshl.edu/teaching/exercises/hadoop/.

The goal of this chapter is to provide a complete K-mer solution using
Spark/Hadoop. Our implementation discovers all K-mers for a given K > 0
and ﬁnds top-N K-mers for a given N > 0.

A K-mer is a DNA word of length k. For example, if a sample DNA sequence
is ”CACACACAGT,” then the following are 3-mers and 5-mers for that
sequence:

original sequence: CACACACAGT
3-mers:

CAC

ACA

CAC

425

ACA

CAC

ACA

CAG

AGT

original sequence: CACACACAGT
5-mers:

CACAC

ACACA

CACAC

ACACA

CACAG

ACAGT

Given a DNA sequence (call it string S – alphabet is {A, C, G, T, · · ·}), we are
interested in counting the number of occurrences in S of every substring of
length k. Typically DNA sequences are represented as a FASTQ ﬁle format
(every 4 lines of input ﬁle is a single sequence). Note that a given DNA
sample may have billions of sequences.

What are the applications of counting K-mers?

Counting the K-mers in a DNA sequence is a very important step in many
bioinformatics applications. The following are examples of applications of
K-mer counting:

• Use K-mer frequencies to ﬁnd out if a misalignment between reads is a

sequencing error or a genuine diﬀerence in sequence.

• Use K-mer frequencies to detect repeated sequences, such as trans-
posons, which is an important factor for biological role applications

• Use K-mer frequencies to correct short-read assembly errors

• Use K-mer frequencies to compute metrics such as relatedness and

unique enough (useful in metagenomic applications)

426

17.2 K-mer counting using MapReduce

Conceptually, K-mer counter using MapReduce is similar to the ”word count”
program, but since there are no spaces in the human genome, we will count
overlapping K-mers instead of discrete words.

17.2.1 K-mer counting using MapReduce: map()

The idea is if the genome sequence is: CACACACAGT and we are counting
3-mers, then the map() function will output the following (key, value) pairs:

CAC
ACA
CAC
ACA
CAC
ACA
CAG
AGT

1
1
1
1
1
1
1
1

Listing 17.1: K-mer Counting map() Function

1 /**
2 * @param key is generated by MapReduce, ignored here
3 * @param sequence (as value) is one line of input for a given genome sequence
4 */
5 map(Long key, String sequence) {
6

// we will get the value of K (K-mer) from setup()
// or broadcast which will be called once
for (int i=0; i < sequence.length()-K+1 ; i++) {
String kmer = sequence.substring(i, K+i);
emit(kmer, 1));

7

8

9

10

}

11
12 }

17.2.2 K-mer counting using MapReduce: reduce()

The sort and shuﬄe function will sort them (output of map()) so the same
key comes right after each other:

427

ACA
ACA
ACA
CAC
CAC
CAC
CAG
AGT

1
1
1
1
1
1
1
1

Finally, the reduce() function will output:

ACA
CAC
CAG
AGT

3
3
1
1

Listing 17.2: K-mer Counting reduce() Function

1 /**
2 * @param key is the unique kmer generated by mappers
3 * @param value is a list of integers (partial count of a kmer)
4 */
5 reduce(String key, List<integer> value) {
6

int sum = 0;
for (int count : value) {

7

8

9

10
11 }

sum += count;

}
emit(key, sum);

17.2.3 K-mer Counting with MapReduce and Hadoop

I have provided a complete solution of K-mer counting by 4 small classes:

• KmerCountDriver (Mapreduce job driver)

• KmerCountMapper (deﬁnes map() function)

• KmerCountReduce (deﬁnes reduce() function)

• KmerUtil (generates K-mers for a given k)

428

17.3

Input Data for K-mer Counting

For input, we will use FASTQ format. FASTQ is a concise and compact
format, which stores DNA sequences in a text ﬁle. Each consecutive 4 lines
in a FASTQ ﬁle represent a single sequence. For example, the following 4
lines represent a sequence:

LINE-1: @EAS54_6_R7_30800
LINE-2: GTTGCTTCCCGCGTGGGTGGGTCGGGG
LINE-3: +EAS54_6_R7
LINE-4: ;;;;;;;33;;;;9;7;;.7;393333

LINE-2 represents the sequence (the other lines are ignored for K-mer count-
ing). For details on FASTQ ﬁles, see http://maq.sourceforge.net/fastq.
shtml. To read FASTQ ﬁle format, we do need to understand the format
speciﬁction. LINE-1 begins with @, LINE-3 begins with +, and LINE-4 be-
gins with ! or ~. Therefore, we will discard all lines except LINE-2, which
represents the sequence to be analyzed.

You may use the following sample data to test your K-mer counting.

• ecoli genome from: http://schatzlab.cshl.edu/teaching/exercises/

hadoop/data/ecoli.fa.gz

• human genome from: http://hgdownload.cse.ucsc.edu/goldenpath/
hg19/chromosomes/. Note that hg19 means human genome, build 19.

17.3.1 Sample Runs of K-mer Counting

Now, you may use the K-mer counting solution to answer the following ques-
tions:

• What are the top 10 most frequently occurring 9-mers in E coli?

• What are the top 10 most frequently occurring 9-mers in hg19?

• What are the top 10 most frequently occurring 21-mers in hg19?

429

Figure 17.1: K-mer MapReduce WorkFlow

17.4 K-mer Implementation in Spark

K-mer MapReduce workﬂow implementation is provided below:

Assume that we want to discover K-mers (for a given K > 0) and top-N
(for a given N > 0) for a set of FASTQ ﬁles. Since FASTQ ﬁle format is
very well-deﬁned, ﬁrst we create a JavaRDD<String> for the given FASTQ
ﬁle. Next, we remove the records, which are not sequences (lines similar
to LINE-1, LINE-3, and LINE-4). This ﬁltering is implemented by the
JavaRDD.filter() function. Once, we have only sequences, then we cre-
ate (K, 1) pairs, where K is a K-mer. Then, we ﬁnd frequency of kmers.
Finally, we can ﬁnd top-N kmers for N > 0. Finding top-N is simple: we

430

assume that (K2,V2) are partitioned (K2 is a kmer and V2 is the frequency
of K2), then we map each partition into top-N and then once we have a list
of top-N (one top-N from each partition), then we may do the ﬁnal reduction
to ﬁnd top-N.

We have 3 inputs to our Spark program:

• FASTQ ﬁle: stored in HDFS

• K > 0 to ﬁnd K-mers

• N > 0 to ﬁnd top-N K-mers

Spark solution is implemented a single Java driver class; this is possible
due to high abstraction of Spark API. First, the entire solution is presented
as a set of 10 high-level steps, then each step is implemented as a Java/Spark
API.

17.4.1 K-mer High-Level Solution in Spark

Listing 17.3: K-mer High-Level Solution in Spark

1 // STEP-0: import required classes and interfaces
2 public class Kmer {
3

static JavaSparkContext createJavaSparkContext() throws Exception {...}

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

public static void main(String[] args) throws Exception {

// STEP-1: handle input parameters
// STEP-2: create a Spark context object
// STEP-3: broadcast K and N as global shared objects,
// which can be accessed from all cluster nodes
// STEP-4: read FASTQ file from HDFS and create the first RDD
// STEP-5: filter redundant records
// STEP-6: generate K-mers
// STEP-7: combine/reduce frequent kmers
// STEP-8: create a local top-N for all partitions
// STEP-9: now collect all topN from all partitions
// and find final topN from all partitions
// STEP-10: emit final topN descending
System.exit(0);

}

19
20 }

431

17.4.2 STEP-0: import required classes and interfaces

Listing 17.4: STEP-0: import required classes and interfaces

1 // STEP-0: import required classes and interfaces
2 import java.util.Map;
3 import java.util.SortedMap;
4 import java.util.TreeMap;
5 import java.util.List;
6 import java.util.ArrayList;
7 import java.util.Iterator;
8 import java.util.Collections;
9 import scala.Tuple2;
10 import scala.Tuple3;
11 import org.apache.spark.SparkConf;
12 import org.apache.spark.api.java.JavaRDD;
13 import org.apache.spark.api.java.JavaPairRDD;
14 import org.apache.spark.api.java.JavaSparkContext;
15 import org.apache.spark.api.java.function.PairFlatMapFunction;
16 import org.apache.spark.api.java.function.FlatMapFunction;
17 import org.apache.spark.api.java.function.Function;
18 import org.apache.spark.api.java.function.Function2;
19 import org.apache.spark.broadcast.Broadcast;

17.4.3

createJavaSparkContext()

To create RDDs, you need an instance of a JavaSparkContext, which is a
factory class for creating JavaRDD and JavaPairRDD objects. Note that here,
I have hard-coded the hostname (as myserver100) for YARN’s ”resourcem-
anager”. For deploying to production environments, you should read these
values from a conﬁguration ﬁle.

Listing 17.5: createJavaSparkContext()

1

2

3

4

5

6

7

8

9

10

11

12

static JavaSparkContext createJavaSparkContext() throws Exception {

SparkConf conf = new SparkConf();
conf.set("yarn.resourcemanager.hostname", "myserver100");
conf.set("yarn.resourcemanager.scheduler.address", "myserver100:8030");
conf.set("yarn.resourcemanager.resource-tracker.address", "myserver100:8031");
conf.set("yarn.resourcemanager.address",
conf.set("mapreduce.framework.name", "yarn");
conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
conf.set("spark.executor.memory", "1g");
JavaSparkContext ctx = new JavaSparkContext("yarn-cluster", "Kmer", conf);
return ctx;

"myserver100:8032");

}

432

1

2

3

4

5

6

7

8

1

2

17.4.4 STEP-1: handle input parameters

This step reads 3 required inputs (FASTQ ﬁle, K – size of kmer – , and N –
for topN) from the command line.

Listing 17.6: STEP-1: handle input parameters

// STEP-1: handle input parameters
if (args.length < 3) {

System.err.println("Usage: Kmer <fastq-file> <K> <N>");
System.exit(1);

}
final String fastqFileName = args[0];
final int K =
final int N =

Integer.parseInt(args[1]); // to find K-mers
Integer.parseInt(args[2]); // to find top-N

// FASTQ file as input

17.4.5 STEP-2: create a Spark context object

We use Kmer.createJavaSparkContext() to create a JavaSparkContext ob-
ject.

Listing 17.7: STEP-2: create a Spark context object

// STEP-2: create a Spark context object
JavaSparkContext ctx = createJavaSparkContext();

17.4.6 STEP-3: broadcast global shared objects

In Spark framework, to use shared objects in all cluster nodes, we can broad-
cat them and read these from map() and reduce() functions. To make an
object sharable, we use the following API:

T t = <an-instance-of-T>;
Broadcast<T> broadcastT = ctx.broadcast(t);

To access the broadcasted object (shared object) from any cluster node, we
use the following API:

T t = broadcastT.value();

433

Since K (K-mer size) and N (for top-N) are required from all cluster nodes,
we broadcast these two values as:

Listing 17.8: STEP-3: broadcast K and N as global shared objects

// STEP-3: broadcast K and N as global shared objects,
// which can be accessed from all cluster nodes
final Broadcast<Integer> broadcastK = ctx.broadcast(K);
final Broadcast<Integer> broadcastN = ctx.broadcast(N);

17.4.7 STEP-4: read FASTQ ﬁle from HDFS and cre-

ate the ﬁrst RDD

This step reads a FASTQ ﬁle and creates a JavaRDD<String> object, where
each record of FASTQ ﬁle is represented as a String object.

Listing 17.9: STEP-4: read FASTQ ﬁle from HDFS and create the ﬁrst RDD

// STEP-4: read FASTQ file from HDFS and create the first RDD
JavaRDD<String> records = ctx.textFile(fastqFileName, 1);
records.saveAsTextFile("/kmers/output/1");

Output of this step is shown below.

1

2

3

4

1

2

3

# hadoop fs -cat /kmers/output/1/part*
@EAS54_6_R1_2_1_413_324
CCCTTCTTGTCCCCAGCGTTTCTCC
+
;;3;;;;;;;;;;;;7;;;;;;;88
@EAS54_6_R1_2_1_540_792
TTGGCAGGCCAAGGCCGATGGATCA
+
;;;;;;;;;;;7;;;;;-;;;3;83
@EAS54_6_R1_2_1_443_348
GTTGCTTCTGGCGTGGGTGGGGGGG
+EAS54_6_R1_2_1_443_348
;;;;;;;;;;;9;7;;.7;393333
@EAS54_6_R1_2_1_413_324
CCCCCCTTGTCTTCAGCCCTTCTCC

434

+
;;3;;;;;;;;;;;;7;;;;;;;88
@EAS54_6_R1_2_1_540_792
TTTTCAGGCCAAGGCCGATGGATCA
+
;;;;;;;;;;;7;;;;;-;;;3;83
@EAS54_6_R1_2_1_443_348
GTTGTTTCTGGCGTGGGTGGGGGGG
+EAS54_6_R1_2_1_443_348
;;;;;;;;;;;9;7;;.7;393333
@EAS54_6_R1_2_1_443_348
GTTGTTTCTGGCGTGGGTGGCCCCC
+EAS54_6_R1_2_1_443_348
;;;;;;;;;;;9;7;;.7;393333

17.4.8 STEP-5: ﬁlter redundant records

This step uses a very powerful Spark API (JavaRDD.filter()) to ﬁlter out
the redundant records before applying the map() function. In a FASTQ ﬁle,
we just keep the records, which represent DNA sequences.

Listing 17.10: STEP-5: ﬁlter redundant records

// STEP-5: filter redundant records
// JavaRDD<T> filter(Function<T,Boolean> f)
// Return a new RDD containing only the elements that satisfy a predicate.
JavaRDD<String> filteredRDD = records.filter(new Function<String,Boolean>() {

public Boolean call(String record) {

String firstChar = record.substring(0,1);
if ( firstChar.equals("@") ||
firstChar.equals("+") ||
firstChar.equals(";") ||
firstChar.equals("!") ||
firstChar.equals("~") ) {

return false; // do not return these records

}
else {

return true;

}

}
});
filteredRDD.saveAsTextFile("/kmers/output/1.5");

Output of this step is shown below.

435

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

# hadoop fs -cat /kmers/output/1.5/part*
CCCTTCTTGTCCCCAGCGTTTCTCC
TTGGCAGGCCAAGGCCGATGGATCA
GTTGCTTCTGGCGTGGGTGGGGGGG
CCCCCCTTGTCTTCAGCCCTTCTCC
TTTTCAGGCCAAGGCCGATGGATCA
GTTGTTTCTGGCGTGGGTGGGGGGG
GTTGTTTCTGGCGTGGGTGGCCCCC

17.4.9 STEP-6: generate K-mers

This step implements the mapper for K-mers by using the JavaRDD.flatMapToPair()
function. The mapper accepts a sequence and K (size of K-mers) and then
generates all (kmer, 1) pairs.

Listing 17.11: STEP-6: generate K-mers

// STEP-6: generate K-mers
// PairFlatMapFunction<T, K, V>
// T => Iterable<Tuple2<K, V>>
JavaPairRDD<String,Integer> kmers = filteredRDD.flatMapToPair(new PairFlatMapFunction<

String,
String,
Integer

>() {

// T
// K
// V

public Iterable<Tuple2<String,Integer>> call(String sequence) {

int K = broadcastK.value();
List<Tuple2<String,Integer>> list = new ArrayList<Tuple2<String,Integer>>();
for (int i=0; i < sequence.length()-K+1 ; i++) {
String kmer = sequence.substring(i, K+i);
list.add(new Tuple2<String,Integer>(kmer, 1));

}
return list;

}

});
kmers.saveAsTextFile("/kmers/output/2");

Partial output of this step is shown below.

# hadoop fs -cat /kmers/output/2/part*
(CCC,1)
(CCT,1)
(CTT,1)
...

436

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

(GGC,1)
(GCC,1)
(CCC,1)
(CCC,1)
(CCC,1)

17.4.10 STEP-7: combine/reduce frequent kmers

This step implements the reducer for K-mers by using the JavaPairRDD.reduceByKey()
function. The reducer accepts a key (as kmer) and values (frequencies of K-
mers) and then generates ﬁnal count of kmers.

Listing 17.12: STEP-7: combine/reduce frequent kmers

1

2

3

4

5

6

7

8

// STEP-7: combine/reduce frequent kmers
JavaPairRDD<String, Integer> kmersGrouped =

kmers.reduceByKey(new Function2<Integer, Integer, Integer>() {
public Integer call(Integer i1, Integer i2) {

return i1 + i2;

}

});
kmersGrouped.saveAsTextFile("/kmers/output/3");

Output of this step is shown below.

# hadoop fs -cat /kmers/output/3/part*
(CTC,2)
(AGC,2)
(CAA,2)
(TGC,1)
(GGC,9)
(GCC,6)
(GCT,1)
(CCT,3)
(TTT,5)
(TGG,12)
(TCC,3)
(CGA,2)
(CCC,11)
(AGG,4)
(GGT,3)

437

(GCA,1)
(CTG,3)
(TGT,4)
(TCA,4)
(GTG,6)
(CTT,6)
(TTC,8)
(CGT,4)
(GGG,13)
(CAG,4)
(GAT,4)
(TTG,6)
(CCA,3)
(AAG,2)
(TCT,7)
(GTT,6)
(GTC,2)
(GCG,4)
(ATG,2)
(CCG,2)
(GGA,2)
(ATC,2)

17.4.11 STEP-8: create a local top-N

This step partitions all (kmer, frequency) pairs into many partitions and
then ﬁnds a top-N for every partition. For every partition, we just keep
the top N (frequency, kmer) (as SortedMap – where TreeMap implements
SortedMap interface). Finding local top-N per partition is implemented by
JavaPairRDD.mapPartitions() method.

Listing 17.13: STEP-8: create a local top-N

1

2

3

4

5

6

// STEP-8: create a local top-N
// now, we have: (K=kmer,V=frequency)
// next step is find the top-N kmers
JavaRDD<SortedMap<Integer, String>> partitions = kmersGrouped.mapPartitions(

new FlatMapFunction<Iterator<Tuple2<String,Integer>>, SortedMap<Integer, String>>() {
@Override

438

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

public Iterable<SortedMap<Integer, String>> call(Iterator<Tuple2<String,Integer>> iter) {

int N = broadcastN.value();
SortedMap<Integer, String> topN = new TreeMap<Integer, String>();
while (iter.hasNext()) {

Tuple2<String,Integer> tuple = iter.next();
String kmer = tuple._1;
int frequency = tuple._2;
topN.put(frequency, kmer);
// keep only top N
if (topN.size() > N) {

topN.remove(topN.firstKey());

}

}
//System.out.println("topN="+topN);
return Collections.singletonList(topN);

}
});

17.4.12 STEP-9: Find Final top-N

This step aggregates all top-N’s generated from all partitions and creates the
ﬁnal top-N for all partitions. For this step, we do need the value of N (for
top-N), which we read it from a broadcasted variable (broadcastN).

Listing 17.14: STEP-9: Find Final top-N

// STEP-9: now collect all topN from all partitions
// and find final topN from all partitions
SortedMap<Integer, String> finaltopN = new TreeMap<Integer, String>();
List<SortedMap<Integer, String>> alltopN = partitions.collect();
for (SortedMap<Integer, String> localtopN : alltopN) {

// frequency = tuple._1
// kmer = tuple._2
for (Map.Entry<Integer, String> entry : localtopN.entrySet()) {

finaltopN.put(entry.getKey(), entry.getValue());
// keep only top N
if (finaltopN.size() > N) {

finaltopN.remove(finaltopN.firstKey());

}

}

}

17.4.13 STEP-10: Emit Final top-N

This step emits the ﬁnal top-N for all kmers.

439

Listing 17.15: STEP-10: Emit Final top-N

1

2

3

4

5

6

// STEP-10: emit final topN descending
System.out.println("=== top " + N + " ===");
List<Integer> frequencies = new ArrayList<Integer>(finaltopN.keySet());
for(int i = frequencies.size()-1; i>=0; i--) {

System.out.println(frequencies.get(i) + "\t" + finaltopN.get(frequencies.get(i)));

}

17.4.14 YARN Script for Spark

This script runs our Spark program in YARN environment.

Listing 17.16: YARN Script for Spark

1 # cat run_kmer.sh
2 #!/bin/bash
3 export SPARK_HOME=/usr/local/spark-1.0.0
4 export HADOOP_HOME=/usr/local/hadoop-2.4.0
5 export JAVA_HOME=/usr/java/jdk7
6 export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop
7 export YARN_CONF_DIR=$HADOOP_HOME/etc/hadoop
8 export MY_JAR=/home/mahmoud/mp.jar
9 export SPARK_JAR=$MP/spark-assembly-1.0.0-hadoop2.4.0.jar
10 #
11 export INPUT=/data/sample.fastq
12 export K=3
13 export N=5
14 $SPARK_HOME/bin/spark-submit --class Kmer \
15

--master yarn-cluster \
--num-executors 12 \
--driver-memory 3g \
--executor-memory 7g \
--executor-cores 12 \
$MY_JAR $INPUT $K

$N

16

17

18

19

20

17.4.15 HDFS Input

# hadoop fs -cat /data/sample.fastq
@EAS54_6_R1_2_1_413_324
CCCTTCTTGTCCCCAGCGTTTCTCC
+
;;3;;;;;;;;;;;;7;;;;;;;88
@EAS54_6_R1_2_1_540_792
TTGGCAGGCCAAGGCCGATGGATCA

440

+
;;;;;;;;;;;7;;;;;-;;;3;83
@EAS54_6_R1_2_1_443_348
GTTGCTTCTGGCGTGGGTGGGGGGG
+EAS54_6_R1_2_1_443_348
;;;;;;;;;;;9;7;;.7;393333
@EAS54_6_R1_2_1_413_324
CCCCCCTTGTCTTCAGCCCTTCTCC
+
;;3;;;;;;;;;;;;7;;;;;;;88
@EAS54_6_R1_2_1_540_792
TTTTCAGGCCAAGGCCGATGGATCA
+
;;;;;;;;;;;7;;;;;-;;;3;83
@EAS54_6_R1_2_1_443_348
GTTGTTTCTGGCGTGGGTGGGGGGG
+EAS54_6_R1_2_1_443_348
;;;;;;;;;;;9;7;;.7;393333
@EAS54_6_R1_2_1_443_348
GTTGTTTCTGGCGTGGGTGGCCCCC
+EAS54_6_R1_2_1_443_348
;;;;;;;;;;;9;7;;.7;393333

17.4.16 Output for Final Top-N

=== top 5 ===
13 GGG
12 TGG
11 CCC
GGC
9
TTC
8

441

Chapter 18

DNA-Sequencing

18.1

Introduction

Today, genome sequencing machines (such as Illumina) are able to generate
hundreds of gigabases of DNA and RNA sequencing data in a day for less
than US$1,000 (few years ago the price was over US$100,000 and the ﬁrst
sequenced human genome cost about US$3 billion – so the price has dropped
considerably!). It is believed that success in the biology and life sciences will
depend on our ability to properly analyze the big data sets that are gener-
ated by these technologies, which in turn requires us to adopt advances in
informatics. MapReduce/Hadoop/Spark enable us to compute and analyze
thousands of gigabytes of data in hours (rather than days or weeks).

In simple terms, DNA-sequencing is the sequencing of whole genomes (such
as human gemones). Following http://dnasequencing.com/: ”if ﬁnding
DNA was the discovery of the exact subtance holding our genetic makeup
information, DNA sequencing is the discovery of the process that will allow
us to READ that information.” The main function of DNA sequencing is
to ﬁnd the precise order of nucleotides within a DNA molecule. Also, DNA
sequencing process is used to determine the order of the four bases – adenine
(A), guanine (G), cytosine (C), and thymine (T) – in a strand of DNA.

What are some of the challenges with DNA-Sequencing? There are many,
but I am listing some of the important ones:

442

• There are several sequencing technology to generate FASTQ ﬁles (the
length of DNA sequences are diﬀerent per sequencing technology)

• Input data (FASTQ data) size is BIG (a single DNA-Seq sample size

can be up to 400-000GB)

• Using a single powerful server, it takes too long (up to 80 hours) to

process one DNA-Seq sample data and get SNP/variants out

• There are many algorithms and steps to run DNA-Seq (selecting proper
combinations of open-source tools is a serious challenge). For example,
there are quite few mapping/alignment algorithms and parameters

• Scalability (optimizing number of mappers and rducers)

A high-level DNA-Sequencing workﬂow is presented below. The focus of this
chapter will be the implementation of ”DNA Sequencing” as a MapReduce
program, which will accept DNA data set as a FASTQ data and ﬁnally it
generate a VCF ﬁle, which has variants for a given set of DNA data sets.

One of the major goal of DNA-Sequecing is to ﬁnd variants (since most of our
DNAs are identical and only very small percent is diﬀerent from each other).
One important objective is the identiﬁcation of genetic variants such as single
nucleotide polymorphisms (SNPs). The identiﬁcation and extraction of SNPs
from the raw genetic sequences involves many algorithms and the application
of a diverse set of tools.

DNA-Sequencing pipeline includes

• Input data validation: quality control of input data such as FASTQ

ﬁles

• Alignment: mapping of short reads to the reference genome

• Recalibration: visualization and post-processing of the alignment in-

cluding base quality recalibration

• Variant detection: the SNP calling procedure along with ﬁltering of

SNP candidates

443

Figure 18.1: High-Level View of DNA Sequencing

444

Figure 18.2: DNA Sequencing Pipeline

445

The DNA Sequencing pipeline is presented below.

There are plenty of data (http://www.1000genomes.org/data) to analyze
and apply DNA-Sequencing and there are lots of open-source algorithms for
these 4 steps outlined above. We do need to understand the choice of the
open-source tools, which signiﬁcantly aﬀects the ﬁnal results.

18.2

Input to DNA-Sequencing

The common format for DNA sequencing is FASTQ format. FASTQ format
is a text-based format for storing both a biological sequence and its quality
scores. For a given FASTQ ﬁle, each 4 record/lines represet a single DNA
sequence. General syntax and an example is given below.

• Syntax:

<fastq>:= <block>+
<block>:=@<seqname>\n<seq>\n[<seqname>]\n<qual>\n
<seqname>:= [A-Za-z0-9_.:-]+
<seq>:= [A-Za-z\n\.~]+
<qual>:= [!-~\n]+

• Example:

@NCYC361-11a03.q1k bases 1 to 1576
GCGTGCCCGAAAAAATGCTTTTGGAGCCGCGCGTGAAAT...
+NCYC361-11a03.q1k bases 1 to 1576
!)))))****(((***%%((((*(((+,**(((+**+,-...

The FASTQ data can be paired or non-paired. If it is paired, then in-
put for a DNA-Sequencing will be a pair of ﬁles: left_file.fastq and
right_file.fastq. If it is non-paired, then there will be a single ﬁle file.fastq.

18.3

Input data validation

This step validates the format of fastq ﬁles. With validation, you want to
make sure that quality of input ﬁles are guaranteed. Input data validation

446

tools help to provide a way to do some quality control checks on raw sequence
data (for example in FASTQ ﬁle format) coming from high throughput se-
quencing pipelines.

There are lots of open-source tools for input data validation. For example,

for FASTQ validation you may use the following open-source tools:

• FastQValidator (http://genome.sph.umich.edu/wiki/FastQValidator)

• FastQC (http://www.bioinformatics.babraham.ac.uk/projects/fastqc)

Input data validation step is very simple and straightforward and we will
not cover it here. Our focus will be on mapping/alignment, recalibration,
and varaint detction algorithms using MapReduce algorithms.

18.4 DNA-Sequencing: Alignment

What is ”sequence alignment”? Sequence alignment is the comparison of
two or more DNA or protein sequences to each other. The main purpose of
sequence alignment is to highlight similarity between the sequences.

For global sequence alignment, consider the following example with two

input sequences over the same alphabet:

Sequence1 : GCGCAT GGAT T GAGCGA

Sequence2 : T GCGCCAT T GAT GACCA

Output: an alignment of the two sequences (a possible alignment):

−GCGC−AT GGAT T GAGCGA

T GCGCCAT T GAT −GACC−A

We can observe three elements in a possible alignment output:

• Perfect matches (Blue color)

• Mismatches (Red color)

• Insertions and deletions (indel)(Green color)

447

For aligment phase, we use MapReduce/Hadoop along with the following

open-source tools:

• BWA: Burrows-Wheeler Aligner (BWA) is an eﬃcient program that
aligns relatively short nucleotide sequences against a long reference se-
quence such as the human genome (see http://bio-bwa.sourceforge.
net//)

• SAM Tools: provide various utilities for manipulating alignments in the
SAM format, including sorting, merging, indexing and generating align-
ments in a per-position format (see http://samtools.sourceforge.
net/)

18.5 MapReduce Algorithms for DNA-Sequencing

Typical DNA-Sequencing for single sample data (about 300-400GB of FASTQ
ﬁle format) might take 70+ hours using a very powerful single server. The
goal of MapReduce algorithm is to ﬁnd the answer in few hours and make
the solution scalable.

Since most of open source tools (such as BWA, SAM Tools, and GATK)
for alignemnt, recalibration, and variant detection have Linux command line
interfaces, map() and reduce() at each MapReduce phases will call Linux
shell scripts with passing proper parameters. To execute these shell scripts,
we will use the FreeMarker1 templating language, which will merge Java
objects (and data structures) with a template to create a proper shell script.
To identify one DNA-Seq from another DNA-seq, for each analysis, we assign
and utilize a unique GUID called ”analysis ID” (this helps us to keep input
and output directories organized).

FreeMarker template engine usage is presented below:

We present 3 steps MapReduce solution (see ﬁgure ):

DNA-Sequencing Data Flow for 3 steps MapReduce solution is presented
below. It show how data are partitioned and merged at diﬀerent steps of
MapReduce algorithms.

1http://freemarker.org/

448

Figure 18.3: FreeMarker Template Engine

449

Figure 18.4: 3 Steps MapReduce Solution (Steps 1 and 2)

450

Figure 18.5: 3 Steps MapReduce Solution (Step 3)

451

Figure 18.6: DNA-Sequencing Data Flow

452

Figure 18.7: DNA-Sequencing: Alignment Workﬂow

18.6 MR Algorithms: Step-1: DNA-Sequencing:

Alignment

A High-level Workﬂow for Alignment phase is depicted below:

Before alignment step starts, we partition DNA-Sequence FASTQ ﬁle(s)
into 8M lines (or 2M sequences – in FASTQ format, each 4 lines repre-
sent asingle DNA sequence data). If FASTQ data is paired, then our input
If it is non-
is a pair of ﬁles: left_file.fastq and right_file.fastq.
paired, then input will be a single ﬁle file.fastq. For paired data, we
will partition as (for paired data, an alignment map() function will process
left_file.fastq.NNNN and right_file.fastq.NNNN together):

453

left_file.fastq.0000 right_file.fastq.0000
left_file.fastq.0001 right_file.fastq.0001
left_file.fastq.0002 right_file.fastq.0002
...

...

For non-paired data, we will partition as (for non-paired data, an align-

ment map() function will process file.fastq.NNNN):

file.fastq.0000
file.fastq.0001
file.fastq.0002
...

Each partition (so called a chunk) will be consumed by a map() function.
The partitioning into 8M lines does depend on the size of your hadoop cluster.
If you have a cluster of 50 nodes and each node can handle 4 mappers, then
you should split your FASTQ ﬁle by 200. For example, if your total input size
is about 400GB, then you should partition your input into 2GB chunks (this
way you will maximize the usage of all your mappers). The map() function
will read input ﬁle (one single chunk) and will generate an aligned ﬁle in BAM
format. Here, the map() function uses the BWA (Burrows-Wheeler Aligner2)
to perform the alignment process. Once alignment is done, then it will extract
all chromosomes (1, 2, ..., 22, 233) and save them in MapReduce ﬁle system
(in Hadoop it is called HDFS). For example, if we had 800 partitions, then
we have generated 800 ﬁles per chromosome (total of 23 ∗ 800 = 18, 400
ﬁles). There will be only 23 reducers (one per chromosome). The reducer
will concatenate (merge-sort) all chromosomes for a speciﬁc chromosome ID.
All chromosomes 1 will be concatenated into a single ﬁle called chr1.bam and
all chromosomes 2 will be concatenated into a single ﬁle called chr2.bam and
so son. Then each reducer will partition merged BAM ﬁle into small ﬁles,
which will be used as input to the recalibration phase.

2http://bio-bwa.sourceforge.net/
3There is no chromosome 23, but we concatenate chromosomes X, Y, and M and call

it chromosome 23

454

18.6.1 Step-1: map(): Alignment

For alignment, our solution will accept FASTQ ﬁle format as input and will
generate partitioned chromosomes (chr1, chr2, ..., chr22, chr23). Note that
human chromosomes are numbered as 1, 2, ..., 22, X, Y, and M. There is no
chromosome 23, but we concatenate chromosomes X, Y, and M and call it
chromosome 23.

Listing 18.1: map(): Alignment

1 /**
2 * @param key a key generated by MapReduce framework
3 * @param value a partitioned FASTQ file (may be 8M lines = 2M sequences)
4 */
5 map(key, value) {

6

7

8

9

// note: chr23 = concat(chrX, chrY, chrM)
alignedBAMFile = alignByBWA(value);
(chr1File, chr2File, ..., chr22File, ch23File) = partitionByChromosome(alignedFile);
for (i=1, i < 24; i++) {

emit(chr<i>, chr<i>File);

10

11
12 }

}

The alignByBWA() function accepts a partitioned FASTQ ﬁle, performs
the alignment, and ﬁnally partitions the alingned ﬁle by chromosome. All of
these are done by a shell script template. Portions of this template are listed
below:

Listing 18.2: Alignment Phase: For Non-Paired Input

1 #!/bin/bash
2 ...
3 export BWA=<bwa-install-dir>/bwa
4 export SAMTOOLS=<samtools-install-dir>/samtools
5 export BCFTOOLS=<bcftools-install-dir>/bcftools
6 export VCFUTILS=<bcftools-install-dir>/vcfutils.pl
7 export HADOOP_HOME=<hadoop-install-dir>
8 export HADOOP_CONF_DIR=<hadoop-install-dir>/conf
9 ...
10 # data directories
11 export TMP_HOME=<root-tmp-dir>/tmp
12 export BWA_INDEXES=<root-index-dir>/ref/bwa
13 ...

455

14 # define ref. genome
15 export REF=<root-reference-dir>/hg19.fasta
16
17 ### step 1: alignment
18 # the KEY uniquely identifies the input file
19 KEY={key}
20 # input_file
21 export INPUT_FILE=${input_file}
22 export ANALYSIS_ID=${analysis_id}
23 NUM_THREAD=3
24 cd $TMP_HOME
25 $BWA aln -t $NUM_THREAD $REF $INPUT_FILE > out.sai
26 $BWA samse -r $REF out.sai $INPUT_FILE | $SAMTOOLS view -Su -F 4 - | \
27

$SAMTOOLS sort - aln.flt

28
29 # start indexing aln.flt.bam file
30 $SAMTOOLS index aln.flt.bam
31
32 # partition aligned data
33 for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
34 do
35

36

CHR=chr$i
$SAMTOOLS view -b -o $CHR.bam aln.flt.bam
$HADOOP_HOME/bin/hadoop fs -put $CHR.bam

37
38 done
39
40 # do the same thing for X, Y and M chromosomes
41 $SAMTOOLS view -b -o chr23.bam aln.flt.bam
42 $HADOOP_HOME/bin/hadoop fs -put chr23.bam
43
44 exit 0

$CHR

/genome/dnaseq/output/$ANALYSIS_ID/$CHR/$KEY.$CHR.bam

chrX chrY chrM

/genome/dnaseq/output/$ANALYSIS_ID/chr23/$KEY.chr23.bam

The provided shell script handles non-paired data only. If the input ﬁles

are paired, then lines 24-26 are replaced by:

Listing 18.3: Alignment Phase: For Paired Input

1 $BWA aln -t $NUM_THREAD $REF $INPUT_FILE_1 > out1.sai
2 $BWA aln -t $NUM_THREAD $REF $INPUT_FILE_2 > out2.sai
3 $BWA sampe -r $INFO_RG $REF out1.sai out2.sai $INPUT_FILE_1 $INPUT_FILE_2 | \
4

$SAMTOOLS view -Su -F 4 - | $SAMTOOLS sort - aln.flt

18.6.2 Step-1: reduce(): Alignment

For Alignment phase, there will be exactly 23 reducers (one reducer per chro-
mosome). The reducer key will be a composite key of <chrID><;><analysisID>,
where chromosome ID (labeled as 01, 02, 03, ..., 23). Note the chromosome
ID of 23 includes chrM, chrX, and chrY. Each reducer will merge all aligned
.bam ﬁles into single merged.bam:

456

chr<i>.bam = merge the following files:

chr<i>.bam.0000
chr<i>.bam.0001
...
chr<i>.bam.0437
...

After merging all ﬁles into a single chr<i>.bam ﬁle, we partition chr<i>.bam
ﬁle into many small bam ﬁles to be fed to the Recalibration mapper of Step-2.
The partitioned ﬁles will be:

chr<i>.bam.j (j = 1, 2, 3, ..., 100+)

The reduce() function for alignment phase is presented below:

Listing 18.4: reduce(): Alignment

1 /**
2

3

4

where chrID is in (1, 2, 3, ..., 23)

* @param key is a <chrID><;><analysis_id>
*
* @param value is ignored (not used)
*/

5
6 reduce(key, value) {
7
8 }

DNASeq.mergeAllChromosomesAndPartition(key);

The bulk of work is with DNASeq.mergeAllAndPartition() method, which
merges all aligned bam ﬁles for a speciﬁc chromosome and then the ﬁnal
merged ﬁle is partitioned for further processing by the recalibration phase
(called Step-2).

Listing 18.5: mergeAllChromosomesAndPartition(): method

1 /**
2

3

4

*
* reducerKey=<chrID>;<analysis_id>
*
*/

where chrID=1, 2, ..., 22, 23 (23 includes chrM, chrX, chrY)

5
6 public static void mergeAllChromosomesAndPartition(String reducerKey) throws Exception {
7

// split the line: each line has (fields are separated by ";")

457

String[] tokens = reducerKey.split(";");
String chrID = tokens[0];
String analysisID = tokens[1];
Map<String, String> templateMap = new HashMap<String, String>();
templateMap.put("chr_id", chrID);
templateMap.put("analysis_id", analysisID);
mergeAllChromosomesBamFiles(templateMap);
partitionSingleChromosomeBam(templateMap);

8

9

10

11

12

13

14

15
16 }

As you can observe from the mergeAllChromosomesAndPartition() method,

both of the helper methods mergeAllChromosomesBamFiles() and partition-
SingleChromosomeBam() use FreeMarker template engine to pass the re-
quired Java objects and then execute shell scripts on behalf of reducers. For
example,

Listing 18.6: mergeAllChromosomesAndPartition(): method

1 /**
2

HDFS: /.../chr<i>/chr<i>.bam.0000
HDFS: /.../chr<i>/chr<i>.bam.0001
...
HDFS: /.../chr<i>/chr<i>.bam.0437

* This method will merge the following files and creates a single chr<i>.bam file
* where ( i is in {1, 2, ..., 23} ).
*
*
*
*
*
*
* Then merge all these (.0000, .0001, ..., .0437) files and save it in
* /data/tmp/<analysis_id>/chr<i>/chr<i>.bam
*
* Once chr<i>.bam is created, then we partition it into small bam files,
* which will be fed to RecalibrationDriver (Step-2 of DNA Sequencing)
*
*/

16
17 public static void mergeAllChromosomesBamFiles(Map<String, String> templateMap)
18

throws Exception {
TemplateEngine.initTemplatEngine();
String templateFileName = <freemarker-template-file-as-a-bash-script>;
// create the actual script from a template file
String chrID = templateMap.get("chr_id");
String analysisID = templateMap.get("analysis_id");
String scriptFileName = createScriptFileName(chrID, analysisID);
String logFileName = createLogFileName(chrID, analysisID);
File scriptFile = TemplateEngine.createDynamicContentAsFile(templateFileName,

if (scriptFile != null) {

ShellScriptUtil.callProcess(scriptFileName, logFileName);

templateMap,
scriptFileName);

3

4

5

6

7

8

9

10

11

12

13

14

15

19

20

21

22

23

24

25

26

27

28

29

30

}

31
32 }

458

The TemplateEngine.createDynamicContentAsFile() methood does the
magic: it takes two inputs (templateFileName and templateMap) and pro-
duces a scriptFileName. Basically all parameters are passed to templateFile-
Name and then a new shell script is generated as a scriptFileName, which
is then executed ob behalf of a reducer. There are two important classes
(TemplateEngine and ShellScriptUtil), which needs some discussion. The
ShellScriptUtil.callProcess() method accepts a shell script ﬁle (ﬁrst
parameter), which executes it and then writes all log from the script execu-
tion to a log ﬁle (second parameter). Logging is asynchronous: it means that
as you execute the script, the log ﬁle immediately becomes available.

The TemplateEngine class is deﬁned below: it just implements the basic
notion of a templating engine: it accetps a template (as a text ﬁle with key
holders) and (key,value) pairs as a Java Map and then creates a brand new
ﬁle in which all keys in template are replaced by values.

Listing 18.7: TemplateEngine Class

1 import java.io.File;
2 import java.io.Writer;
3 import java.io.FileWriter;
4 import java.util.Map;
5 import java.util.concurrent.atomic.AtomicBoolean;
6 import freemarker.template.Template;
7 import freemarker.template.Configuration;
8 import freemarker.template.DefaultObjectWrapper;
9
10 /**
11

12

13

14

15

16

17

18

19

* This class uses FreeMarker (http://freemarker.sourceforge.net/).
* FreeMarker is a "template engine"; a generic tool to generate text
* output (anything from shell scripts to autogenerated source code)
* based on templates. It’s a Java package, a class library for Java
* programmers. It’s not an application for end-users in itself, but
* something that programmers can embed into their products.
*
* @author Mahmoud Parsian
*
*/

20
21 public class TemplateEngine {
22

23

24

25

26

27

28

29

30

31

32

// You usually do it only once in the whole application life-cycle
private static Configuration TEMPLATE_CONFIGURATION = null;
private static AtomicBoolean initialized = new AtomicBoolean(false);

// the following template directories will be loaded from configuration file
private static String TEMPLATE_DIRECTORY

= "/home/dnaseq/template";

public static void init() throws Exception {

if (initialized.get()) {

// it is already initialized and returning...

459

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

return;

}
initConfiguration();
initialized.compareAndSet(false, true);

}

static {

if (!initialized.get()) {

try {

init();

}
catch(Exception e) {

theLogger.error("TemplateEngine init failed at static initialization.", e);

}

}

}

// this suppports single template directory
private static void initConfiguration() throws Exception {

TEMPLATE_CONFIGURATION = new Configuration();
TEMPLATE_CONFIGURATION.setDirectoryForTemplateLoading(new File(TEMPLATE_DIRECTORY));
TEMPLATE_CONFIGURATION.setObjectWrapper(new DefaultObjectWrapper());
TEMPLATE_CONFIGURATION.setWhitespaceStripping(true);
// if the following is set, then undefined keys will be set to "".
TEMPLATE_CONFIGURATION.setClassicCompatible(true);

}

public static File createDynamicContentAsFile(...){...}

The most important method of TemplateEngine class is deﬁned below.
This method accepts a template ﬁle, which has key holders and a set of
(key,value) pairs and then generates a new ﬁle by substituting the given keys
in key holders.

Listing 18.8: TemplateEngine.createDynamicContentAsFile() Method

/**

* @param templateFile is a template filename such as script.sh.template
* @param keyValuePairs set of (K,V) pairs
* @param outputFileName is a generated filename
*/

from templateFile

public static File createDynamicContentAsFile(String templateFile,

throws Exception {
if ((templateFile == null) || (templateFile.length() == 0)) {

Map<String,String> keyValuePairs,
String outputFileName)

return null;

}

Writer writer = null;
try {

// create a template : example "cb_stage1.sh.template2"
Template template = TEMPLATE_CONFIGURATION.getTemplate(templateFile);

460

// Merge data-model with template
File outputFile = new File(outputFileName);
writer = new BufferedWriter(new FileWriter(outputFile));
template.process(keyValuePairs, writer);
writer.flush();
return outputFile;

}
finally {

if (writer != null) {
writer.close();

}

}

18

19

20

21

22

23

24

25

26

27

28

29

}

30
31 }

18.7 Step-2: DNA-Sequencing: Recalibration

Recalibration is the second phase of DNA sequencing pipeline. In recalibra-
tion step, each map() function will work on a speciﬁc aligned chromosomes.
The mapper will do ”marking duplicates”, ”local re-alignment”, and recali-
bration. The goal of map() is to to create a local ”recalibration table” (called
covariates), which will be merged by the single reducer. Then a single re-
ducer will create the ﬁnal single ﬁle (called ”recalibration table”), which will
be used by the map() of variant detection step (called Step-3 – ﬁnal step of
the DNA Sequencing).

Recalibration MapReduce algorithm (data ﬂow) is presented below.

Following the alignment phase, we create a special metadata to be used by
recalibraton mappers. The metadata generated for recalibration mappers
has the following format:

<counter><;><partitioned-bam-file><;><ref_genome><;><analysis_id>

where

<counter> is a auto-generated sequence numbers 0000, 0001, 0002, ...
<partitioned-bam-file> is a chunck of partitioned aligned file
<ref_genome> refers to hg18 or hg19
<analysis_id> is a GUID for DNA Sequencing (to manage

461

Figure 18.8: DNA-Sequencing: Recalibration

462

one analysis from another one)

Example of an input is given below:

0001;chr07.bam.0001;hg19;208
0002;chr07.bam.0002;hg19;208
0003;chr07.bam.0003;hg19;208
...

Recalibration mapper is presented below:

Listing 18.9: Recalibration Mapper

1 // key is MR generated, ignored here
2 // value is: <counter><;><partitioned-bam-file><;><ref_genome><;><analysis_id>
3 map(key, value) {
4

// actual file location will be: /data/dnaseq/align/ANALYSIS_ID/merged.bam.<KEY>
Map<String, String> tokens = DNASeq.tokenizeRecalibrationMapperInput(value);
String reducerKey = tokens.get("analysis_id");
DNASeq.recalibrationMapper(tokens);
emit(reducerKey, value);

5

6

7

8
9 }
10
11 public static void recalibrationMapper(Map<String, String> templateMap)
12

throws Exception {
TemplateEngine.init();
// create the actual script from a template file
String key = templateMap.get("key");
String analysisID = templateMap.get("analysis_id");
String scriptFileName = createScriptFileName("recalibration_mapper", key, analysisID);
String logFileName = createLogFileName("recalibration_mapper", key, analysisID);
File scriptFile = TemplateEngine.createDynamicContentAsFile("recalibration_mapper.template",

if (scriptFile != null) {

ShellScriptUtil.callProcess(scriptFileName, logFileName);

templateMap,
scriptFileName);

13

14

15

16

17

18

19

20

21

22

23

}

24
25 }

There will be only ONE reducer per <analysis_id>.

Listing 18.10: Recalibration Mapper

1 // key: analysisID
2 // values: ignored
3 reduce(key, Iterable<Object> values) {
4

DNASeq.recalibrationReducer(key);

463

emit(key, key);

5
6 }

The recalibrationReducer() method is deﬁned below:

Listing 18.11: recalibrationReducer() Method

1 public static void recalibrationReducer(String analysisID)
2

throws Exception {
TemplateEngine.init();
String[] tokens = valueAsString.split(";");
Map<String, String> templateMap = new HashMap<String, String>();
templateMap.put("key", "-"); // key is undefined
templateMap.put("analysis_id", key);
// create the actual script from a template file
String scriptFileName = createScriptFileName("recalibration_reducer", analysisID);
String logFileName = createLogFileName("recalibration_reducer", analysisID);
File scriptFile = TemplateEngine.createDynamicContentAsFile("recalibration_reducer.template",

if (scriptFile != null) {

ShellScriptUtil.callProcess(scriptFileName, logFileName);

templateMap,
scriptFileName);

3

4

5

6

7

8

9

10

11

12

13

14

15

}

16
17 }

Recalibration templates are deﬁned below:

Listing 18.12: Recalibration Mapper Template

1 #!/bin/bash
2
3 ###
4 ### Recalibration Mapper Template
5 ###
6 ### call snp (get vairants) up to calculation of ...recal.table.csv
7 ### once recal.table.csv is created, it will be saved in HDFS
8 ### input file: aligned bam file (partitioned from a
9 ...
10 ##
11 ## input file: aligned bam file (partitioned from a chr<i>.bam)
12 ## copy HDFS_BAM_FILE to LOCAL_BAM_FILE
13 HDFS_BAM_FILE=${hdfs_bam_file}
14 BAM_FILE=‘basename $HDFS_BAM_FILE‘;
15 $HADOOP_HOME/bin/hadoop fs -copyToLocal $HDFS_BAM_FILE .
16 ...
17 #
18 # put 4.recal.table.csv into GLOBAL/SHARED directory
19 #
20 export SHARED_RECAL_DIR=/dnaseq/recal/${analysis_id}
21 ...
22 ## marking duplicates
23 java

chr<i>.bam)

-Xmx4g\

464

24

25

26

27

28

29

-Djava.io.tmpdir=$JAVA_IO_TMPDIR \
-jar $PICARD_JAR/MarkDuplicates.jar \
I=$BAM_FILE \
O=2.mark.out.bam \
M=2.mark.out.metrics \
AS=true

30
31 ## local realignment
32 samtools index 2.mark.out.bam
33 java
34

-Xmx4g \

39

38

37

36

35

-Djava.io.tmpdir=$JAVA_IO_TMPDIR \
-jar $GATK_JAR/GenomeAnalysisTK.jar \
-T IndelRealigner \
-I 2.mark.out.bam \
-o 3.realigned.out.bam \
-R $REF \
-targetIntervals $DBSNP/dbsnp_indel.intervals \
-known $DBSNP/dbsnp_indel.vcf \
--consensusDeterminationModel KNOWNS_ONLY \
-LOD 0.4
43
44 ## base quality recalibration
45 java
46

-Xmx4g

41

40

42

\

47

48

49

50

51

52

53

54

55

-Djava.io.tmpdir=$JAVA_IO_TMPDIR \
-jar $GATK_JAR/GenomeAnalysisTK.jar \
-T CountCovariates \
-I 3.realigned.out.bam \
-recalFile 4.recal.table.csv \
-R $REF \
-knownSites $DBSNP/dbsnp.vcf \
-cov QualityScoreCovariate \
-cov ReadGroupCovariate \
-cov PositionCovariate \
-cov DinucCovariate

56
57 # copy result to shared directory
58 cp -f 4.recal.table.csv $SHARED_RECAL_DIR/$KEY.4.recal.table.csv
59
60 ##
61 ## we need also to save: 3.realigned.out.bam (which will be
62 ## needed in variant_detection_mapper.sh.template
63 ##
64 cp -f 3.realigned.out.bam $SHARED_RECAL_DIR/$BAM_FILE.3.realigned.out.bam
65 ###
66 ### so we will have:
67 ###
68 ###
69 ###
70 ###

£SHARED_RECAL_DIR/£KEY.4.recal.table.csv
£SHARED_RECAL_DIR/£BAM_FILE.3.realigned.out.bam
(will be input to variant_detection_mapper.sh.template)

for KEY=1, 2, 3, ....
for KEY=1, 2, 3, ....

Listing 18.13: Recalibration Reducer Template

1 #!/bin/bash
2 ###
3 ### Merge all -.4.recal.table.csv files (generated by individual .bam files)
4 ### into a single recal.table.merged.final.txt file.

465

5 ###
6 ### Once recal.table.merged.final.txt is created, it will be saved in
7 ### /dnaseq/recal/£{analysis_id}/ and will be fed into VariantDetectionMapper.
8 ###
9 ...
10 #
11 # All -.4.recal.table.csv files are in
12 #
13 export SHARED_RECAL_DIR=/dnaseq/recal/$ANALYSIS_ID/
14 recal_files=‘find $SHARED_RECAL_DIR -name ’*.4.recal.table.csv’ | sort‘
15 num_of_recal_files=‘find $SHARED_RECAL_DIR -name ’*.4.recal.table.csv’ | wc -l‘
16 ...
17 ### NOTE: all calculations will take place at £SHARED_RECAL_DIR
18 # prepare java input files
19 java_input_files=""
20 for file in $recal_files
21 do
22

£SHARED_RECAL_DIR directory

echo "preparing java input file=$file"
java_input_files="$file $java_input_files"

23
24 done
25 ...
26 cd $SHARED_RECAL_DIR
27 current_dir=‘pwd‘
28 export MERGE_COVARIATES=JavaMergeCovariates
29 $JAVA_HOME/bin/java -Xms4g -Xmx12g $MERGE_COVARIATES -i "$java_input_files" -o recal.txt.unsorted
30 #
31 # sort the file accordingly
32 #
33 /bin/sort -t, -k 2,2n -k3,3n -k4,4 recal.txt.unsorted > recal.txt.sorted
34 #
35 # The recal.txt.sorted file will be used by the Variant Detection Mapper.

18.8 Step-3: DNA-Sequencing: Variant De-

tection

Variant Detection is the ﬁnal step of DNA Sequencing. The goal of this
step is to generate variants in VCF (variant call format – developed by 1000
Genomes Project) format. The map() function will use the BAM ﬁle (gen-
erated by the map() function of the recalibration step) and the ﬁnal single
”recalibration table” ﬁle. The map() function will use open-source tools
(such as GATK4 and SAM Tools) to generate partial variants (called raw
BCF ﬁles). The reducer will concatenate (sort-merge) the raw BCF ﬁles to
generate a single VCF ﬁle. Once VCF ﬁle is created, it can be used by many
analytical algorithms such as ”Allelic Frequency”, ”Family Analysis”, and

4https://www.broadinstitute.org/gatk/

466

”Cochran-Armitage Test”.

Variant Detection (also called SNP calling) is the process of ﬁnding bases in
the NGS data that diﬀer from the reference genome (such as hg18 or hg19 –
these refer to the version of the human genome assembly and determines the
version of the corresponding reference annotations – for details, see http:
//hgdownload.cse.ucsc.edu/goldenPath/hg18/bigZips/).

18.8.1 Variant Detection Mapper

The mapper accepts a chunked ”realigned bam” ﬁle and performs the follow-
ing transformations on it:

• base quality recalibration

• variant calling and ﬁltering

The bulk of work is done by calling DNASeq.theVariantDetectionMapper()

method, which accepts the required parameters and creates a proper shell
script from a given template. Finally it executes the shell script. The mapper
for variant detection is provided below.

Listing 18.14: Variant Detection Mapper

<

1

0

> <

1 // key: ignored, not used
2 // value: <counter><;><3.realigned.out.bam.<key>><;><ref_genome><;><analysis_id>
3 // index
4 // value example-1:
5 // value example-2:
6 // NOTE: THERE WILL BE ONE SINGLE REDUCER for variant detection:
7 // the key for output of reducer will be: <analysis_id>
8 map(key, value) {
9

0001;/<dir>/realigned.out.bam.0001;hg19;208
0007;/<dir>/realigned.out.bam.0007;hg19;208

Map<String, String> tokens = DNASeq.tokenizeTheVariantDetectionMapper(value);
String reducerKey = tokens.get("analysis_id");
DNASeq.theVariantDetectionMapper(tokens);
emit(reducerKey, reducerKey);

> <

> <

3

>

2

10

11

12
13 }

The theVariantDetectionMapper() method accepts analysis_id (which

uniquely identiﬁes all ﬁles dir directories for a speciﬁc DNA Seq. run).

Listing 18.15: theVariantDetectionMapper()

467

3

4

5

6

7

8

9

11

12

13

14

15

1 public static void theVariantDetectionMapper(Map<String, String> templateMap)
2

throws Exception {
TemplateEngine.init();
// create the actual script from a template file
String scriptFileName = "/dnaseq/variant_detection_mapper_" + templateMap.get("analysis_id") + "_" + templateMap.get("key") +".sh";
String logFileName =
File scriptFile = TemplateEngine.createDynamicContentAsFile("variant_detection_mapper.template", templateMap, scriptFileName);
if (scriptFile != null) {

"/dnaseq/variant_detection_mapper_" + templateMap.get("analysis_id") + "_" + templateMap.get("key") +".log";

ShellScriptUtil.callProcess(scriptFileName, logFileName);

}

10
11 }

Portions of the variant_detection_mapper.template is provided be-

low:

Listing 18.16: Variant Detection Mapper Template

1 cat variant_detection_mapper.template
2 #!/bin/bash
3 ...
4
5 # 1. perform base quality recalibration:
6 # GATK required that the BAM file extension has to .bam
7 samtools index $REALIGNED_OUT_BAM_FILE
8 #
9 java -Xmx4g \
10

-Djava.io.tmpdir=$JAVA_IO_TMPDIR \
-jar $GATK_JAR/GenomeAnalysisTK.jar \
-T TableRecalibration \
-I $REALIGNED_OUT_BAM_FILE \
-o 4.recal.out.bam \
-R $REF \
-recalFile $SHARED_RECAL_DIR/recal.table.merged.final.txt

16
17 ...
18 # 2. variant calling and filtering
19 samtools mpileup -Duf $REF -q 1 4.recal.out.bam | bcftools view -bvg - > $REALIGNED_OUT_BAM_FILE.raw.bcf

18.8.2 Variant Detection Reducer

There will be ONY ONE REDUCER for all mappers. The reason for one
reducer is that we will be merging values to create a single output: a VCF
ﬁle. The reducer does only one thing: creates a VCF ﬁle.

Listing 18.17: Variant Detection Reducer

1 // key: <analysis_id>, which identifies all data uniquely
2 // values: ignored
3 reduce(key, values){

468

DNASeq.theVariantDetectionReducer(key);
emit(key, key);

4

5
6 }

Listing 18.18: theVariantDetectionReducer()

1 public static void theVariantDetectionReducer(String analysisID)
2

throws Exception {
TemplateEngine.init();
Map<String, String> templateMap = new HashMap<String, String>();
templateMap.put("key", "-");
templateMap.put("analysis_id", analysisID);
// create the actual script from a template file
String scriptFileName = "/dnaseq/variant_detection_reducer_" + templateMap.get("analysis_id") +".sh";
String logFileName = "/dnaseq/variant_detection_reducer_" + templateMap.get("analysis_id") +".log";
File scriptFile = TemplateEngine.createDynamicContentAsFile("variant_detection_reducer.template", templateMap, scriptFileName);
if (scriptFile != null) {

3

4

5

6

7

8

9

10

11

12

ShellScriptUtil.callProcess(scriptFileName, logFileName);

}

13
14 }

Portions of the variant_detection_mapper.template is provided be-

low:

Listing 18.19: Variant Detection Reducer Template

1 #cat variant_detection_reducer.template
2 #!/bin/bash
3 ...
4 # call snp (get vairants)
5 # concatenate all £KEY.raw.bcf files
6 #
7 FINAL_BCF_FILE=$FINAL_DIR/all.raw.bcf
8 VCF_FILE=$FINAL_DIR/var.flt.vcf
9 ...
10 ##
11 ## Concatenate BCF files. The input files are required to be
12 ## sorted and have identical samples appearing in the same order.
13 ##
14 ALL_BCF_FILES=‘find $RECAL_DIR/
15 $BCFTOOLS cat $ALL_BCF_FILES > $FINAL_BCF_FILE
16 #
17 #begin bcftools & create final VCF file
18 $BCFTOOLS view $FINAL_BCF_FILE | $VCFUTILS varFilter > $VCF_FILE

-name ’*.raw.bcf’ | sort‘

469

Chapter 19

Cox Regression

19.1

Introduction to Survival Analysis using
Cox Regression

In medical statistics, survival analysis is used to describe the eﬀect on survival
times of a continuous variable (such as gene expression). Cox proportional
hazard regression is a very important and popular regression algorithm; its
simplicity and no assumption about survival distribution provide relative risk
for a unit change in the variable. For example, a unit change in the expression
of a speciﬁc gene gives a 2-fold increase in relative risk. A simple example of
Cox regression is given: do men and women have diﬀerent risks of developing
brain cancer based on drinking alcoholic beverages? By constructing a Cox
Regression model, with alcohol usage (ounces drank per day) and gender
entered as covariates, you can test hypotheses regarding the eﬀects of gender
and alcohol usage on time-to-onset for brian cancer.

What is a Cox Regression? A Cox Regression model is a statistical technique
used to explore the relationship between the survival of a patient and several
explanatory variables such as time and censor. Cox Regression model was
developed by Sir Professor David Cox. One imortant characteristics of Cox
regression is that estimates relative rather than absolute risk and it does
not assume any knowledge of absolute risk. By deﬁnition, Cox regression,
which implements the proportional hazards model is designed for analysis
of time until an event or time between events. Cox regression uses one or

470

more predictor variables (so called covariates – example is time variable), to
predict a status (event such as survival) variable. For example, time is an
example of covariate (time from diagnosis of illness until the event of death
– called survival analysis).

Cox Proportional Hazard Model is the most popular model for survival
analysis because of its simplicity and no assumption about survival distribu-
tion.

For details on Cox regression, see David Garson’s book [10].

Cox Proportional Hazard Regression is used to describe the eﬀect on survival
times of a continuous variable (e.g., gene expression). For details on Cox Re-
gression, refer to http://en.wikipedia.org/wiki/Cox_regression. The
R’s programming language (http://www.r-project.org/) implementation
of Cox Regression is an industry-standard reliable implementation (called
coxph() function) and we will use it in our MapReduce solution. Unfortu-
nately, there is no good implementation of Cox Regression in Java.

Cox Regression is used extensively by clinical and medical ﬁelds. The fol-
lowing are some examples of Cox Regression in medical ﬁelds:

• Survival analysis using continuous variables such as gene expression or

White Blood Count ([27])

• Combining Gene Signatures Improves Prediction of Breast Cancer Sur-

vival ([31]).

The goal of this chapter is to provide a two-phase MapReduce solution to
Cox regression:

• The PHASE-1 prepares proper input for Cox Regression

• The PHASE-2 uses output of PHASE-1 and applies R’s coxph() to
solve Cox Regression (there is no proper Java package for Cox regression
algorithms – R provides defacto standards for Cox regression)

19.2 Cox Model in a Nutshell

Cox Regression is a relatively complex time-based statistical function. The
main function of Cox Regression is to build a predictive model for time-
to-event data. In a nutshell, the Cox regression model produces a survival

471

function that predicts the probability that the event of interest has occurred
at a given time t for given values of the predictor variables (for example,
in lung cancer analysis predictor variables can be the number of cigarettes
smoked by diﬀerent genders – men and women). The Cox regression is esti-
mated from observed subjects and events during some time period.

In a nutshell, Cox Proportional Hazard Model can be expressed as a model

hi(t) = h0(t) exp(β1xi1 + β2xi2 + ... + βnxin)

where

• (xi1, xi2, ..., xin) are the predictor variables and time independent
• (β1, β2, ..., βn) is a vector of regression parameters and are estimated

by Cox regression

• h0(t) is the baseline hazard, which is an unspeciﬁed function, making it
a semi-parametric model (h0(t) depends on time but not the covariates)

• exp(βX) depends on the covariates but not time.

• The hazard ratio for two observations is independent of time t, which

deﬁnes the proportional hazards property as:

hi(t)
hj(t)

=

h0(t)eθi
θj
h0(t)e

=

eθi
θj

e

We can divide the both sides of the equation by h0(t) taking logarithms,

we obtain:

´

ln

hi(t)
h0(t)

¯

´

¯

=

β1xi1 + β2xi2 + ... + βnxin

we call

hi(t)
h0(t)

the hazard ratio.

19.3 MapReduce Solution for Cox Regression

We implement Cox Regression by 2-phase MapReduce algorithms:

472

• MapReduce PHASE-1: Aggregate, Group By, and Generate data
ready for calling R’s coxph() function. The coxph()1 function ﬁts a
Cox proportional hazards regression model.

• MapReduce PHASE-2: Use output of PHASE-1 and Call R’s coxph().

Finally, analyze generated results.

19.3.1 Cox Regression Basic Terminology

To use, Cox Regression in the context of survival analysis, we need to un-
derstand several key deﬁnitions. We borrow these deﬁnitions from Michael
Walker (http://walkerbioscience.com/pdfs/Survival%20analysis.pdf).

• Event: This is an application depenedent concept. Examples are:

death, disease recurrence, or recovery.

• Time: This parameter for sure plays an important role in Cox regres-
sion deﬁnition. Events are time based. For example, the time from the
beginning of an observation period (e.g., surgery) to (a) an event, or
(b) end of the study, or (c) loss of contact or (d) withdrawal from the
study.

• Censoring/Censored observation: When a test subject does not
have an event during the observation time, they are described as cen-
sored, meaning that we cannot observe what has happened to them
subsequently.

• Censored subject: a censored subject may or may not have an event

after the end of observation time.

• Survivor function: S(t) = the probability that a subject survives

longer than time t.

1Fits a Cox proportional hazards regression model. Time dependent variables, time
dependent strata, multiple events per subject, and other extensions are incorporated using
the counting process formulation of Andersen and Gill. (source: http://stat.ethz.ch/
R-manual/R-patched/library/survival/html/coxph.html)

473

19.4 Cox Regression by using R Language

The R programming language provides an implementation of Cox Propor-
tional Hazards Regression Model by coxph{survival}.

Survival data

>time=c(5.880903491,11.07186858,10.97330596,1.347022587,8.246406571,

6.209445585,1.80698152,6.899383984,1.281314168,5.650924025,
10.25051335,2.036960986,6.800821355,6.932238193,6.800821355,
2.595482546,8.344969199,5.848049281,4.238193019,5.815195072,
6.340862423,2.529774127,2.628336756,0.689938398,1.347022587,
2.694045175,6.078028747,1.21560575,8.410677618,8.509240246)

> censor=c(1,1,0,1,1,1,1,0,1,1,0,1,0,1,1,1,0,0,1,1,1,1,1,1,1,0,1,1,0,0)

Expression data

The data for a speciﬁc gene is expressed as a foldchange below.

>foldchange=c(20.3,-15.5,-8.04,4.85,5.5,2.16,1.94,-2.13,-52.5,-1.07,
6.23,7.19,4.97,-39.8,-2.11,3.19,-1.24,1.24,2.73,-44.4,
-35,-58.5,-1.79,1.74,-2.15,3.22,-1.7,-3.07,2.57,-1.41)

> convert=function(x){return(log2(max(x, -1/x)))}
> logRatio = sapply(foldchange, convert)

> logRatio

[1] 4.3434078 -3.9541963 -3.0071955 2.2779847 2.4594316 1.1110313
[7] 0.9560567 -1.0908534 -5.7142455 -0.0976108 2.6392322 2.8459918
[13] 2.3132459 -5.3146965 -1.0772430 1.6735564 -0.3103401 0.3103401
[19] 1.4489010 -5.4724878 -5.1292830 -5.8703647 -0.8399596 0.7990873
1.6870607 -0.7655347 -1.6182387 1.3617684 -0.4956952
[25] -1.1043367

Cox regression

The R’s Surv() function accepts two parameters: Surv(time, censor), where

• time is a vector of event time

474

• censor is a vector of indicator (denoting if the event was observed or

censored)

> library(survival) # load the package
> coxph(Surv(time, censor) ~ logRatio)
Call:
coxph(formula = Surv(time, censor) ~ logRatio)

logRatio -0.0247

coef exp(coef) se(coef)
0.976

p
0.0798 -0.31 0.76

z

Likelihood ratio test=0.1 on 1 df, p=0.758 n= 30, number of events= 21

From coxph function, we are only interested in two values: coef =

−0.0247 and pvalue = 0.758.

19.5 Problem Statement

We have a set of patients. Each patient has a set of biosets and each bioset has
a set of genes (for example, genes in RNA Gene-Expression data type) and
its associated values (so called foldchange). What is a bioset? Individually
analyzed data signatures are referred to as ”biosets.” ”Biosets” encompass
data in the form of experimental sample comparisons (for transcriptomic,
epigenetic, and copy number variation data), as well as genotype signatures
(for GWAS and mutational data). A bioset is most commonly referred to as
a ”gene signature” (for details, see 2).
The number of genes per bioset can be up to 60,000. This number can be
diﬀerentiated by the type of bioset, for example, for methylation biosets,
this can be up to 20,000 genes and for gene-expression type this can be up
to 50,000 genes). The problem can be stated as such: given a set of biosets,
time, and censor, ﬁnd ”coef” (coeﬃcient) and ”value” for all genes contained
in all biosets. If we are doing the Cox Regression for a set of 100,000 samples,
then we have to analyze 100,000 × 60,000 = 6 billion data records.
This is a good candidate for MapReduce.

2http://en.wikipedia.org/wiki/Gene signature

475

19.6 Cox Regression POJO Solution

To understand Cox Regression, we present a non-MapReduce solution. For
each bioset data type (”gene expression,” ”copy number variation,” ”methy-
lation”) there are ﬁxed number of genes, which are identiﬁed by geneIdList.
The objective of algorithm is to create input like:

geneID_1 bioset1_value11 bioset2_value12, ..., biosetN_value1N
geneID_2 bioset1_value21 bioset2_value22, ..., biosetN_value2N
...
geneID_M bioset1_valueM1 bioset2_valueM2, ..., biosetN_valueMN

and then to pass this input to R’s coxph() function. For example, for

copy number variation (cnv) type, we can express our algorithm as:

Listing 19.1: Cox Regression Algorithm without MapReduce

1 input: double[] time;
2 input: int[] censor;
3 input: List<Long> biosetIDs;
4 input: List<Long> cnvGeneIdList; // pre built (key, value) database
5 output: List<Tuple3<String, Double, Double>>
6 //
7 //
8 // iterate through all genes
9 for (geneID : cnvGeneIdList) {
10

as List<Tuple3<geneID, coef, pvalue>>

// there is a key-value store per geneID
// where key is the biosetID and value is the gene value
mapDB = getMapDB(geneID);
int index = 0;
double[] geneValues = new double[time.length];
for (biosetID : biosetIDs) {

double geneValue = mapDB.get(biosetID);
geneValues[index++] = geneValue;

}

// call R’s Cox Regression as coxph() function
double[] result = coxph(time, censor, geneValues);
double coef = result[0];
double pvalue = result[1];
emit(geneID, (coef, pvalue));

11

12

13

14

15

16

17

18

19

20

21

22

23

24
25 }

For example, if we have 5,000 biosets, then we want to calculate coxph()
for all genes (up to 40,000) contained in these biosets. This will require 40,000
coxph() calls and each call will have three arrays of time[5,000], censor[5,000]
and foldchange[5,000], where foldchange refers to gene values).
Running this algorithm will generate the following output:

476

geneID_1 coef_1 pvalue_1
geneID_2 coef_2 pvalue_2
...
geneID_M coef_M pvalue_M

Discussion of Cox Regression Solution without MapRe-
duce

This solution does not use MapReduce. Each bioset has a set of geneIDs
(it can be up to 40,000 gene IDs per bioset) and its associated value. To
make this happen, we create a persistent (key, value) store for each gene:
the database name is the geneID, key is the biosetID, and value is the value
associated with geneID. For persistent store, we use MapDB3.

This is an eﬃcient solution when the number of biosets are in the hun-
dreds. When the number of biosets are in the thousands, MapReduce/Hadoop
solution will scale much better than the non-MapReduce solution.

19.7

Input for MapReduce

Typically, a patient has a set of biosets (and each bioset can be a diﬀerent
type deﬁned by copy number variation, methylation, gene-expression). Each
bioset has thousands of records and each record contains a ”gene-id” and
”value: associated with that ”gene-id.”

For example, a biosetID 8800 has the following data:

$ head 8800.csv

13972,r1;2.45
4082,r1;1.8
40583,r1;1.8
16422,r1;1.8

3MapDB (https://github.com/jankotek/MapDB) provides concurrent TreeMap and
HashMap backed by disk storage or oﬀ-heap-memory. It is a fast, scalable and easy to use
embedded Java database engine. It is tiny (160KB jar), yet packed with features such as
transactions, space eﬃcient serialization, instance cache and transparent compression/en-
cryption. It also has outstanding performance rivaled only by native embedded db engines.
MapDB is developed by Jan Kotek (https://github.com/jankotek/).

477

21602,r1;1.8
45735,r1;1.8
43936,r1;1.8
26446,r1;1.8
16030,r1;-3
828,r1;0

where each row/record represents gene-id-and-ref (for ﬁrst row, 13972 is
the gene-id, r1 is a normal reference and 2.45 is an associated foldchange
(gene-value) value. The reference can be r1 = normal, r2 = disease,
r3 = paired, r4 = unknown . Given that the order of values per gene-id
is very important in Cox Regression (coxph() function call – it is a time and
event-based algorithm), we generate another set of data from existing data
to include the biosetID as well. Below is our desired input for biosetID of
8800 to be used in MapReduce/Hadoop implementation.

$ head 8800_for_cox.csv

13972,r1;8800,2.45
4082,r1;8800,1.8
40583,r1;8800,1.8
16422,r1;8800,1.8
21602,r1;8800,1.8
45735,r1;8800,1.8
43936,r1;8800,1.8
26446,r1;8800,1.8
16030,r1;8800,-3
828,r1;8800,0

Input Format for MapReduce

Each bioset record will have the following format:

Record Format:

<geneID><,><referenceID><;><biosetID><,><geneValue>

where

referenceID = r1 (normal)
referenceID = r2 (disease)

478

referenceID = r3 (paired)
referenceID = r4 (unknown)

Example for biosetID of 8800:

13972,r1;8800,2.45

Note that we used two diﬀerent delimiters (”;” and ”,”) in our data, which
t map() and t reduce()

will help us in tokenizing data in MapReduce’s
functions.

19.8 Cox Regression by MapReduce

We implemented Cox Regression in 2-phase MapReduce algorithms:

• MapReduce PHASE-1: Generate data ready for calling coxph()

function

– map() PHASE-1: Group data by <geneID><referenceID>

– reduce() PHASE-1: Per reducer (key of <geneID><referenceID>),
generate <geneID><referenceID> followed by all values of gene
value in proper order of biosets (order has to be preserved, other-
wise coxph() call will be meaningless.

• MapReduce PHASE-2: Call coxph() and analyze generated results

– map() PHASE-2: Call coxph() for data generated by t reduce()

phase of Phase1.

– reduce() PHASE-2: NONE

19.8.1 Cox Regression PHASE-1: map()

The mapper is an identity mapper. It accepts a (key, value) pairs and emits
the same (key, value) pairs.

Listing 19.2: Cox Regression Algorithm PHASE-1: map()

479

1 /**
2

3

4

8

9

10
11 }

* Each input record represents a (key, value) pair
* @param key is: <geneID><,><referenceID>
* @param value is: <biosetID><,><geneValue>
*/

5
6 map(key, value) {
7

String[] tokens = Stringutil.split(value, ";");
String reducerKey = tokens[0]; // <geneID><,><referenceID>
String reducerValue = tokens[1]; // <biosetID><,><geneValue>
emit(reducerKey, reducerValue);

19.8.2 Cox Regression PHASE-1: reduce()

Each reducer accepts a (key, values) pair, where key is a pair of (geneID,
referenceID) and values is a list of pair of (biosetID, geneValue). The
reducer orders geneValue(s) according to the order of biosets received at
the setup() of the reducer class. For example if values = {(B1, G1), (B3,
G3), (B4, G4), (B2, G2)} and biosets are received as (B1, B2, B3, B4),
then reducer will generate sorted gene values as (G1, G2, G3, G4).

Listing 19.3: Cox Regression Algorithm PHASE-1: reduce()

1 /**
2

* @param key key is the <geneID><referenceID>
* @param values is a list of {<biosetID><,><geneValue>}
* NOTE: bioset IDs (List<Long>) will be passed from MapReduce Driver and
* will be saved at the reducer’s setup() function (done once before reduce() starts)
*/

6
7 reduce(key, values) {
8

3

4

5

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

String[] doubleValues = new String[biosets.size()];
int numberOfValues = 0;
for (pair : values) {

String[] tokens = StringUtils.split(pair, ",");
String biosetID = tokens[0];
String geneValue = tokens[1];

int index = biosets.indexOf(biosetID);
if (index == -1) {

// biosetID not found
return;

}

// biosetID found at location "index"
doublevalues[index] = geneValue;
numberOfValues++;

}

// values are candidate for cox regression analysis

480

if (numberOfValues != biosets.size()) {

// there are not enough gene values for these biosets,
// can not perform cox regression
return;

}

// numberOfValues == biosets.size()
StringBuilder builder = new StringBuilder();
builder.append(key.toString());
builder.append(",");
for (int i=0; i < doublevalues.length; i++) {

builder.append(doublevalues[i]);
// check to see if we need to add comma
if (i < (doublevalues.length -1)) {

builder.append(",");

}

}

// prepare reducer for output
String reducerValue = builder.toString();
// reducerValue = <geneID><,><referenceID>, value1, value2, ..., valueN
context.write(null, reducerValue);

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48
49 }

19.8.3 Cox Regression PHASE-2: map()

The mapper accepts an HDFS input ﬁle and then executes coxph() with
this input. Output is then transferred to HDFS for ﬁnal analysis. For this
mapper, we do need a setup() function which will be executed once.

Listing 19.4: Cox Regression Algorithm PHASE-2: setup()

1 /**
2

3

5

4

which will be used as an input to cox regrssion analysis

* map(key) = LongWritable (generated by hadoop, ignored here)
* map(value) = Text (name of a HDFS file: /biomarker/output/rnae/0/part-r-00000)
*
*
*
*
7
8 */
9 public class CoxRegressionMapperPhase2
10

extends Mapper<LongWritable, Text, LongWritable, Text> {

reduce(key)
= none
reduce(value) = none

6

11

12

13

14

15

16

17

18

19

private Configuration conf = null;
private FileSystem fs = null;
private String timeAsCommaSeparatedString = null;
private String censorAsCommaSeparatedString = null;
private String hadoopOutputPathAsString = null;

...

481

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

// will be run only once
public void setup(Context context)

throws IOException, InterruptedException {
this.conf = context.getConfiguration();
this.fs = FileSystem.get(conf);
hadoopOutputPathAsString = conf.get("hadoopOutputPathAsString");
timeAsCommaSeparatedString = conf.get("time");
censorAsCommaSeparatedString = conf.get("censor");

//
// make sure /hadoop/home/cox_regression.r.template file does exist
// in local unix file system, if it does not exist then copy it from
// hdfs:/biomarker/template/cox_regression.r.template
//
if (IOUtil.fileExists(CoxRegressionUsingR.COX_REGRESSION_TEMPLATE_FILE_FULL_NAME)) {

THE_LOGGER.info("template file does exist: "+
CoxRegressionUsingR.COX_REGRESSION_TEMPLATE_FILE_FULL_NAME);

}
else {

// copy it from HDFS
copyHDFSFileToLocal(CoxRegressionUsingR.COX_REGRESSION_TEMPLATE_FILE_HDFS_PATH,

CoxRegressionUsingR.COX_REGRESSION_TEMPLATE_FILE_FULL_NAME);

}

}

// map() defined next

Listing 19.5: Cox Regression Algorithm PHASE-2: map()

* @param key key is the key generated by MapReduce framework (not used here)
* @param value is the name of HDFS input file
* (for example: HDFS file like: </biomarker/output/rnae/0><,><part-r-00019>)
* NOTE: the following variables (timeAsCommaSeparatedString, censorAsCommaSeparatedString,
* and hadoopOutputPathAsString) are initialized in reducer’s setup() function (done once).
*/

generated by reduce() of PHASE-1

7
8 map(key, value) {
9

String coxRegressionInputFileName = "/tmp/" + HadoopUtil.getRandomUUID();
// coxRegressionInputFileName = /tmp/a99817a0-c149-4cb2-a771-dbc7da86b56a
String coxRegressionOutputFileName = coxRegressionInputFileName + ".out.txt";
File coxRegressionInputFile = new File(coxRegressionInputFileName);

Path hdfsPartFile = new Path(valueAsString);
FileUtil.copy(fs,

hdfsPartFile,
coxRegressionInputFile,
false,
conf);

// FileSystem
// src file
// destination
// boolean deleteSource,

int coxCallStatus = -1; // failure
// perform Cox Regression
coxCallStatus = CoxRegressionUsingR.callCoxRegression(

coxRegressionInputFileName,
coxRegressionOutputFileName,

482

1 /**
2

3

4

5

6

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

timeAsCommaSeparatedString,
censorAsCommaSeparatedString);

if (coxCallStatus == 0) {

// it is success! then copy coxRegressionOutputFileName to HDFS (to hadoopOutputPathAsString)
File coxRegressionOutputFile = new File(coxRegressionOutputFileName);
if (coxRegressionOutputFile.exists()) {

FileUtil.copy(coxRegressionOutputFile, fs, new Path(hadoopOutputPathAsString), false, conf);

}

}

// send it to reducer (indication, we are done for logging purposes)
context.write(key, value);

26

27

28

29

30

31

32

33

34

35

36

37

38
39 }

19.8.4 Sample Output Generated by PHASE-2 reduce()

Output ﬁles generated by reduce() of PHASE-1:

$ hadoop fs -ls /biomarker/output/rnae/0/part*
Found 30 items
-rw-r--r--
-rw-r--r--
-rw-r--r--
...
-rw-r--r--
-rw-r--r--
-rw-r--r--

3 hadoop hadoop 1047918 ... /biomarker/output/rnae/0/part-r-00000
3 hadoop hadoop 1053398 ... /biomarker/output/rnae/0/part-r-00001
3 hadoop hadoop 1022627 ... /biomarker/output/rnae/0/part-r-00002

3 hadoop hadoop 1026116 ... /biomarker/output/rnae/0/part-r-00025
3 hadoop hadoop 1030567 ... /biomarker/output/rnae/0/part-r-00026
3 hadoop hadoop 1028483 ... /biomarker/output/rnae/0/part-r-00027

If our test example has 5000 biosets, then we have:

[hadoop@hnode01337 ~]$ hadoop fs -cat /biomarker/output/rnae/0/part-r-00005 | head
100174,r1,1.8619553641448698,1.8925853151926535, ..., <5000th-value>
100181,r1,0.40490312214513074,2.67581593117227, ..., <5000th-value>
100191,r2,-13.287712379549449,13.28771237954945, ..., <5000th-value>
100237,r1,0.8147554828098739,-0.3391373849195852, ..., <5000th-value>
100314,r1,2.103665482765696,2.254594043033141, ..., <5000th-value>
100478,r2,0.0,0.0, ..., <5000th-value>
100482,r1,1.5464623581670915,-2.5864044748950628, ..., <5000th-value>
100545,r1,-2.454965473634712,0.41359408240917517, ..., <5000th-value>
100555,r2,-13.287712379549449,-0.15055967657538144, ..., <5000th-value>

483

19.8.5 Sample Output Generated by PHASE-2 map()

The ﬁrst column is <geneID_and_rreference>}, the second column is coef,
and the last column is pvalue.

0.02973554
0.326605

94893,r2 -0.04106195 0.7144141
94963,r2
0.2514287
95037,r1 -0.1822651
95047,r2 -0.02349459 0.8174117
0.4429394
95338,r1
0.06733862
95425,r2 -0.1370884
0.3265356
95719,r2 -0.02158204 0.9071648
0.6061742
0.1033474
95891,r1

19.8.6 Cox Regression by MapReduce: How Does It

Work

The CoxRegressionUsingR class has the core functionality for Cox regres-
sion. This class creates an Rscript from a template ﬁle. An instance of a
Rscript is given below:

Listing 19.6: Cox Regression Algorithm by Rscript

1 #!/usr/local/bin/Rscript
2
3 input_file = "/tmp/f11d10f4-e0a6-4796-9a1c-34c6914be1e7"
4 cat("input_file=", input_file, "\n")
5 output_file = "/tmp/f11d10f4-e0a6-4796-9a1c-34c6914be1e7.out.txt"
6 cat("output_file=", output_file, "\n")
7
8 library("survival")
9
10 # a function for conversion
11 convert=function(x){return(log2(max(x, -1/x)))}
12
13 # a function to perform Cox regression
14 cox_regression <- function(line){
15

#cat(line, "\n")
# each line has this format:
# <geneID><;><V1,V2,...,Vn><;><T1,T2,...,Tn><;><C1,C2,...,Cn>
items = unlist(strsplit(line, ";"))
#
geneID = items[[1]]
#
value = as.double(unlist(strsplit(items[[2]], ",")))
#

16

17

18

19

20

21

22

23

484

24

25

26

27

28

29

time = as.double(unlist(strsplit(items[[3]], ",")))
#
censor = as.double(unlist(strsplit(items[[4]], ",")))
#
coxphoutput = coxph(Surv(time,censor) ~ value)
pvalue = summary(coxphoutput)$waldtest[3]
cat(geneID, coxphoutput$coef, pvalue, "\n", file=output_file, append=TRUE)

30
31 }
32
33 # driver section of Rscript
34 conn <- file(input_file, open="r")
35 while(length(line <- readLines(conn, 1)) > 0) {
36
37 }
38 close.connection(conn)

try.output <- try( cox_regression(line) )

Rscript code description is given below:

Lines 34-37 This is the driver for the Rscript. It opens the ﬁle, reads line-
by-line, and applies the cox_regression function. Finally, it closes
the input ﬁle (to release the resources).

Lines 14-31 Deﬁnes our custom function called cox_regression(), which
calls R’s coxph() function. Line 18 tokenizes the input record. Finally,
coxph() produces ”coef” and ”pvalue”.

Line 30 Appends geneID, ”coef” and ”pvalue” to output ﬁle.

Sample output is given below:

$ head -4 /tmp/f11d10f4-e0a6-4796-9a1c-34c6914be1e7.out.txt
100007,r1,0.1038095,0.3594686
10017,r2,0.00613293,0.892313
100205,r1,-0.01681699,0.6164844
101583,r1,0.03383865,0.4736812

485

Chapter 20

Cochran-Armitage Test for Trend

20.1

Introduction

Cochran-Armitage Test for Trend (CATT) is used in analyzing germline1
data. For example, variants expressed as a VCF (Variant Call Format) and
generated by DNA-Sequencing can be labeled as a germline data. The CATT
is a statistical method of directing chi squared tests toward narrow alterna-
tives. Let R be a set of response variables and E be a set of experimental
variables, then the CATT is sensitive to the linearity between R(s) and E(s)
and detects trends. The CATT can be expressed another way:
let B be a
binary outcome of some events {PASSED, FAILED} and C be a set of or-
dered categories {C1, ..., Cn}, then CATT can be used as a linear trend in
proportions on B across levels of C. To apply CATT, we build a contigency
table: 2 rows with outcome values {PASSED, FAILED} and n columns as
{C1, ..., Cn}. The contingenecy table for CATT is explained in the next
sections.

According to Wikipedia2: ”The Cochran-Armitage test for trend, named
for William Cochran and Peter Armitage, is used in categorical data analysis
when the aim is to assess for the presence of an association between a variable
with two categories and a variable with k categories. It modiﬁes the Pearson
chi-squared test to incorporate a suspected ordering in the eﬀects of the k
categories of the second variable. For example, doses of a treatment can be

1https://en.wikipedia.org/wiki/Germline
2 https://en.wikipedia.org/wiki/Cochran%E2%80%93Armitage test for trend

486

ordered as ’low’, ’medium’, and ’high’, and we may suspect that the treat-
ment beneﬁt cannot become smaller as the dose increases. The trend test is
often used as a genotype-based test for case-control genetic association stud-
ies.” And according to Wellek and Ziegler3: ”The Cochran-Armitage trend
test based on the linear regression model has become a standard procedure
for association testing in case-control studies.”

20.2 Cochran-Armitage Algorithm

The CATT is applied when the data take the form of a 2×k contingency table.
The number of rows (2) indicate outcome of an experiment and the number
of columns indicate varibale number (k) of experiments. For example, if
k = 3, then the contingency will be:

(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)

Count

Group
A = 1
A = 2

B = 1 B = 2 B = 3

N11
N21

N12
N22

N13
N23

This contingency table can be completed with the marginal totals of the

two variables:

(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)

Count

Group
A = 1
A = 2
Sum

B = 1 B = 2 B = 3

Sum

N11
N21
C1

N12
N22
C2

N13
N23
C3

R1
R2
N

where

• R1 = N11 + N12 + N13
• R2 = N21 + N22 + N23
• C1 = N11 + N21
3 Cochran-Armitage test versus logistic regression in the analysis of genetic association
studies. Wellek S, Ziegler A. Department of Biostatistics, Central Institute of Mental
Health Mannheim, University of Heidelberg, Mannheim, Germany.

487

• C2 = N12 + N22
• C3 = N13 + N23
• N = R1 + R2 = C1 + C2 + C3 = N11 + N12 + N13 + N21 + N22 + N23

The trend test statistic is

T ≡

k
(cid:88)

i=1

wi(N1iR2 − N2iR1)

where the wi are weights.

The hypothesis of no association (known as the null hypothesis) can be

expressed as:

Pr(A = 1|B = 1) = · · · = Pr(A = 1|B = k)

Assuming that the null hypothesis holds, then, using iterated expectation we
can write:

E(T ) = E pE(T |R1, R2)q = E(0) = 0

Given two discrete random variables X and Y, you can deﬁne the condi-

tional expectation as:

E[X|Y = y] =

(cid:88)

x

x · P(X = x|Y = y)

Now, using all these deﬁnitions and formulas, we are ready to write Cochran-
Armitage Algorithm in Java. One major goal of CATT is compute the p-value
(a probability value between 0.00 and 1.00). Using the algorithm deﬁned in
Wikipedia, we implement CATT as a POJO class CochranArmitage. This
Java class will be used in our MapReduce solution.

Listing 20.1: Cochran-Armitage Algorithm

1 import java.io.BufferedReader;
2 import java.io.BufferedWriter;
3 import java.io.FileReader;
4 import java.io.FileWriter;
5 import java.io.IOException;
6

488

7 import org.apache.log4j.Logger;
8 import org.apache.commons.math3.distribution.NormalDistribution;
9
10 /**
11

* Class the calculates the Cochran-Armitage test for trend
* on a 2x3 contingency table. Used to estimate association
* in additive genetic models of genotype data.
*/

12

13

14
15 public class CochranArmitage {
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

private static final Logger THE_LOGGER = Logger.getLogger(CochranArmitage.class);

// use weights corresponding to additive/codominant model
private static final int[] WEIGHTS = { 0, 1, 2 };

// dimensions of passed contingency table - must be 2 rows x 3 columns
private static final int NUMBER_OF_ROWS = 2;
private static final int NUMBER_OF_COLUMNS = 3;

// variables to hold variance, raw statistic, standardized statistic, and p-value
private double stat = 0.0;
private double standardStatistics = 0.0;
private double variance = 0.0;
private double pValue = -1.0; // range is 0.0 to 1.0 (-1.0 means undefined)

// NormalDistribution class from Apache used to calculate p-values
private static NormalDistribution normDist = new NormalDistribution();

/**
* Get the variance
*/
public double getVariance() {

return variance;

}

/**
* Get the Stat
*/
public double getStat() {

return stat;

}

/**
* Get the StandardStatistics
*/
public double getStandardStatistics() {

return standardStatistics;

}

/**
* Get the pvalue
*/
public double getPvalue() {

return pValue;

}

489

/**
* Computes the Cochran-Armitage test for trend for the passed
* 2 row by 3 column contingency table
* @param countTable 2x3 contingency table
* @return the p-value of the Cochran-Armitage statistic of the passed table
*/
public double callCochranArmitageTest(int[][] countTable) {

// defined in next sections ...

}

/**
* @param args input/output files for testing/debugging
* args[0] as input file
* args[1] as output file
*/
public static void main(String[] args) throws IOException {

// defined in next sections ...

}

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82
83 }

The following method is the core of the Cochran-Armitage Algorithm:

Listing 20.2: Cochran-Armitage Algorithm: callCochranArmitageTest()

1 /**
2

3

4

5

* Computes the Cochran-Armitage test for trend for the passed
* 2 row by 3 column contingency table
* @param countTable 2x3 contingency table
* @return the p-value of the Cochran-Armitage statistic of the passed table
*/

6
7 public double callCochranArmitageTest(int[][] countTable) {
8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

if (countTable == null) {

throw new IllegalArgumentException("contingency table cannot be null/empty.");

}

if ( (countTable.length != NUMBER_OF_ROWS) || (countTable[0].length != NUMBER_OF_COLUMNS) ) {

throw new IllegalArgumentException("contingency table must be 2 rows by 3 columns");

}

int totalSum=0;
int[] rowSum = new int[NUMBER_OF_ROWS];
int[] colSum = new int[NUMBER_OF_COLUMNS];

// calculate marginal and overall sums for the contingency table
for (int i=0; i<NUMBER_OF_ROWS; i++) {

for (int j=0; j<NUMBER_OF_COLUMNS; j++) {

rowSum[i] += countTable[i][j];
colSum[j] += countTable[i][j];
totalSum += countTable[i][j];

}

490

}

// calculate the test statistic and variance based on the formulae at
// http://en.wikipedia.org/wiki/CochranArmitage_test_for_trend
stat = 0.0;
variance = 0.0;
for (int j=0; j<NUMBER_OF_COLUMNS; j++) {

stat += WEIGHTS[j] * (countTable[0][j]*rowSum[1] - countTable[1][j]*rowSum[0]);
variance += WEIGHTS[j]*WEIGHTS[j]*colSum[j]*(totalSum-colSum[j]);

if (j!=NUMBER_OF_COLUMNS-1) {

for (int k=j+1;k<NUMBER_OF_COLUMNS;k++) {

variance -= 2*WEIGHTS[j]*WEIGHTS[k]*colSum[j]*colSum[k];

}

}

}
variance *= rowSum[0]*rowSum[1]/totalSum;

// standardized statistic is stat divided by SD
standardStatistics = stat/Math.sqrt(variance);

// use Apache commons normal distribution to calculate two tailed p-value
pValue = 2*normDist.cumulativeProbability(-Math.abs(standardStatistics));

// return the p-value
return pValue;

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 }

The following program tests the Cochran-Armitage Algorithm:

Listing 20.3: Cochran-Armitage Algorithm: main()

1 /**
2

3

4

* @param args input/output files for testing/debugging
* args[0] as input file
* args[1] as output file
*/

5
6 public static void main(String[] args) throws IOException {
7

if (args.length != 2) {

8

9

10

11

12

13

14

15

16

17

18

19

20

21

THE_LOGGER.info("usage: java CochranArmitage <input-filename> <output-filename>");
throw new IOException("must provide input and output files for testing.");

}

long startTime = System.currentTimeMillis();
String inputFileName = args[0];
String outputFileName = args[1];
BufferedWriter outfile = new BufferedWriter(new FileWriter(outputFileName));
outfile.write("score\tp-value\n");
BufferedReader infile = new BufferedReader(new FileReader(inputFileName));

int[][] countTable = new int[2][3];
String line = null;
while (( line = infile.readLine()) != null) {

491

String[] tokens = line.split("\t");
int index=0;

// populate 2x3 contingency table
for(int i=0; i<2; i++) {

for(int j=0; j<3; j++) {

countTable[i][j] = Integer.parseInt(tokens[index++]);

}

}

CochranArmitage catest = new CochranArmitage();
double pValue = catest.callCochranArmitageTest(countTable);
outfile.write(String.format("%f\t%f\n", catest.getStandardStatistics(), pValue));

}

long elapsedTime = System.currentTimeMillis() - startTime;
THE_LOGGER.info("run time (in milliseconds): " + elapsedTime);

infile.close();
outfile.close();

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41
42 }

The following is a sample run of the Cochran-Armitage Algorithm:

# Compile the algorithm
$ javac CochranArmitage.java

# Define input
$ cat test3.txt
1386 1565 401 1342 1579
695
13
2716
2062 1144 151 2021 1184

2689

672

434
9
173

# Run algorithm
$java CochranArmitage test3.txt test3.txt.out
Jul 13 2013 04:36:31 [main] [INFO ] [CochranArmitage] - run time (in milliseconds): 9

# Expected output
$ cat test3.txt.out
p-value
score
0.157114
-1.414843
0.624943
-0.488857
0.119864
-1.555344

492

20.3 Application of Cochran-Armitage

In genome analysis, the CATT is applied for statistical tests for diﬀerence in
”Genotype Frequency”. For diﬀerences in genotype frequency, each individ-
ual should be coded as {0, 1, 2} based on the number of the particular variant
allele in that individual. These counts can be used to assemble a 2 × 3 (2
rows and 3 columns: each row represent a speciﬁc group and each column
represent outcome of an experiment such as an allele count) contingency ta-
ble that can be analyzed by standard statistical methods. The CATT is used
to approximate an additive genetic model.

The real example in genomic analysis can be stated as follows: let Group-A
denotes a set of biosets (generated from VCF – variant call format – ﬁles) for
a set of patients and let Group-B denotes another set of biosets (generated
from VCF ﬁles) for another set of patients. The goal is to apply CATT to a set
of alleles found at a speciﬁc chromosome4 with a given ”start position” and
”stop position” (for details on chromosomes, you may visit National Institute
of Health5). This data can be very huge. Each bioset generated from a
(human sample) VCF ﬁle may have over 4000,000 chromosomes. If Group-
A has 3,000 samples and Group-B has 5,000 samples to compare (genotype
frequency), then we have to analyze 32 billion records (obviously this is a big
data problem).

Group-A records = 3,000*4,000,000 = 12,000,000,000
Group-B records = 5,000*4,000,000 = 20,000,000,000
Total records = 12,000,000,000 + 20,000,000,000 = 32,000,000,000

To use the CATT for genotype frequency we form of a 2 × 3 contingency
table for each allele found at the common key of a speciﬁc chromosome
(identiﬁed by its ”start position” and ”end position”).

4Humans normally have 46 chromosomes in each cell, divided into 23 pairs. Two copies
of chromosome 1, one copy inherited from each parent, form one of the pairs. (source:
http://ghr.nlm.nih.gov/chromosome/1)

5 http://ghr.nlm.nih.gov/handbook/basics/chromosome

493

(cid:96)(cid:96)(cid:96)(cid:96)(cid:96)(cid:96)(cid:96)(cid:96)(cid:96)(cid:96)(cid:96)(cid:96)(cid:96)(cid:96)(cid:96)

Allele Count

Group
Group-A
Group-B

Count of 0

Count of 1

Count of 2

N11
N21

N12
N22

N13
N23

I will demonstrate building a 2 × 3 contingency table for each allele by
the following example. Let Group-A be a set of 6 biosets identiﬁed by
{B1, B2, B3, B4, B5, B6} and let Group-B be a set of 5 biosets identiﬁed
by {B7, B8, B9, B10, B11}. Note that these data are for a very speciﬁc chro-
mosome at a deﬁned position (identiﬁed by ”chromosome start position” and
”chromosome stop position”)

Group-A Biosets

Bioset ID
B1
B2
B3
B4
B5
B6

Allele1
A
A
A
G
A
AC

Allele2
C
A
C
G
A
T

Group-B Biosets

Bioset ID
B7
B8
B9
B10
B11

Allele1
A
C
A
A
A

Allele2
A
C
C
A
A

Before generating/building contingency tables, we do need to build some

data structures:

494

Genotype Frequency Table

Bioset ID
B1
B2
B3
B4
B5
B6
B7
B8
B9
B10
B11

Group
Group-A
Group-A
Group-A
Group-A
Group-A
Group-A
Group-B
Group-B
Group-B
Group-B
Group-B

"A" count
1
2
1
0
2
0
2
0
1
2
2

"C" count
1
0
1
0
0
0
0
2
1
0
0

"G" count
0
0
0
2
0
0
0
0
0
0
0

"T" count
0
0
0
0
0
1
0
0
0
0
0

"AC" count
0
0
0
0
0
1
0
0
0
0
0

Now, we can generate a contingency table for each allele (”A”, ”C”, ”G”,
”T”, and ”AC”), which then we may apply the CATT algorithm. In MapRe-
duce algorithm, each reducer for (Key2, Value2) will generate a set of contin-
gency tables (where Key2 is a composite key of chromosomeID:start:stop).

(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)

Count

Group
Group-A
Group-B

(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)

Count

Group
Group-A
Group-B

(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)

Count

Group
Group-A
Group-B

Contingency Table for allele ”A”

Count of 0

Count of 1

Count of 2

2
1

2
1

2
3

Contingency Table for allele ”C”

Count of 0

Count of 1

Count of 2

4
3

2
1

0
1

Contingency Table for allele ”G”

Count of 0

Count of 1

Count of 2

5
5

0
0

1
0

495

(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)

Count

Group
Group-A
Group-B

(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)

Count

Group
Group-A
Group-B

Contingency Table for allele ”T”

Count of 0

Count of 1

Count of 2

5
5

1
0

0
0

Contingency Table for allele ”AC”

Count of 0

Count of 1

Count of 2

5
5

1
0

0
0

20.4 MapReduce Solution

We present a MapReduce algorithm for CATT, which can be implemented by
Hadoop and Spark. Our implementation is based on MapReduce/Hadoop.

20.4.1

Input

Since the same bioset can be selected for both group of biosets (A and B), we
will generate two types of data (the only diﬀerence will be the GROUP-NAME,
for group A, GROUP-NAME will be a and for group B, GROUP-NAME will be b, this
will enable us to identify one group from another). Therefore, GROUP-NAME
can be in {a, b}.
Each bioset record will have the following format:

<chromosome-ID>
<:>
<chromosome-start-position>
<:>
<chromosome-stop-position>
<;>
<GROUP-NAME>
<:>
<allele1>
<:>

496

<allele2>
<:>
<referece>
<:>
<snp-id>
<:>
<mutation-class-ID>
<:>
<gene-id>
<:>
<bioset_Id>

For example, if we select 6 biosets for group A, then we will have:

7:10005296:10005296;a:A:C:A:snpid:mc:geneid:1000
7:10005296:10005296;a:A:A:A:snpid:mc:geneid:2000
7:10005296:10005296;a:A:C:C:snpid:mc:geneid:3000
7:10005296:10005296;a:G:G:G:snpid:mc:geneid:4000
7:10005296:10005296;a:A:A:A:snpid:mc:geneid:5000
7:10005296:10005296;a:AC:T:A:snpid:mc:geneid:6000

For example, if we select 5 biosets for group B, then we will have:

7:10005296:10005296;b:A:A:A:snpid:mc:geneid:7000
7:10005296:10005296;b:C:C:C:snpid:mc:geneid:7100
7:10005296:10005296;b:A:C:C:snpid:mc:geneid:7200
7:10005296:10005296;b:A:A:A:snpid:mc:geneid:7300
7:10005296:10005296;b:A:A:A:snpid:mc:geneid:7400

20.4.2 Expected Output

Each result record (p-value is generated by Cochran-Armitage Test) will have
the following format:

<pValue> (result of CATT)
<:>
<chromosome-ID>
<:>
<chromosome-start-position>
<:>

497

<chromosome-stop-position>
<:>
<gene-id>
<:>
<mutation-class-ID>
<:>
<reference>
<:>
<alternate-allele>
<:>
<N11>
<:>
<N12>
<:>
<N13>
<:>
<N21>
<:>
<N22>
<:>
<N23>
<:>
<snp-id>

20.4.3 Mapper

The mapper will generate a (key, value) pair for each record, where key will
be:

<chromosome-ID><:><chromosome-start-position><:><chromosome-stop-position>

and the value will be the remaining attributes:

<GROUP-NAME>
<:>
<allele1>
<:>
<allele2>
<:>

498

<referece>
<:>
<snp-id>
<:>
<mutation-class-ID>
<:>
<gene-id>
<:>
<bioset_Id>

Listing 20.4: map() for Cochran-Armitage

1 /**
2

3

4

5

6

7

8

9

10

14

15

16

17

where GROUP can be in {"a" , "b"}

<chr-ID><:><start><:><stop><;><GROUP><|><allele1><|><allele2><|>
<ref><|><snp-id><|><mutation-class><|><gene-id>|<bioset_Id>

* @param key the key generated by hadoop, ignored here
* @param value has the following format:
*
*
*
*
* reducerKey = Text:
* reducerValue = Text: <GROUP><|><allele1><|><allele2><|><ref><|>
*
*/

<chr-ID><:><start><:><stop>

<snp-id><|><mutation-class><|><gene-id>|<bioset_Id>

11
12 map(Object key, Text value) {
13

String[] tokens = StringUtils.split(line, ";");
if (tokens.length == 2) {

String reducerKey = tokens[0];
String reducerValue = tokens[1];
emit(reducerKey, reducerValue);

}

18
19 }

20.4.4 Reducer

The main task for CATT is done by reducers. Each reducer’s key will
be the key generated by mappers. The value of each reducer will a list
of values generated by mappers. Therefore, a reducer which has a key of
”7:10005296:10005296”, will have the following values (by iteration of one by
one):

a:A:C:A:snpid:mc:geneid:1000
a:A:A:A:snpid:mc:geneid:2000
a:A:C:C:snpid:mc:geneid:3000
a:G:G:G:snpid:mc:geneid:4000

499

a:A:A:A:snpid:mc:geneid:5000
a:AC:T:A:snpid:mc:geneid:6000
b:A:A:A:snpid:mc:geneid:7000
b:C:C:C:snpid:mc:geneid:7100
b:A:C:C:snpid:mc:geneid:7200
b:A:A:A:snpid:mc:geneid:7300
b:A:A:A:snpid:mc:geneid:7400

For implementation of reduce(), we do need 3 data structures:

// all alleles in Group-A and Group-B
Map<String, String[]> allAlleles = new HashMap<String, String[]>();

// all alleles in Group-A
List<String[]> groupA = new ArrayList<String[]>();

// all alleles in Group-A
List<String[]> groupB = new ArrayList<String[]>();

After all these 3 data structures are populated, we will generate contigency
tables and then apply Cochran-Armitage trend test.

Listing 20.5: reduce() for Cochran-Armitage

<GROUP><:><allele1><:><allele2><:><ref><:><snp-id><:><mutation-class><:><gene-id>:<bioset_Id>

1 /**
2

3

4

5

6

7

8

<chr-ID><:><start><:><stop>

where GROUP can be in {"a" , "b"}

* @param key the key: Text:
* @param values list of {value}, where each value has the following format:
*
*
*
* outputKey = null
* outputValue = built by buildOutputValue() method
*/

9
10 reduce(Text key, Iterable<Text> values) {
//
1
11
// reduce(value) = Text: <GROUP><:><allele1><:><allele2><:><ref><:><snp-id><:>
//
// reduce(value) = Text: <mutation-class><:><gene-id>:<bioset_Id>

tokens[index]

tokens[index]

14

12

13

5

7

6

0

3

4

2

15

16

17

18

19

20

Map<String, String[]> allAlleles = new HashMap<String, String[]>();
List<String[]> groupA = new ArrayList<String[]>();
List<String[]> groupB = new ArrayList<String[]>();

for (Text valueAsText : values) {

500

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 }

String value = valueAsText.toString();
String[] tokens = StringUtils.split(value, "|");
if (tokens.length != 8) {

continue;

}

String group = tokens[0];
String allele1 = tokens[1];
String allele2 = tokens[2];
if (!allAlleles.containsKey(allele1)) {
allAlleles.put(allele1, tokens);

}
if (!allAlleles.containsKey(allele2)) {
allAlleles.put(allele2, tokens);

}

if (group.equals("a")) {

// it is either group "a"
groupA.add(tokens);

}
else {

// or it is group "b"
groupB.add(tokens);

}

} // end-for

if ( (groupA.isEmpty()) & (groupB.isEmpty()) ){

return;

}

// iterate through allAllelles and do analysis
int[][] contingencyTable = new int[2][3]; // create a contingency table
for (Map.Entry<String, String[]> entry : allAlleles.entrySet()) {

String allele = entry.getKey();
String[] tokens = entry.getValue();

// key
// value

0

1
-------------------

// ------------------------------------------------
// create the following table:
//
//
//
// groupA
// groupB
//
//
// --------------------------------------------------

(index 0 is groupA)
(index 1 is groupB)

The pass this array of 2x3 to CochranArmitage Test

<-- counts

n12
n22

n11
n21

n10
n20

2

clearContingencyTable(contingencyTable);
fillContingencyTable(groupA, groupB, contingencyTable);
double pValue = CochranArmitage.callTrendTest(contingencyTable);
String outputValue = buildOutputValue(pValue, key, allele, tokens, contingencyTable);
// prepare reducer for output
emit(null, outputValue);

501

Listing 20.6: Helper Functions for Cochran-Armitage

1 private static void clearContingencyTable(int[][] contingencyTable) {
2

for (int i=0; i < 2; i++) {

3

4

5

for (int j=0; j < 3; j++) {

contingencyTable[i][j] = 0;

}

}

6
7 }
8
9 private static void fillContingencyTable(List<String[]> groupA,
List<String[]> groupB,
10
int[][] contingencyTable) {

11

12

13

14

15

16

17

18

19

20

21

for (String[] tokensA: groupA) {

int count = countAlleles(tokensA, allele);
// here count = 0, 1, or 2
contingencyTable[0][count]++; // (index 0 is groupA)

}

for (String[] tokensB: groupB) {

int count = countAlleles(tokensB, allele);
// here count = 0, 1, or 2
contingencyTable[1][count]++; // (index 1 is groupB)

}

22
23 }
24
25 private static int countAlleles(String[] tokens, String allele) {
26

int count = 0;
if (allele.equals(tokens[1])) {

count++;

}
if (allele.equals(tokens[2])) {

count++;

}
// here is count = 0, 1, or 2
return count;

27

28

29

30

31

32

33

34
35 }

The following method builds ﬁnal output to be emitted by reducers.

Listing 20.7: buildOutputValue() for Cochran-Armitage

1 String buildOutputValue(pValue, key, allele, tokens, contingencyTable) {
2

<GROUP><|><allele1><|><allele2><|><ref><|><snp-id><|>

1

2

3

4

<mutation-class><|><gene-id>|<bioset_Id>

6

7

= new StringBuilder();

0

5

// tokens:
// tokens[index]
// tokens:
// tokens[index]
StringBuilder outputValue
outputValue.append(pValue);
outputValue.append(":");
outputValue.append(key.toString());
outputValue.append(":");
outputValue.append(tokens[6]);
outputValue.append(":");

3

4

5

6

7

8

9

10

11

12

// pValue

// reduce(key) =

<chr-ID><:><start><:><stop>

// <gene-id>

502

outputValue.append(tokens[5]);
outputValue.append(":");
outputValue.append(tokens[3]);
outputValue.append(":");
outputValue.append(allele);
outputValue.append(":");
outputValue.append(contingencyTable[0][0]);
outputValue.append(":");
outputValue.append(contingencyTable[0][1]);
outputValue.append(":");
outputValue.append(contingencyTable[0][2]);
outputValue.append(":");
outputValue.append(contingencyTable[1][0]);
outputValue.append(":");
outputValue.append(contingencyTable[1][1]);
outputValue.append(":");
outputValue.append(contingencyTable[1][2]);
outputValue.append(":");
outputValue.append(tokens[4]);
return outputValue.toString();

// <mutation-class>

// <ref>

// alternate allele

// n10 (group A, count 0)

// n11 (group A, count 1)

// n12 (group A, count 2)

// n20 (group B, count 0)

// n21 (group B, count 1)

// n22 (group B, count 2)

// snp-id

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32
33 }

20.5 MapReduce/Hadoop Implementation

The Hadoop implementation for CATT is comprised of the following classes:

503

Class Name
CochranArmitage.java
CochranArmitageAnalyzer.java

CochranArmitageClient.java

CochranArmitageDriver.java

CochranArmitageItem.java

Hadoop Implementation Classes
Class Description
Cochran-Armitage Tred test Algorithm
Read and analyze the result
generated by MapReduce program
Simple class to submit
MapReduce jobs
Actual Driver to submit
MapReduce jobs
Output record is mapped into
this bean class

CochranArmitageItemFactory.java Factory class to generate

CochranArmitageItemImpl.java
CochranArmitageMapper.java

CochranArmitageReducer.java

PaginatedObject.java
ResultObject.java

CochranArmitageItem object
Implementation of CochranArmitageItem
Hadoop map() for Cochran-Armitage
Trend test Algorithm
Hadoop reduce() for Cochran-Armitage
Trend test Algorithm
How to paginate result for front-end
Result object for Cochran-Armitage
Trend Test Algorithm

20.5.1 Sample Run of MapReduce/Hadoop Implemen-

tation

20.5.1.1

Input

$ cat run_CochranArmitage.sh
#!/bin/bash
client=CochranArmitageClient
java $client interactive 0out groupA_0.txt groupB_0.txt

$ cat groupA_0.txt
0

$ cat groupB_0.txt
0

504

$ hadoop fs -cat /germline/groupA/0/*
7:100:200;a|A|C|Ref|snpid|mc|geneid|1000
7:100:200;a|A|A|Ref|snpid|mc|geneid|2000
7:100:200;a|A|C|Ref|snpid|mc|geneid|3000
7:100:200;a|G|G|Ref|snpid|mc|geneid|4000
7:100:200;a|A|A|Ref|snpid|mc|geneid|5000
7:100:200;a|AC|T|Ref|snpid|mc|geneid|6000

$ hadoop fs -cat /germline/groupB/0/*
7:100:200;b|A|A|Ref|snpid|mc|geneid|7000
7:100:200;b|C|C|Ref|snpid|mc|geneid|7100
7:100:200;b|A|C|Ref|snpid|mc|geneid|7200
7:100:200;b|A|A|Ref|snpid|mc|geneid|7300
7:100:200;b|A|A|Ref|snpid|mc|geneid|7400

20.5.1.2 Sample Run

$ ./run_CochranArmitage.sh
Jul 18 2013 16:34:40 [main] [INFO ] [CochranArmitageClient] - executionType: interactive
Jul 18 2013 16:34:40 [main] [INFO ] [CochranArmitageClient] - requestID: 0out
Jul 18 2013 16:34:40 [main] [INFO ] [CochranArmitageClient] - biosetIDsFilenameGroupA: groupA_0.txt
Jul 18 2013 16:34:40 [main] [INFO ] [CochranArmitageClient] - biosetIDsFilenameGroupB: groupB_0.txt
...
Jul 18 2013 16:34:41 [main] [INFO ] [org.apache.hadoop.mapred.JobClient] - Running job: job_201307110717_0285
Jul 18 2013 16:34:42 [main] [INFO ] [org.apache.hadoop.mapred.JobClient] - map 0% reduce 0%
Jul 18 2013 16:34:58 [main] [INFO ] [org.apache.hadoop.mapred.JobClient] - map 100% reduce 0%
Jul 18 2013 16:35:10 [main] [INFO ] [org.apache.hadoop.mapred.JobClient] - map 100% reduce 33%
Jul 18 2013 16:35:11 [main] [INFO ] [org.apache.hadoop.mapred.JobClient] - map 100% reduce 41%
Jul 18 2013 16:35:12 [main] [INFO ] [org.apache.hadoop.mapred.JobClient] - map 100% reduce 74%
Jul 18 2013 16:35:13 [main] [INFO ] [org.apache.hadoop.mapred.JobClient] - map 100% reduce 100%
Jul 18 2013 16:35:18 [main] [INFO ] [org.apache.hadoop.mapred.JobClient] - Job complete: job_201307110717_0285
...
Jul 18 2013 16:35:18 [main] [INFO ] [org.apache.hadoop.mapred.JobClient] -
Jul 18 2013 16:35:18 [main] [INFO ] [CochranArmitageDriver] - run(): jobSucceeded=true
Jul 18 2013 16:35:18 [main] [INFO ] [CochranArmitageDriver] - run(): Job Finished in 37.782 seconds
Jul 18 2013 16:35:18 [main] [INFO ] [CochranArmitageDriver] - run(): jobid=job_201307110717_0285
Jul 18 2013 16:35:18 [main] [INFO ] [CochranArmitageDriver] - submitJob(): runStatus=0

Map output records=11

505

Jul 18 2013 16:35:18 [main] [INFO ] [CochranArmitageClient] - main() jobid=job_201307110717_0285

20.5.1.3 Generated Output

$ hadoop fs -cat /biomarker/output/germline/0out/part*
0.2635524772829726:7:100:200:geneid:mc:Ref:AC:5:1:0:5:0:0:snpid
0.2635524772829726:7:100:200:geneid:mc:Ref:T:5:1:0:5:0:0:snpid
0.2635524772829726:7:100:200:geneid:mc:Ref:G:5:0:1:5:0:0:snpid
0.3545394797735012:7:100:200:geneid:mc:Ref:A:2:2:2:1:1:3:snpid
0.43276758066778453:7:100:200:geneid:mc:Ref:C:4:2:0:3:1:1:snpid

506

Chapter 21

Allelic Frequency

21.1

Introduction

Allelic Frequency is a technique used to ﬁnd frequency of alleles for genomic1
data (especially for germline2 data type). An ”allelic frequency”3 is deﬁned
as ”the percentage of a population of a species that carries a particular allele
on a given chromosome locus.” After all genomic data is aggrgated per de-
sired key (comprised of [chromosome, start-position, stop-position])
then Fisher’s Exact Test is applied. Fisher’s Exact Test is a statistical test
used to determine if there are non-random associations between two groups of
variables (these two groups of variables can be patient’s biosets, which will be
discussed shortly). We will then analyze and plot the output of the MapRe-
duce program. The input for Allelic Frequency comes from VCF ﬁles, which
are generated by DNA-Sequencing pipelines. Typically each VCF record
includes: chromosome, start-position, stop-position, genome-reference, and
two alleles (labeled as allele1 an allele2 – one from mother and one from
father). These information will be suﬃcient to perform an allelic frequency
for two sets of data.

The main goal of this chapter is to present a MapReduce solution, comprised
of three MapReduce jobs, to Allelic Frequency using Fisher’s Exact Test 4.

1http://en.wikipedia.org/wiki/Genomics
2http://en.wikipedia.org/wiki/Germline
3http://www.thefreedictionary.com/allele+frequency
4http://en.wikipedia.org/wiki/Fisher’s_exact_test

507

Figure 21.1: Mutation Example

To comprehend the importance and the impact of Allelic Frequency, it is
better to understnad the meaning of ”mutations”, ”migrations”, and ”selec-
tions”. For details on these concepts, see 5 and 6. Calculating an allelic
frequency in very important for biology scientists:
if over time, there are
changes in allele frequencies then this can implicate that genetic drift is oc-
curring or that new mutations have been introduced into the population.

Example of a mutation7 is illustrated below: the image shows that how
do populations change genetically away from the Hardy-Weinberg equilib-
rium.

In this chapter we will:

1. Find the p-value (probability value in the range of 0.00 to 1.00) for ev-
ery triplet of (chromosome, start, stop) between two given groups
(A and B) of biosets (deﬁned below). This will be accomplished by a
MapReduce Phase-1. For eﬃciency of run-time processing, for a given
bioset, we create two identical copies (they diﬀer just by groupID value)
of the original data by adding a groupID as ”a” and ”b”

5http://163.16.28.248/bio/activelearner/18/ch18c3.html
6http://www.ndsu.edu/pubweb/ mcclean/plsc431/popgen/popgen4.htm
7source of image is from http://163.16.28.248/bio/activelearner/18/images/ch18c3.jpg

508

2. Find the ﬁrst smallest 100 p-values among all chromosomes, which are
closest to 0.00 — as p-values get closer to 0.00, they become interesting
ones). This means that if we sort all p-values in ascending order, then
our desired solution will be the ﬁrst 100 p-values. This is implemented
by another MapReduce Phase-2 program. The outpt of Phase-1 will
be used as input to Phase-2.

3. Find the ﬁrst smallest-100 p-values per chromosome, which are closest
to 0.00. This is implemented by another MapReduce Phase-3 program.
The output of Phase-1 will be used as input to Phase-3.

21.2 Basic Deﬁnitions

21.2.1 Chromosome

A chromosome is an organized structure of DNA, protein, and RNA found
in cells. Human cells have 23 pairs of chromosomes labeled as {1, 2, ...,
22, X, Y}. For details, see Wikipedia: Chromosome.

21.2.2 Bioset

We have a set of patients. Each patient has a set of biosets (biosets are cre-
ated directly from VCF ﬁles – each record of VCF ﬁle contains information
about a position in the genome) and each bioset has a set of genes. For
example, a bioset may have genes in RNA Gene-Expression data type, and
its associated values or ”fold change.” What is a bioset? Individually ana-
lyzed data signatures are referred to as ”biosets.” ”Biosets” encompass data
in the form of experimental sample comparisons (for transcriptomic, epi-
genetic, and copy number variation data), as well as genotype signatures
(for GWAS and mutational data). A bioset most commonly referred to
as a ”gene signature.” A sample record of a bioset will contain a chromo-
some, its start and stop positions, two alleles, and other related information.
A bioset has an associated data type. A bioset data type can be ”gene-
expression,” ”protein-expression,” ”methylation,” ”copy-number-variation,”
”miRNA,” or ”somatic mutation.” The number of entries/records per bioset
does depend on the data type of a bioset. For example, a germline bioset
can have 4.3 million records while a gene-expression bioset can have up to
60,000 records.

509

21.2.3 Allele and Allelic Frequency

What is an ”allele” and ”allelic frequency”? An allele8 is a viable DNA
(deoxyribonucleic acid) coding that occupies a given locus (position) on a
chromosome. There are two alleles per chromosome position and they are
called allele1 and allele2. An allelic frequency is deﬁned as ”the percent-
age of a population of a species that carries a particular allele on a given
chromosome locus.” Alternatively, ”allele frequency” can be deﬁned as the
frequency of an allele relative to that of other alleles of the same gene in
a population. Typically, the Fisher’s Exact Test is used to calculate the
”pvalue” (probability value) for Allelic Frequency. The Fisher’s Exact Test
uses a 2×2 contingency table, which represents how diﬀerent treatments have
produced diﬀerent outcomes. Furthermore, the Fisher’s Exact Test is based
on ”null hypothesis,” which assumes that treatments do not aﬀect outcomes,
that the two are independent.

21.2.4 Source of Data for Allelic Frequency

Shotgun sequencing machines generate DNA-Sequence data (in FASTQ9 and
other well known formats) from biological (including human) samples. Then
these FASTQ data (size of these can be up to 200GB) are analyzed by DNA
sequencing10 software and workﬂows, which eventually generate VCF (Vari-
ant Call Format)11 ﬁles. VCF is the result of DNA sequencing on germline
data. VCF has a text ﬁle format and partitioed into meta-data (what kind
of data it represents, quality of data, ...) and data. Once a VCF ﬁle is avail-
able, then we can create biosets and biomarkers (which are used in further
analysis of genomes contained in groups of biosets/biomarkers). One such
analysis is an ”Allelic Frequency”, which we will focus in this chapter. A
workﬂow diagram for Allelic Frequency is presented below.

Allelic Frequency for germline data is a big data problem: each germline
bioset has about 4.3 millions records (genomic information, such as chro-
mosome ID, chromosome start position, chromosome end position, reference

8http://www.sciencedaily.com/articles/a/allele.htm
9http://en.wikipedia.org/wiki/FASTQ_format
10https://en.wikipedia.org/wiki/DNA_sequencing
11http://en.wikipedia.org/wiki/Variant_Call_Format

510

Figure 21.2: Allelic Frequency WorkFlow

511

Imagine we have two group of germline
genome, allele1, and allele2, ...).
biosets: A and B. If group A has 2000 biosets and group B has 4000 biosets
and we want to ﬁnd an ”Allelic Frequency” of ”group A biosets” with ”group
B biosets”, then we have to analyze

4, 300, 000 × (2000 + 4000) = 25, 800, 000, 000

records and on top of it we have to do ”Allelic Frequency” analysis (such
as Fisher’s Exact Test) for all alleles (allele1, and allele2) in groups A and
B. With 15 nodes Hadoop cluster, ”allele frequency” analysis takes about 20
minutes and with 100 nodes this might take just under 4 minutes.

21.2.5 Allelic Frequency Analysis by Fisher’s Exact

Test

Typically, after we ﬁnd the Allelic Frequency for a given chromosome ( iden-
tiﬁed by its chromosome ID, start position, and end stop position), we apply
Fisher’s Exact Test to ﬁnd the pvalue where (0.0 ≤ pvalue ≤ 1.0). As
pvalue is getting closer to 1.0, it indicates that the association between rows
(groups) and columns (outcomes) is considered to be not statistically signif-
icant; and as pvalue is moving closer to 0.0, it indicates that the association
between rows (groups) and columns (outcomes) is statistically signiﬁcant.

21.2.6 Fisher’s Exact Test

What is the Fisher’s Exact Test? Fisher’s12 exact test is ”A statistical test
of independence much used in medical research. It tests the independence
of rows and columns in a 2 × 2 contingency table (with 2 horizontal rows
crossing 2 vertical columns creating 4 places for data) based on the exact
sampling distribution of the observed frequencies. Hence it is an exact test.”
The Fisher’s Exact Test was devised by Sir Ronald Aylmer Fisher13.

Typically, Fisher’s test is conducted for two groups (Group-1, Group-2)
with two outcomes (Outcome-1, Outcome-2). Actual data values are shown
in blue color.

12http://www.medterms.com/script/main/art.asp?articlekey=3469
13http://en.wikipedia.org/wiki/Ronald_Fisher

512

Group-1
Group-2
Column Totals

Outcome-1 Outcome-2 Row Totals
a
c
a + c

a + b
c + d
n = a+b+c+d

b
d
b + d

Fisher’s Exact Test formula is given below:

ˆ

p =

a + b
a
ˆ

˙ˆ

˙

c + d
c
˙

n
a + c

=

(a+b)! (c+d)! (a+c)! (b+d)!
a! b! c! d! n!

is a Binomial coeﬃcient and n! is a factorial of n.

where

ˆ

˙

n
k

What do we determine with Fisher’s Exact Test? ”Fisher’s exact test can
be used to statistically determine whether there is any association between
two categorical variables with two levels each. The p-value for this test is
the probability that the observed data or more extreme data occur under
the null hypothesis of no diﬀerence between the two levels.” (source: http:
//rfd.uoregon.edu/files/rfd/StatisticalResources/lec_05a.txt).

Below we provide two simple examples:

• An example of 2 × 2 contingency table is given below:

Group-1
Group-2
Column Totals

Success Failure Row Totals
16
12
18
10
n = 34
22

4
8
12

Fisher’s exact test: the two-tailed p-value equals to 0.2966. The as-
sociation between rows (groups) and columns (outcomes) is considered
to be not statistically signiﬁcant. A p-value can be calculated with
either one or two tails. It is recommended to use two-tailed (also called
two-sided) P values (for details on one-tail vs. two-tail P values see
[2]).

513

For example, in R programming language, we can perform Fisher’s
Exact Test as:

# R
R version 2.15.1 (2012-06-22)
> mytable = rbind ( c(4, 12), c(8, 10) );
> mytable

[,1] [,2]
12
10

[1,]
[2,]
> fisher.test(mytable)

4
8

Fisher’s Exact Test for Count Data
data: mytable
p-value = 0.2966

• An example of 2 × 2 contingency table is given below:

Group-1
Group-2
Column Totals

Success Failure Row Totals
14
2
12
10
n = 26
12

12
2
14

Fisher’s exact test: the two-tailed p-value equals 0.0011 The associ-
ation between rows (groups) and columns (outcomes) is considered to
be very statistically signiﬁcant.

21.3 Formal Problem Statement

Let A (denoted by groupID of ”a”) and B (denoted by groupID of ”b”) be
a set of biosets for germline data (these biosets are created from VCF ﬁles
generated by DNA-Sequencing). Size of set A is m and size of set B is n.
Note that m and n can be the same or diﬀerent sizes). Given A and B, we
want to ﬁnd the Allelec Frequency for these two groups by using Fisher’s
Exact Test. Each bioset record represents a variant and will be identiﬁed by
the following attributes. Note that a bioset record may have over 50 attrbites,
but for Allelec Frequency the following attributes will be suﬃcient):

• Bioset’s Key Attributes

514

– Chromosome ID: 1, 2, 3, ...

– Chromosome Start position

– Chromosome Stop position

• Bioset’s Value Attributes

– Group ID: ”a”, ”b”

– Allele1

– Allele2

– Reference

– SNP ID

– Mutation Class ID

– Gene ID

– Bioset ID

Therefore, we need to implement:

1. Find the p-value for every triplet of (chromosomeID, start, stop) be-
tween two given groups of A and B. This is solved by MapReduce-
Phase-1.

2. Find the ﬁrst 100 p-values, which are closest to 0.00 — as p-values get
closer to 0.00, they become interesting ones). This means that if we
sort all p-values in ascending order, then our desired solution will be
the ﬁrst 100 p-values. This is solved by MapReduce-Phase-2. Output
of Phase-1 will be an input to Phase-2.

3. Find the ﬁrst smallest 100 p-values per chromosome, which are closest
to 0.00. This is solved by MapReduce-Phase-3. Output of Phase-1 will
be an input to Phase-3.

21.4 MapReduce Phase-1

This phase ﬁnds the p-value for every triplet of (chromosome, start, stop) be-
tween two given groups (A and B) of biosets. The map() function will group
input records by key of (chromosome, start, stop). The reduce() function

515

will construct a 2 × 2 contingency table and ﬁnally calls the Fisher’s Exact
Test. It is not possible provide a combine() function, since we need all alleles
per reducer.

21.4.1

Input

Since the same bioset can be selected for both sets (A and B), we will generate
two types of data (the only diﬀerence will be the group-name, for group A,
group-name will be a and for group B, group-name will be b, this will enable
us to identify one group from another).
Each bioset record will have the following format:

<chromosome-ID>
<:>
<chromosome-start-position>
<:>
<chromosome-stop-position>
<;>
<GROUP-NAME>
<:>
<allele1>
<:>
<allele2>
<:>
<referece>
<:>
<snp-id>
<:>
<mutation-class-ID>
<:>
<gene-id>
<:>
<bioset_Id>

For example, if we select 6 biosets for group A, then for chromosome 7

we might have the following data:

7:10005296:10005296;a:A:C:A:snpid:mc:geneid:1000
7:10005296:10005296;a:A:A:A:snpid:mc:geneid:2000

516

7:10005296:10005296;a:A:C:C:snpid:mc:geneid:3000
7:10005296:10005296;a:G:G:G:snpid:mc:geneid:4000
7:10005296:10005296;a:A:A:A:snpid:mc:geneid:5000
7:10005296:10005296;a:AC:T:A:snpid:mc:geneid:6000

For example, if we select 5 biosets for group B, then for chromosome 7

we might have the following data:

7:10005296:10005296;b:A:A:A:snpid:mc:geneid:7000
7:10005296:10005296;b:C:C:C:snpid:mc:geneid:7100
7:10005296:10005296;b:A:C:C:snpid:mc:geneid:7200
7:10005296:10005296;b:A:A:A:snpid:mc:geneid:7300
7:10005296:10005296;b:A:A:A:snpid:mc:geneid:7400

21.4.2 Output/Result

Each output/result record (pValue is generated by Fisher’s Exact Test per
chromosome-ID, chromosome-start-position, and chromosome-stop-position)
will have the following format:

517

<pValue> (result of Fisher’s Exact Test)
<:>
<chromosome-ID>
<:>
<chromosome-start-position>
<:>
<chromosome-stop-position>
<:>
<gene-id>
<:>
<mutation-class-ID>
<:>
<reference>
<:>
<alternate-allele>
<:>
<N11>
<:>
<N12>
<:>
<N21>
<:>
<N22>
<:>
<snp-id>

Note that N11, N12, N21, N22 refers to the values that we generate as a
2 × 2 contingency table shown below:

Row Totals
N11 + N12
Group-A
Group-B
N21 + N22
Column Totals N11 + N21 N12 + N22 n = N11 + N12 + N21 + N22

Known
N11
N21

Others
N12
N22

Allelec Frequency analysis by Fisher’s Exact Test will generate the following
output:

1.0:7:10005296:10005296:geneid:mc:A:AC:1:11:0:10:snpid
1.0:7:10005296:10005296:geneid:mc:A:T:1:11:0:10:snpid
0.480519480519484:7:10005296:10005296:geneid:mc:G:G:2:10:0:10:snpid
0.4148606811145488:7:10005296:10005296:geneid:mc:A:A:6:6:7:3:snpid
0.6240601503759411:7:10005296:10005296:geneid:mc:C:C:2:10:3:7:snpid

518

21.4.3 MapReduce Solution for Allelec Frequency

We implement Allelec Frequency by 3-phase MapReduce algorithms:

• MapReduce Phase-1: Aggregate, Group By, and Generate p-values

by calling Fisher’s Exact Test

• MapReduce Phase-2: Use output of Phase-1 and ﬁnd the bottom
100 smallest p-values among all chromosomes. We have designed this
algorithm in such a way that we will be able to ﬁnd bottom-N smallest
for any N — for example, bottom 50 or bottom 500).

• MapReduce Phase-3: Find the ﬁrst smallest-100 p-values per chro-
mosome which are closest to 0.00. For example, what is the smallest-
100 p-values for chromosome 5?

21.4.4 Phase-1 Mapper

The mapper will generate a (key, value) pair for each record, where key will
be:

<chromosome-ID><:><chromosome-start-position><:><chromosome-stop-position>

and the value will be the remaining attributes:

<GROUP-NAME>
<:>
<allele1>
<:>
<allele2>
<:>
<referece>
<:>
<snpID>
<:>
<mutationClassID>
<:>
<geneID>
<:>
<biosetID>

Listing 21.1: map() for Allelec Frequency

519

1 /**
2 * @param key the key generated by hadoop, ignored here
3 * @param value has the following format:
4 * <chrID><:><start><:><stop><;><GROUP><|><allele1><|><allele2><|><ref><|>
5 *
6 * where GROUP can be in {"a" , "b"}
7 *
8 * reducerKey = Text: <chrID><:><start><:><stop>
9 * reducerValue = Text: <GROUP><|><allele1><|><allele2><|><ref><|>

<snpID><|><mutationClass><|><geneID>|<biosetID>

<snpID><|><mutationClass><|><geneID>|<biosetID>

10
11 */
12 map(Text key, Text value)

{
String[] tokens = StringUtils.split(line, ";");
if (tokens.length == 2) {

String reducerKey = tokens[0];
String reducerValue = tokens[1];
emit(reducerKey, reducerValue);

13

14

15

16

17

}

18
19 }

The mapper function generates (key, value) pairs, where key is comprised
of { chrID, start, stop } and value is comprised of { GROUP, allele1,
allele2, ref, snpID, mutationClass, geneID, biosetID } . Therefore,
each reducer will receive a key as <chrID><:><start><:><stop> and values
(as a list of mappers’s emitted values).

21.4.5 Phase-1 Reducer

The main task is done by reducers. Each reducer’s key will be the key gen-
erated by mappers. The value of each reducer will be a list of values generated
by mappers. Therefore, a reducer which has a key of "7:10005296:10005296"
will have the following values (by iteration of one by one):

a:A:C:A:snpid:mc:geneid:1000
a:A:A:A:snpid:mc:geneid:2000
a:A:C:C:snpid:mc:geneid:3000
a:G:G:G:snpid:mc:geneid:4000

520

a:A:A:A:snpid:mc:geneid:5000
a:AC:T:A:snpid:mc:geneid:6000
b:A:A:A:snpid:mc:geneid:7000
b:C:C:C:snpid:mc:geneid:7100
b:A:C:C:snpid:mc:geneid:7200
b:A:A:A:snpid:mc:geneid:7300
b:A:A:A:snpid:mc:geneid:7400

In our implementation of a reducer, we do need 3 basic hash tables:

• groupA: alleles, which are only in group A

Map<String, Integer> groupA = new HashMap<String, Integer>();

• groupB: alleles, which are only in group B

Map<String, Integer> groupB = new HashMap<String, Integer>();

• globalMap: alleles, which are group A or group B

Map<String, String[]> globalMap = new HashMap<String, String[]>();

After all these 3 tables are populated per key (as <chrID><:><start><:><stop>),
we will iterate globalMap to ﬁnd all Allelec Frequencies.

Listing 21.2: reduce() for Allelec Frequency

<chrID><:><start><:><stop>

<mutationClass><:><geneID>:<biosetID>

1 /**
2 * @param key the key: Text:
3 * @param values list of {value}, where each value has the following format:
4 * <GROUP><:><allele1><:><allele2><:><ref><:><snpID><:>
5 *
6 * where GROUP can be in {"a" , "b"}
7 *
8 * outputKey = null (no key is required)
9 * outputValue = built by buildOutputValue() method
10 */
11 reduce(Text key, Iterable<Text> values) {

521

12

13

14

15

16

17

18

19

20

21

22

23

24

25
26 }

int totalNumOfBiosetsInGroupA = 0;
int totalNumOfBiosetsInGroupB = 0;

Map<String, String[]> globalMap = new HashMap<String, String[]>();
Map<String, Integer> groupA = new HashMap<String, Integer>();
Map<String, Integer> groupB = new HashMap<String, Integer>();

<STEP-1: POPULATE-TABLES-BY-ITERATING-VALUES>

// STEP-2: create an instance of the Fisher’s Exact Test
FisherExactTest theFisherExactTest = new FisherExactTest();

<STEP-3: FIND-ALLELIC-FREQUENCIES-BY-ITERATING-TABLES-BUILT>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

Listing 21.3: STEP-1: POPULATE-TABLES-BY-ITERATING-VALUES

for (Text valueAsText: values) {

String value = valueAsText.toString();
String[] tokens = StringUtils.split(value, ":");
if (tokens.length != 8) {

continue;

}

1

0

2

5

tokens[index]

tokens[index]

// reduce(value) = <GROUP><:><allele1><:><allele2><:><ref><:><snpID><:>
//
3
// reduce(value) = <mutationClass><:><geneID>:<biosetID>
//
String group = tokens[0];
String allele1 = tokens[1];
String allele2 = tokens[2];
if (group.equals("a")) {
// it is group "a"
totalNumOfBiosetsInGroupA++;
// handle allele1
Integer count = groupA.get(allele1);

7

6

4

522

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

if (count == null) {

groupA.put(allele1, 1);
globalMap.put(allele1, tokens);

}
else {

groupA.put(allele1, Integer.valueOf(count.intValue() + 1));

}
// handle allele2
Integer count2 = groupA.get(allele2);
if (count2 == null) {

groupA.put(allele2, 1);
globalMap.put(allele2, tokens);

}
else {

groupA.put(allele2, Integer.valueOf(count2.intValue() + 1));

}

}
else {

// handle allele1 for group "b"
totalNumOfBiosetsInGroupB++;
Integer count = groupB.get(allele1);
if (count == null) {

groupB.put(allele1, 1);
// check to see if we want to add this allele or not
if (!globalMap.containsKey(allele1)) {
globalMap.put(allele1, tokens);

}

}
else {

groupB.put(allele1, Integer.valueOf(count.intValue() + 1));

}
// handle allele2
Integer count2 = groupB.get(allele2);
if (count2 == null) {

groupB.put(allele2, 1);
// check to see if we want to add this allele or not
if (!globalMap.containsKey(allele2)) {

523

57

58

59

60

61

62

63

64

65

66

67

68

69

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

globalMap.put(allele2, tokens);

}

}
else {

groupB.put(allele2, Integer.valueOf(count2.intValue() + 1));

}

}

} // end-while

if ( (groupA.size() == 0) || (groupB.size() == 0) ){

return;

}

Listing 21.4: STEP-3:

FIND-ALLELIC-FREQUENCIES-BY-ITERATING-

TABLES-BUILT

groupA<String, Integer>
groupB<String, Integer>
globalMap<allele, tokens[])

// now all of our 3 required hash tables are created:
//
//
//
//
// next, iterate through globalMap<allele, tokens[]) and do analysis
// note that globalMap<allele, tokens[]) has all alleles
for (Map.Entry<String, String[]> entry : globalMap.entrySet()) {

String allele = entry.getKey(); // key
String[] tokens = entry.getValue();

int n11 = 0;
int n12 = 0;
int n21 = 0;
int n22 = 0;

// check to see if groupA has this allele:
Integer countOfAllelesInGroupA = groupA.get(allele);
Integer countOfAllelesInGroupB = groupB.get(allele);
if (countOfAllelesInGroupA == null) {

524

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

// then this allele must be only in groupB
n11 = 0;
n12 = (2 * totalNumOfBiosetsInGroupA);
n21 = countOfAllelesInGroupB;
n22 = (2 * totalNumOfBiosetsInGroupB) - n21;

}
else if (countOfAllelesInGroupB == null) {

// then this allele must be only in groupA
n11 = countOfAllelesInGroupA;
n12 = (2 * totalNumOfBiosetsInGroupA) - n11;
n21 = 0;
n22 = (2 * totalNumOfBiosetsInGroupB);

}
else {

// then this allele must be in both (groupA and groupB)
n11 = countOfAllelesInGroupA;
n12 = (2 * totalNumOfBiosetsInGroupA) - n11;
n21 = countOfAllelesInGroupB;
n22 = (2 * totalNumOfBiosetsInGroupB) - n21;

}

theFisherExactTest.init(n11, n12, n21, n22);
double pValue = theFisherExactTest.get2Tail();
String outputValue = buildOutputValue(pValue, key, allele, tokens, n11, n12, n21, n22);
// prepare reducer for output
emit(null, outputValue);

}// end for-loop

47
48 }

Listing 21.5: buildOutputValue() for Allelec Frequency

1 String buildOutputValue(pValue, key, allele, tokens, n11, n12, n21, n22) {

2

3

4

5

6

StringBuilder outputValue = new StringBuilder();
outputValue.append(pValue);
outputValue.append(":");
outputValue.append(key.toString()); // key = <chrID><:><start><:><stop>
outputValue.append(":");

// pValue

525

outputValue.append(tokens[6]);
outputValue.append(":");
outputValue.append(tokens[5]);
outputValue.append(":");
outputValue.append(tokens[3]);
outputValue.append(":");
outputValue.append(allele);
outputValue.append(":");
outputValue.append(n11);
outputValue.append(":");
outputValue.append(n12);
outputValue.append(":");
outputValue.append(n21);
outputValue.append(":");
outputValue.append(n22);
outputValue.append(":");
outputValue.append(tokens[4]);
return outputValue.toString();

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24
25 }

// <geneID>

// <mutationClass>

// <ref>

// alternate allele

// n11

// n12

// n21

// n22

// snpID

21.4.6 Sample Run of MapReduce/Hadoop Implemen-

tation

21.4.6.1 The Script

# cat run_test.sh
#!/bin/bash
groupA=/bioset/input/groupA/groupA.txt
groupB=/bioset/input/groupB/groupB.txt
output=/bioset/output
java AllelicFrequencyClient interactive $groupA $groupB $output

526

21.4.6.2

Input

# hadoop fs -cat /bioset/input/groupA/groupA.txt
7:100:200;a|A|C|Ref|snpid|mc|geneid|1000
7:100:200;a|A|A|Ref|snpid|mc|geneid|2000
7:100:200;a|A|C|Ref|snpid|mc|geneid|3000
7:100:200;a|G|G|Ref|snpid|mc|geneid|4000
7:100:200;a|A|A|Ref|snpid|mc|geneid|5000
7:100:200;a|AC|T|Ref|snpid|mc|geneid|6000

# hadoop fs -cat /bioset/input/groupB/groupB.txt
7:100:200;b|A|A|Ref|snpid|mc|geneid|7000
7:100:200;b|C|C|Ref|snpid|mc|geneid|7100
7:100:200;b|A|C|Ref|snpid|mc|geneid|7200
7:100:200;b|A|A|Ref|snpid|mc|geneid|7300
7:100:200;b|A|A|Ref|snpid|mc|geneid|7400

21.4.6.3 Running The Script

# . env.sh
JAVA_HOME=/usr/java/jdk6
# ./run_test.sh
Jul 18 2013 16:01:50 [main] [INFO ] [AllelicFrequencyClient] - executionType: interactive
Jul 18 2013 16:01:50 [main] [INFO ] [AllelicFrequencyClient] - requestID: 0
Jul 18 2013 16:01:50 [main] [INFO ] [AllelicFrequencyClient] - biosetIDsFilenameGroupA: groupA.txt
Jul 18 2013 16:01:50 [main] [INFO ] [AllelicFrequencyClient] - biosetIDsFilenameGroupB: groupB.txt
...
Jul 18 2013 16:01:51 [main] [INFO ] [AllelicFrequencyDriver] - GroupA biosetID: 0
Jul 18 2013 16:01:51 [main] [INFO ] [AllelicFrequencyDriver] - GroupA biosetPath::/bioset/input/groupA::
Jul 18 2013 16:01:51 [main] [INFO ] [AllelicFrequencyDriver] - GroupB biosetID: 0
Jul 18 2013 16:01:51 [main] [INFO ] [AllelicFrequencyDriver] - GroupB biosetPath::/bioset/input/groupB::
Jul 18 2013 16:01:51 [main] [INFO ] [AllelicFrequencyDriver] - - hadoopOutputPathAsString: /bioset/output
Jul 18 2013 16:01:51 [main] [INFO ] [AllelicFrequencyDriver] - run() wait=wait
...
Jul 18 2013 16:01:51 [main] [INFO ] [org.apache.hadoop.mapred.JobClient] - Running job: job_201307110717_0278
Jul 18 2013 16:01:52 [main] [INFO ] [org.apache.hadoop.mapred.JobClient] -
Jul 18 2013 16:02:06 [main] [INFO ] [org.apache.hadoop.mapred.JobClient] -
Jul 18 2013 16:02:16 [main] [INFO ] [org.apache.hadoop.mapred.JobClient] -
...
Jul 18 2013 16:03:07 [main] [INFO ] [org.apache.hadoop.mapred.JobClient] -
Jul 18 2013 16:03:12 [main] [INFO ] [org.apache.hadoop.mapred.JobClient] - Job complete: job_201307110717_0278
...
Jul 18 2013 16:03:12 [main] [INFO ] [org.apache.hadoop.mapred.JobClient] -
Jul 18 2013 16:03:12 [main] [INFO ] [AllelicFrequencyDriver] - run(): jobSucceeded=true
Jul 18 2013 16:03:12 [main] [INFO ] [AllelicFrequencyDriver] - run(): Job Finished in 80.862 seconds
Jul 18 2013 16:03:12 [main] [INFO ] [AllelicFrequencyDriver] - run(): jobid=job_201307110717_0278
Jul 18 2013 16:03:12 [main] [INFO ] [AllelicFrequencyDriver] - submitJob(): runStatus=0
Jul 18 2013 16:03:12 [main] [INFO ] [AllelicFrequencyClient] - main() jobid=job_201307110717_0278

map 0% reduce 0%
map 100% reduce 0%
map 100% reduce 6%

Map output records=11

map 100% reduce 100%

527

21.4.6.4 Generated Output

# hadoop fs -cat /bioset/output/part*
1.0:7:100:200:geneid:mc:Ref:AC:1:11:0:10:snpid
1.0:7:100:200:geneid:mc:Ref:T:1:11:0:10:snpid
0.480519480519484:7:100:200:geneid:mc:Ref:G:2:10:0:10:snpid
0.4148606811145488:7:100:200:geneid:mc:Ref:A:6:6:7:3:snpid
0.6240601503759411:7:100:200:geneid:mc:Ref:C:2:10:3:7:snpid

21.4.7 Sample Plot of Pvalues

Let’s say we have extracted pvalues from the Allelic Frequency output (into a
ﬁle called pvalue.txt and we want to plot these values (I have just extracted
about 40 pvalues here — out of 4.3 million). Using the R programming
language, it is straightforward:

# R
R version 2.15.1 (2012-06-22) -- "Roasted Marshmallows"
> p = read.table(’pvalue.txt’);
> p

V1
1 0.00
2 0.05
...
36 0.90
37 1.00
38 1.00
> plot(table(p));
> title(main="Allelic Frequency");
> q();

The output will be a PDF ﬁle illustrated below:

528

01234ptable(p)00.10.20.30.40.50.60.70.80.91Allelic Frequency21.5 MapReduce Phase-2

The goal of this phase is to ﬁnd the ﬁrst smallest 100 p-values among all
chromosomes, which are closest to 0.00. The output of Phase-1 will be used
as input to Phase-2. The easiest solution is to sort (by ascending order) the
output of Phase-1 by p-value and then output the ﬁrst 100 records (this is the
desired output). Since the output of Phase-1 may be big, sorting is not a good
option, instead, we solve this by another MapReduce job called as Phase-2.
Using relational databases (such as Oracle or MySQL), this question can be
answered as SQL query (assuming that allele_frequency_table is a table
which contains pvalue and <other> columns and data is loaded to this table
from the output of Phase-1):

SELECT *

FROM allele_frequency_table

ORDER BY pvalue LIMIT 100;

Using allele frequency algorithm (Phase-1), we were able to generate
(pvalue, chromosomeID, start, stop, ...) for all chromosomes for all given
biosets in both groups. Now we need to do sorting (in ascending order) and
ﬁnd the smallest-100 pvalues among generated records. Sorting all the out-
put generated by ”allele frequency algorithm” is not a good solution at all.
If the output of Phase-1 is huge, then we might ran out of memory. The
other option is to use another MapReduce program, which reads the output
of the ”allele frequency” and then generates the smallest-100 pvalues among
all chromosomes. How do we do this MapReduce for ﬁnding the smallest-100
pvalues? The new MapReduce algorithm is pretty simple:

1. Mapper:

a. Each mapper finds its local bottom-100 pvalues
and sends that bottom-100 list to the reducer.

b. We will use many mappers.

2. Reducer

530

Figure 21.3: p-value for Allelic Frequency

531

a. The reducer finds the final bottom-100 pvalues

from the bottom-100 lists sent from the mappers.

b. We will use a single reducer for final bottom-100.

21.5.1 Phase-2: Mapper for Bottom-100

The mappers will consume the outputs generated by allele frequency algo-
rithm. Each mapper will read (pvalue, chromosomeID, start, stop, ...) and
then emit a bottom-100 list of pvalues. Each mapper will use a bottom-100
list data structure. We will use the Java’s TreeMap14 data structure to keep
track of bottom-100 list: the bottom-100 sorted list will be preserved by the
pvalue (as a Double key) (0 ≤ pvalue ≤ 1).

import java.util.TreeMap;
...
TreeMap<Double, String> bottom100 = new TreeMap<Double, String>();

We have to make sure that out bottom100 data structure just holds ”bottom
100” pvalues. Here is the map() function inside Bottom100Mapper class: the
map() function itself will not emit any key-value pairs, but it will maintain
and update the bottom100 data structure. When the map() has completed
its function, then the cleanup() function will emit the ”bottom 100 list”.

Listing 21.6: Bottom100Mapper

1 public class Bottom100Mapper ... {
2

private SortedMap<Double, String> bottom100 =

new TreeMap<Double, String>();

3

4

5

14The java.util.TreeMap is a Red-Black tree based NavigableMap implementation.
The map is sorted according to the natural ordering of its keys, or by a Comparator
provided at map creation time, depending on which constructor is used. This implemen-
tation provides guaranteed log(n) time cost for the containsKey, get, put and remove
operations.

532

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

// key is the pvalue of double type and range is 0.00 to 1.00
// value is the entire record of allelic frequency output (includes pvalue)
map(Double key, String entireRecord) {

bottom100.put(key, value); // sort by pvalue
if (bottom100.size() > 100) {

// remove the greatest pvalue
bottom100.remove(bottom100.lastKey());

}

}

// called once at the end of the mapper task.
cleanup() {

for (Map.Entry<Double, String> entry : bottom100.entrySet() {

Double pvalue = entry.getKey();
String entireRecord = entry.getValue();
String outputValue = pair(pvalue, entireRecord);
// NULL key will send all key-value
// pairs to a single reducer only
emit(NULL, outputValue);

}

}

26
27 }

21.5.2 Phase-2: Reducer for ”Bottom 100”

We designed ”bottom100” algorithm in such a way so as to have only one
reducer to aggregate all bottom 100 lists generated by all mappers. The
key for our single reducer is NULL (in Hadoop this will be an instance of
NullWritable. To guarantee that we will have only one reducer, additionaly
we will set the number of reduce tasks (setNumOfReduceTasks()) to one (1)
in our job driver class:

Listing 21.7: Bottom100Driver

1 public class Bottom100Driver {
2

...
void run(String[] args) {

3

4

5

6

7

8

...
Job job = new Job(...);
...
job.setNumReduceTasks(1);
...

533

}
...

9

10
11 }

The job of the single Reducer is to generate the ﬁnal ”bottom 100” list
from all ”bottom 100” lists generated by all mappers. So, the reducer func-
tionality is very similar to the mappers.

Listing 21.8: Bottom100Reducer

1 public class Bottom100Reducer ... {
2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

reduce(NullWritable key, Iterable<pair<Double, String>> values) {

SortedMap<Double, String> finalBottom100 =

new TreeMap<Double, String>();

for (pair(Double, String) value : values) {

Double pvalue = value.pvalue;
String entireRecord = value.entireRecord;
finalBottom100.put(pvalue, entireRecord);

if (finalBottom100.size() > 100) {
// remove the greatest pvalue
finalBottom100.remove(finalBottom100.lastKey());

}

}

// now, we have the final bottom 100 list
for (Map.Entry<Double, String> entry : finalBottom100.entrySet() {

Double pvalue = entry.getKey();
String entireRecord = entry.getValue();
emit(pvalue, entireRecord);

}

}

24
25 }

21.6

Is Bottom 100 List A Monoid?

The question is whether our bottom100 is a monoid? If it is, then we can
provide a combiner for our bottom100 list. As we will see below, bottom100
is a commutative monoid:

534

• The bottom100 Deﬁnition:

bottom100 = MONOID(S, e, f),
where

S = {(p, w), 0 ≤ p ≤ 1, w is a unique chromosome record}
e = {} is an empty set
f = bottom100 function

• The bottom100 Commutative Property:

bottom100(a) = {(p1, w1), ..., (p100, w100) where 0 ≤ p1 ≤ ... ≤ p100 ≤ 1}
bottom100(a, b) = bottom100(a ∪ b) = bottom100(b ∪ a) = bottom100(b, a)
bottom100(a, b) = c ∈ S

• The bottom100 Identity Element Property:

Let a, b ∈ S,

then

bottom100(a, e) = a
bottom100(e, a) = a

And in mathematical notation we can write these as

(cid:88) Closure: ∀a, b ∈ S : bottom100(a, b) ∈ S

(cid:88) Associativity: ∀a, b, c ∈ S :

bottom100(a, bottom100(b, c)) = bottom100(bottom100(a, b), c))

(cid:88) Identity element: ∃e ∈ S : ∀a ∈ S : bottom100(a, e) = a = bottom100(e, a)

(cid:88) Commutative: ∀a, b ∈ S : bottom100(a, b) = bottom100(b, a)

21.6.1 Hadoop Solution for Bottom 100 List

The Java classes used in Bottom 100 List MapReduce solution are listed be-
low. In our solution, we utilized the edu.umd.cloud9.io.pair.PairOfDoubleString15

15 http://lintool.github.io/Cloud9/docs/api/edu/umd/cloud9/io/pair/PairOfDoubleString.html

(Cloud9, developed by Jimmy Lin, is a collection of Hadoop tools that tries to make
working with big data a bit easier.)

535

class to represent a Hadoop’s WritableComparable representing a pair con-
sisting of a Double and an String.

Class name
Bottom100Driver
Bottom100Mapper
Bottom100Combiner
Bottom100Reducer
HadoopUtil
PairOfDoubleString WritableComparable representing a

Description
A driver program to submit Hadoop jobs
Deﬁnes map()
Deﬁnes combine()
Deﬁnes reduce()
Deﬁnes some utility functions

pair consisting of a double and a String.

21.6.2 Sample Run of Bottom 100 List

21.6.2.1 Prepare HDFS’s Input/Output

21.6.2.2 Running the Job

21.6.2.3 Viewing Output

21.6.2.4 Sample Run for Bottom 50

21.7 MapReduce Phase-3

In Phase-2 we found the ﬁrst smallest 100 p-values among all chromosomes,
which are closest to 0.00. In Phase-3, we will ﬁnd the ﬁrst smallest 100 p-
values per chromosome, which are closest to 0.00. That is, we want to ﬁnd
the

536

• ﬁrst smallest 100 p-values for chromosome 1

• ﬁrst smallest 100 p-values for chromosome 2

• ...

• ﬁrst smallest 100 p-values for chromosome 22

• ﬁrst smallest 100 p-values for chromosome X

• ﬁrst smallest 100 p-values for chromosome Y

Therefore, we want to generate 24 outputs. The output of Phase-1 will
be used as input to Phase-3. The easiest solution is to sort (by ascending
order) the output of Phase-1 by p-value and then group by a chromosome,
and ﬁnally output the ﬁrst 100 records (this is the desired output) per chro-
mosome. Given that the output of Phase-1 may be big, sorting is not a good
option. Instead, we solve this by another MapReduce job called as Phase-3.
Using relational databases (such as Oracle or MySQL), this question can be
answerd as SQL query (assuming that allele_frequency_table is a table
which contains pvalue and <other> columns and data is loaded to this table
from the output of Phase-1): we may run this SQL query per chromosome

for (id in (1, 2, 3, ..., 21, 22, X, Y)) {

SELECT *

FROM allele_frequency_table
WHERE chromosome_id = id
ORDER BY pvalue LIMIT 100;

}

The MapReduce Phase-3 algorithm is pretty simple:

1. Mapper:

a. Each mapper finds its local bottom-100 pvalues

per chromosome and sends that bottom-100 list
to the reducer (one reducer per chromosome ---

537

total of 24 reducers).

b. We will use many mappers.

2. Reducer

a. Each reducer finds the final bottom-100 pvalues

from the bottom-100 lists sent from the mappers.

b. We will use a single reducer per chromosome for

final bottom-100.

21.7.1 Phase-3: Mapper for Bottom-100

The mappers will consume the outputs generated by allele frequency algo-
rithm. Each mapper will read (pvalue, chromosomeID, start, stop, ...) and
then emit a bottom-100 list of pvalues. Each mapper will use a bottom-100
list data structure for each chromosome. We will use the Java’s TreeMap
data structure to keep track of bottom-100 list: the bottom-100 sorted list
will be preserved by the pvalue (as a Double key) (0 ≤ pvalue ≤ 1).

1

2

3

4

5

6

7

8

Listing 21.9: Required Data Structures

import java.util.Map;
import java.util.HashMap;
import java.util.SortedMap;
import java.util.TreeMap;
...

// map<chromosomeID, treemap<pvalue, record>>
private Map<String, SortedMap<Double, String>> chromosomes =

new HashMap<String, TreeMap<Double, String>>();

We have to make sure that out bottom100 data structure just holds ”bot-
tom 100” pvalues. Here is the map() function inside Bottom100MapperPhase3
class: the map() function itself will not emit any key-value pairs, but it will
maintain and update the bottom100 data structure. When the map() is done
its function, then the cleanup() function will emit the ”bottom 100 list” per
chromosome.

538

Listing 21.10: Bottom100MapperPhase3

1 public class Bottom100MapperPhase3 ... {
2

// map<chromosomeID, treemap<pvalue, record>>
private Map<String, SortedMap<Double, String>> chromosomes =

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

new HashMap<String, TreeMap<Double, String>>();

// key is the pvalue of double type and range is 0.00 to 1.00
// value is the entire record of allelic frequency output (includes pvalue)
map(Double key, String entireRecord) {

String chromosomeID = extract(entireRecord);
SortedMap<Double, String> bottom100 = chromosomes.get(chromosomeID);
if (bottom100 == null) {

bottom100 = new TreeMap<Double, String>();

}
bottom100.put(key, value); // sort by pvalue
if (bottom100.size() > 100) {

// remove the greatest pvalue
bottom100.remove(bottom100.lastKey());

}

}

// called once at the end of the mapper task.
cleanup() {

for (Map.Entry<String, SortedMap<Double, String>>> entry : chromosomes.entrySet() {

String chromosomeID = entry.getKey();
SortedMap<Double, String> bottom100 = = entry.getValue();
for (Map.Entry<Double, String> row : bottom100.entrySet() {

Double pvalue = row.getKey();
String entireRecord = row.getValue();
String outputValue = pair(pvalue, entireRecord);
// pairs to a specific chromosome
emit(chromosomeID, outputValue);

}

}

}

34
35 }

21.7.2 Phase-3: Reducer for ”Bottom 100”

We designed ”bottom100” algorithm in such a way to have only one reducer
per chromosome to aggregate all bottom 100 lists generated by all mappers
(note that each reducer will work on bottom-100 per chromosome — as op-

539

posed to all chromosomes in Phase-2). The key for our single reducer is
chromosomeID.

The job of each Reducer is to generate the ﬁnal ”bottom 100” list from
all ”bottom 100” lists generated by all mappers (per chromosome). So, the
reducer functionality is very similar to the mappers.

Listing 21.11: Bottom100ReducerPhase3

1 public class Bottom100ReducerPhase3 ... {
2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

// key is a chromosomeID in {1, 2, ..., 22, X, Y}
reduce(String key, Iterable<pair<Double, String>> values) {

SortedMap<Double, String> finalBottom100 =

new TreeMap<Double, String>();

for (pair(Double, String) value : values) {

Double pvalue = value.pvalue;
String entireRecord = value.entireRecord;
finalBottom100.put(pvalue, entireRecord);

if (finalBottom100.size() > 100) {
// remove the greatest pvalue
finalBottom100.remove(finalBottom100.lastKey());

}

}

// now, we have the final bottom 100 list
for (Map.Entry<Double, String> entry : finalBottom100.entrySet() {

Double pvalue = entry.getKey();
String entireRecord = entry.getValue();
emit(key, (pvalue + entireRecord));

}

}

25
26 }

540

21.7.3 Hadoop Solution for Bottom 100 List Per Chro-

mosome

The Java classes used in Bottom 100 List Per Chromosome MapReduce solu-
tion are listed below. In our solution, we utilized the edu.umd.cloud9.io.pair.PairOfDoubleString16
class to represent a Hadoop’s WritableComparable representing a pair con-
sisting of a Double and an String.

Description
A driver program to submit Hadoop jobs
Deﬁnes map()

Class name
Bottom100DriverPhase3
Bottom100MapperPhase3
Bottom100CombinerPhase3 Deﬁnes combine()
Bottom100ReducerPhase3
HadoopUtil
PairOfDoubleString

Deﬁnes reduce()
Deﬁnes some utility functions
WritableComparable representing a
pair consisting of a double and a String.

21.7.4 Sample Run of Bottom 100 List Per Chromo-

some

21.7.4.1 Prepare HDFS’s Input/Output

21.7.4.2 Running the Job

21.7.4.3 Viewing Output

16 http://lintool.github.io/Cloud9/docs/api/edu/umd/cloud9/io/pair/PairOfDoubleString.html

(Cloud9, developed by Jimmy Lin, is a collection of Hadoop tools that tries to make
working with big data a bit easier.)

541

Chapter 22

The T-Test

22.1

Introduction

The T-Test (known as two-sample t-test) is used in clinical applications and
genome analysis as a statistical hypothesis test. The t-test for independent
samples compares the means of two samples. In statistics, to compare two
data sets, we convert the data to a simpler form such as means of data
and then compare the means. We can compare these two sets of data by
computing an average, or mean (µ). Since we are comapring random sample,
there is a room for a random error (usually denoted by the sample’s standard
µ2). In factoring a random error, therefore, we might be
deviation σ =
comparing µ ± σ. According to Statistics in a Nutshell1 ”The purpose of
this test (T-test) is to determine whether the means of the populations from
which the samples were drawn are the same. The subjects in the two samples
are assumed to be unrelated and to have been independently selected from
their populations.”

?

The main goal of this chapter is to provide a MapReduce/Hadoop and
Spark/Hadoop solutions for T-Test. The MapReduce algorithm presented
here is generic and can be used for any high volume of data.

In genome analysis and especially in ”somatic mutations,” they use the T-
Test for a pair of samples drawn for the same gene (identiﬁed as a GENE-ID).

1Statistics in a Nutshell, Second Edition by Sarah Boslaugh, Published by OReilly

Media, Inc., 2013

542

This is how T-Test is done: given a set of biosets/biomarkers identiﬁed by
B1, B2, ..., Bn (where each bioset has a set of ”pair of GENE-ID and GENE-
VALUE”2) and given ”survival time” identiﬁed by S1, S2, ..., Sn (note that
, Si corresponds to Bi), the goal is create two sample sets: Exist-Set and
Non-Exist-Set. Given these input, we want to create G1, G2, ..., Gm where
Gi represents a set of biosets and Gi is a GENE-ID in that bioset (Gi acts
as a reverse index to biosets).

• Exist-Set Sample: {Si|Bi ∈ Gk}
• Non-Exist-Set Sample: {Si|Bi /∈ Gk}
Then we apply ttest function to Exist-Set and Non-Exist-Set. Here is
a concrete example with 4 biosets (Bi is a GUID and Ti is primitive double
data type):

Sample Data

Biosets ID:

Survival Time: T1

B1 B2 B3 B4
T4

T2

T3

Further, assume that the biosets have the following GENE-ID and GENE-
VALUE pairs:

2We note that the number of pairs does depend on the ”bioset type”. For example, for
RNA Gene Expression data type we might have 40,000+ pairs and for Methylation data
type we might have 20,000+ pairs.

543

Bioset Data
Bioset GENE-ID GENE-VALUE

B1

B2

B3

B4

G1
G2
G3
G1
G2
G4
G1
G3
G4
G5
G6
G2
G5
G6

V11
V12
V13
V21
V22
V24
V31
V32
V33
V34
V35
V41
V42
V43

Then we will have a containment table as:

(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)(cid:88)

Time

GENE-ID
G1
G2
G3
G4
G5
G6

T1

B1
B1
B1
–
–
–

T2

B2
B2
–
B2
–
–

T3

B3
–
B3
B3
B3
B3

T4

–
B4
–
–
B4
B4

For example, the ﬁrst rwo indicates that G1 is contained in biosets {B1, B2, B3},
but not contained in {B4}. This leads us to call up the following functions:

G1: ttest({T1, T2, T3}, {T4})
G2: ttest({T1, T2, T4}, {T3})
G3: ttest({T1, T3}, {T2, T4})
G4: ttest({T2, T3}, {T1, T4})
G5: ttest({T3, T4}, {T1, T2})
G6: ttest({T3, T4}, {T1, T2})

544

For a single ttest implementation, we will use the following objects from

the Apache’s Common Math project:

• Interface: org.apache.commons.math.stat.inference.TTest

• Implementation class: org.apache.commons.math.stat.inference.TTestImpl

The implementation of ttest (used in TTestImpl class) can be described
as follows. This statistic can be used to perform a two-sample (sample1 and
sample2) t-test to compare sample means. The returned t-statisitc is

t =

(m1 − m2)
b
v2
+
n2

v1
n1

where

• n1 is the size of the ﬁrst sample (sample1)
• n2 is the size of the second sample (sample2)
• m1 is the mean of the ﬁrst sample
• m2 is the mean of the second sample
• v1 is the variance of the ﬁrst sample
• v2 is the variance of the second sample
How do we use these objects for implementation of ttest? Here is a simple

example:

Listing 22.1: TTest Implementation

1 import org.apache.commons.math.stat.inference.TTest;
2 import org.apache.commons.math.stat.inference.TTestImpl;
3 import org.apache.commons.math.MathException;
4
5 public class MathUtil {
6

/**
* @param sample1 array of sample data values
* @param sample2 array of sample data values
* @return Returns the observed significance level,
* or p-value, associated with a two-sample, two-tailed
* t-test comparing the means of the input arrays.

7

8

9

10

11

545

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

*/
public static double ttest(double[] sample1, double[] sample2) {

if ( (sample1 == null) ||
(sample2 == null) ||
(sample1.length == 0) ||
(sample2.length == 0) ) {

// return a none-existent-value
return Double.MAX_VALUE;

}

if ((sample1.length == 1) && (sample2.length == 1)) {

// return a none-existent-value
return Double.MAX_VALUE;

}
return calculateTtest(sample1, sample2);

}

private static double calculateTtest(double[] sample1, double[] sample2) {

...

}

31
32 }

Implementation of calculateTtest() method is given below:

Listing 22.2: The calculateTtest() Method

1 /**
2

3

4

* @param sample1 array of sample data values
* @param sample2 array of sample data values
* @return Returns p-value, associated with sample1 and sample2
*/

5
6 private static double calculateTtest(double[] sample1, double[] sample2) {
7

double pvalue = 0.0d;
TTest ttest = new TTestImpl();
try {

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25
26 }

if (sample1.length == 1) {

pvalue = ttest.tTest(sample1[0], sample2);

}
else if (sample2.length == 1) {

pvalue = ttest.tTest(sample2[0], sample1);

}
else {

}

pvalue = ttest.tTest(sample1, sample2);

}
catch(MathException me) {

System.out.println("ttest() failed. +", me.getMessage());
pvalue = 0.0d;

}

return pvalue;

546

22.2 MapReduce Problem Statement

Given a set of biosets3 with data in the millions and tens of millions, and
where a bioset may have up to 40,000 to 100,000 genes, we want to apply
T-Test (ttest) function to each gene for all biosets. Typically, in genome
analysis, the T-Test is applied to ”gene expression,” ”methylation,” ”so-
matic mutation,” and ”copy number variation” bioset data types. This kind
of analysis involves reading and processing hundreds of millions of records.
For example, to process 200,000 biosets (the normal number of biosets in
patient centric applications) with each having 50,000 unique GENE-IDs, the
MapReduce solution has to handle 10 billion (10,000,000,000) records (this
volume of data and ttest processing cannot be handled by a single server).

22.3

Input

Our input for T-Test has two parts (Bi corresponds to Si):

• List of biosets: B1, B2, ..., Bn
• Survival time for these biosets: S1, S2, ..., Sn
Each record of a bioset will have the following format:

format:

<geneID><,><biosetID><,><geneValue>

example-1:

7562135,778800,1.04

example-2:

7570769,778800,-1.09

The bioset ﬁles persists in HDFS and will be read by MapReduce frame-
work (during the map() execution). How will we pass these two additional
dynamic parameters (”list of bioset IDs”, and ”survival time for biosets”)

3For details on biosets, please refer to Appendix A

547

from MapReduce driver to map() and reduce() functions. Using MapRe-
duce/Hadoop Configuration object, we can set these values by Configurtion.set()
and retrieve them (by Configurtion.get()) in the setup() function of
map() or reduce(). An alternative method is to use Hadoop’s DistributedCache4
class, which can distribute application-speciﬁc large, read-only ﬁles eﬃciently.

22.4 Expected Output

For each GENE-ID (contained in all of biosets), we do need to generate:

format:

<geneID><,><RESULT-of-TTEST-FUNCTION>

where <RESULT-of-TTEST-FUNCTION> is a p-value

22.5 MapReduce Solution

The goal of MapReduce solution is to apply ttest to all genes contained in
these biosets. The mapper gets <geneID><,><biosetID><,><geneValue>
and emits a (key, value) pair, where key is the GENE-ID and value is the
BIOSET-ID. The reducer function’s job is to create two lists (EXIST and
NON-EXIST) and to then apply ttest to these two lists.

The map() function is a simple function, which emits pairs of (geneID,
biosetID).

Listing 22.3: Mapper for T-Test

1 /**
2

* @param key is generated by MapReduce framework, ignored here
* @paran value as a String has the the following format:
*
<geneID><,><biosetID><,><geneValue>
* Note that <geneValue> is not used in T-Test.
*/

3

4

5

6

4The full name is org.apache.hadoop.filecache.DistributedCache. Distributed-
Cache is a class provided by the Hadoop’s MapReduce framework to cache ﬁles needed by
applications.

548

7 map(key, value) {
8

String[] tokens = value.split(",");
String geneID = tokens[0];
String biosetID = tokens[1];
emit(geneID, biosetID);

9

10

11
12 }

The main function of a reducer is to create a reverse index genes based
on bioset-IDs and ﬁnally apply the T-Test algorithm to two sets: EXIST
and NON-EXIST. The reduce() function does T-Test implementation and
preserves the order of bioset IDs with survival time.

Listing 22.4: Reducer for T-Test

1 public class TtestReducer {
2

// instance variables
private Configuration conf = null;
// biosetIDs as Strings : NOTE oreder of biosets are VERY IMPORTANT
public List<String> biosets = null;
// survival time : NOTE oreder of time items are VERY IMPORTANT
public List<Double> time = null;

// will be run only once
public void setup(Context context) {
this.conf = context.getConfiguration();

// get parameters from Hadoop’s configuration
String biosetsAsString = conf.get("biosets");
this.biosets = DataStructuresUtil.splitOnToListOfString(biosetsAsString, ",");

String timeAsCommaSeparatedString = conf.get("time");
this.time = DataStructuresUtil.toListOfDouble(timeAsCommaSeparatedString);

// key = geneID
// values = list of { biosetID }
public void reduce(Text key, Iterable<Text> values)

{

// solution is given next

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 }

}

}

The reduce() function for T-Test is presented below:

Listing 22.5: reduce() function for T-Test

1 // key = geneID
2 // values = list of { biosetID }
3 public void reduce(Text key, Iterable<Text> values)

{

549

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 }

Iterator<Text> iter = values.iterator();
List<Double> exist = new ArrayList<Double>();
List<Double> notexist = new ArrayList<Double>();
List<String> genebiosets = new ArrayList<String>();
while (iter.hasNext()) {

String biosetID = iter.next();
genebiosets.add(biosetID);

}

for (int i=0; i < biosets.size(); i++) {

// check to to see if this biosetID does exist in genes
int index = genebiosets.indexOf(biosets.get(i));
if (index == -1) {

// biosetID not found
notexist.add(time.get(i));

// biosetID found
exist.add(time.get(i));

}
else {

}

}

if (exist.isEmpty()) {

// no need to include it
return;

}

if (notexist.isEmpty()) {

// no need to include it
return;

}

(exist.size() > 0) && (notexist.size() > 0)

//
// here we have:
//
//
// prepare final value(s) for reducer
//
double pvalue = MathUtil.ttest(exist, notexist);
emit(key, pvalue);

// calls ttest()

22.6 Hadoop Implementation

This section implements a MapReduce solution for T-Test using Hadoop.
Our Hadoop solution is comprised of the following Java classes:

550

Class Name
TtestDriver.java
TtestMapper.java
TtestReducer.java Deﬁnes the reduce() function
TtestAnalyzer.java Reads output data generated by reducers

Description
The driver class for submitting MapReduce jobs
Deﬁnes the map() function

22.7 Spark Implementation

This section implements a MapReduce solution for T-Test using Spark. The
Spark soultion is a single driver Java class using RDDs. Three types of input
are involved for T-Test:

• List of bioset IDs as {B1, B2, ..., Bn}, where n > 0 and each Bi is a

bioset ID

• List of survival time as {T1, T2, ..., Tn}, where each Ti is a double data

type. Each Bi corrsponds to Ti.

• List of n ﬁles (one ﬁle per bioset): {B1.txt, B2.txt, ..., Bn.txt}.
Each record of bioset ﬁles has the following format (note that for ttest,
geneValue will not be used):

<geneID><,><biosetID><,><geneValue>

Since each Bi corrsponds to Ti, we will combine these two data into a
single ﬁle, called timetable.txt where each record will have two columns:
<bioset_id> followed by <survival_time>. Therefore, we assume the fol-
lowing input ﬁles:

/<hdfs-directory>/timetable/timetable.txt
/<hdfs-directory>/biosets/bioset_1.txt
/<hdfs-directory>/biosets/bioset_2.txt
/<hdfs-directory>/biosets/bioset_3.txt
...
/<hdfs-directory>/biosets/bioset_n.txt

551

Figure 22.1: Ttest Spark WorkFlow

552

Using these input ﬁles, Ttest Spark workﬂow is presented below:

The high-level implementation of workﬂow in Spark is presented below:

STEP-1 : Concatenate all bioset ﬁles (B1.txt, B2.txt, ..., Bn.txt) and
create a JavaRDD<String>, where each item (as a String object) of
this RDD will be as:

<geneID><,><biosetID><,><geneValue>

STEP-2 : Map JavaRDD<String> into JavaRDD<String, Iterable<String>>,

where key (as a String) is a gene-id and value is a list of biosets.

STEP-3 : Read timetable data (as pairs of (biosetID, survival-time)) and
reduce JavaRDD<String, Iterable<String>> using T-test algorithm
into a ﬁnal JavaRDD<String, Double> where key (as a String) is a
gene-id and value is a p-value (output of ttest algorithm).

STEP-4 : Save the ﬁnal JavaPairRDD in HDFS.

22.7.1 High Level Steps

Listing 22.6: Spark Solution: High Level Steps

1 // STEP-0: import required classes and interfaces
2 public class SparkTtest {
3

static JavaSparkContext createJavaSparkContext() {...}
static Map<String, Double> createTimeTable(String filename) {...}
static JavaRDD<String> readBiosetFiles(JavaSparkContext ctx, String biosetFiles) {...}

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

public static void main(String[] args) throws Exception {

// STEP-1: handle input parameters
// STEP-2: Create time table data structure
// STEP-3: create a spark context object
// STEP-4: broadcast shard variables
// STEP-5: create RDD for all biosets
// each RDD element has: <geneID><,><biosetID><,><geneValue>
// STEP-6: map bioset records into JavaPairRDD(K,V) pairs
// where K = <GeneID>, V = <Bioeset-ID>
// STEP-7: group biosets by GENE-ID
// now, for each GENE-ID we have a List<BIOSET-ID>
// STEP-8: perform Ttest for every GENE-ID

used by all cluster nodes

553

System.exit(0);

19

20
21 }

}

22.7.2 STEP-0: import required classes and interfaces

Listing 22.7: Spark Solution: High Level Steps

1 // STEP-0: import required classes and interfaces
2 import scala.Tuple2;
3 import org.apache.spark.api.java.JavaRDD;
4 import org.apache.spark.api.java.JavaPairRDD;
5 import org.apache.spark.api.java.JavaSparkContext;
6 import org.apache.spark.api.java.function.Function;
7 import org.apache.spark.api.java.function.PairFunction;
8 import org.apache.commons.lang.StringUtils;
9 import org.apache.spark.broadcast.Broadcast;
10 import org.apache.spark.SparkConf;
11
12 import java.util.Map;
13 import java.util.HashMap;
14 import java.util.Set;
15 import java.util.HashSet;
16 import java.util.List;
17 import java.util.ArrayList;
18 import java.io.FileReader;
19 import java.io.BufferedReader;

22.7.3 Create JavaSparkContext

Listing 22.8: Spark Solution: High Level Steps

1

2

3

4

5

6

7

8

9

10

11

12

static JavaSparkContext createJavaSparkContext() throws Exception {

SparkConf conf = new SparkConf();
conf.set("yarn.resourcemanager.hostname", "hnode01319.nextbiosystem.net");
conf.set("yarn.resourcemanager.scheduler.address", "hnode01319.nextbiosystem.net:8030");
conf.set("yarn.resourcemanager.resource-tracker.address", "hnode01319.nextbiosystem.net:8031");
conf.set("yarn.resourcemanager.address",
conf.set("mapreduce.framework.name", "yarn");
conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
conf.set("spark.executor.memory", "7g");
JavaSparkContext ctx = new JavaSparkContext("yarn-cluster", "SparkTtest", conf);
return ctx;

"hnode01319.nextbiosystem.net:8032");

}

554

22.7.4 Create TimeTable Data Structure

Listing 22.9: Spark Solution: High Level Steps

static Map<String, Double> createTimeTable(String filename) throws Exception {

Map<String, Double> map = new HashMap<String, Double>();
BufferedReader in = null;
try {

in = new BufferedReader(new FileReader(filename));
String line = null;
while ((line = in.readLine()) != null) {

String value = line.trim();
String[] tokens = value.split("\t");
String biosetID = tokens[0];
Double time = new Double(tokens[1]);
map.put(biosetID, time);

}
System.out.println("createTimeTable() map="+map);

}
finally {

if (in != null) {

in.close();

}

}
return map;

}

22.7.5 Create RDD for All Biosets

Listing 22.10: Spark Solution: High Level Steps

static JavaRDD<String> readBiosetFiles(JavaSparkContext ctx,

String biosetFiles)

throws Exception {
StringBuilder unionPath = new StringBuilder();
BufferedReader in = null;
try {

in = new BufferedReader(new FileReader(biosetFiles));
String singleBiosetFile = null;
while ((singleBiosetFile = in.readLine()) != null) {

singleBiosetFile = singleBiosetFile.trim();
unionPath.append(singleBiosetFile);
unionPath.append(",");

}
//System.out.println("readBiosetFiles() unionPath="+unionPath);

}
finally {

if (in != null) {

in.close();

555

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

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

1

2

3

4

5

6

7

8

9

1

2

1

2

}

}
// remove the last comma ","
String unionPathAsString = unionPath.toString();
unionPathAsString = unionPathAsString.substring(0, unionPathAsString.length()-1);
// create RDD
JavaRDD<String> allBiosets = ctx.textFile(unionPathAsString);
JavaRDD<String> partitioned = allBiosets.coalesce(14);
return partitioned;

}

22.7.6 STEP-1: handle input parameters

Listing 22.11: Spark Solution: High Level Steps

// STEP-1: handle input parameters
if (args.length != 2) {

System.err.println("Usage: SparkTtest <timetable-file> <bioset-file>");
System.exit(1);

}
String timetableFileName = args[0];
System.out.println("<timetable-file>="+timetableFileName);
String biosetFileNames = args[1];
System.out.println("<bioset-file>="+biosetFileNames);

22.7.7 Create time table data structure

Listing 22.12: Spark Solution: High Level Steps

// STEP-2: Create time table data structure
Map<String, Double> timetable = createTimeTable(timetableFileName);

22.7.8 STEP-3: create a spark context object

Listing 22.13: Spark Solution: High Level Steps

// STEP-3: create a spark context object
JavaSparkContext ctx =

createJavaSparkContext();

556

1

2

3

4

1

2

3

4

1

2

3

4

5

6

7

8

9

10

11

12

13

14

22.7.9 High Level Steps

Listing 22.14: Spark Solution: High Level Steps

// STEP-4: broadcast shard variables
// we need this shared data structure when we want to find
// "existSet" and notExistSet" sets after grouping data by GENE-ID.
final Broadcast<Map<String, Double>> broadcastTimeTable = ctx.broadcast(timetable);

used by all cluster nodes

22.7.10 STEP-5: create RDD for all biosets

Listing 22.15: Spark Solution: High Level Steps

// STEP-5: create RDD for all biosets
// each RDD element has: <geneID><,><biosetID><,><geneValue>
JavaRDD<String> biosets = readBiosetFiles(ctx, biosetFileNames);
biosets.saveAsTextFile("/ttest/output/1");

22.7.11 STEP-6: map bioset records into JavaPair-

RDD(K,V) pairs

Listing 22.16: Spark Solution: High Level Steps

// STEP-6: map bioset records into JavaPairRDD(K,V) pairs
// where K = <GeneID>
//
// Note that for TTest, <geneValue> is not used (ignored here)
//
JavaPairRDD<String, String> pairs = biosets.mapToPair(new PairFunction<String, String, String>() {

V = <Bioeset-ID>

K

V

T

public Tuple2<String, String> call(String biosetRecord) {

String[] tokens = StringUtils.split(biosetRecord, ",");
String geneID = tokens[0];
// K
String biosetID = tokens[1]; // V
return new Tuple2<String,String>(geneID, biosetID);

}

});
pairs.saveAsTextFile("/ttest/output/2");

22.7.12 STEP-7: group biosets by GENE-ID

557

1

2

3

4

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

Listing 22.17: Spark Solution: High Level Steps

// STEP-7: group biosets by GENE-ID
JavaPairRDD<String, Iterable<String>> grouped = pairs.groupByKey();
// now, for each GENE-ID we have a List<BIOSET-ID>
grouped.saveAsTextFile("/ttest/output/3");

22.7.13 STEP-8: perform Ttest for every GENE-ID

Listing 22.18: Spark Solution: High Level Steps

// STEP-8: perform Ttest for every GENE-ID
// mapValues[U](f: (V) => U): JavaPairRDD[K, U]
// Pass each value in the key-value pair RDD through a map function without
// changing the keys; this also retains the original RDD’s partitioning.
JavaPairRDD<String, Double> ttest = grouped.mapValues(

new Function<Iterable<String>, // input

Double

// output (result of ttest)

>() {
public Double call(Iterable<String> biosets) {

Set<String> geneBiosets = new HashSet<String>();
for (String biosetID : biosets) {
geneBiosets.add(biosetID);

}

// now we do need shared Map data structure to iterate over its items
Map<String, Double> timetable = broadcastTimeTable.value();
// the following two lists are needed for ttest(exist, notexist)
List<Double> exist = new ArrayList<Double>();
List<Double> notexist = new ArrayList<Double>();
for (Map.Entry<String, Double> entry : timetable.entrySet()) {

String biosetID = entry.getKey();
Double time = entry.getValue();
if (geneBiosets.contains(biosetID)) {

exist.add(time);

}
else {

notexist.add(time);

}

}

// perform the ttest(exist, notexist)
double ttest = MathUtil.ttest(exist, notexist);
return ttest;

}

});

ttest.saveAsTextFile("/ttest/output/4");

558

22.7.14 Ttest Algorithm

Listing 22.19: Spark Solution: High Level Steps

public static double ttest(List<Double> groupA, List<Double> groupB) {

if ((groupA.size() == 1) && (groupB.size() == 1)) {

public static double ttest(double[] arrA, double[] arrB) {

if ((arrA.length == 1) && (arrB.length == 1)) {

// return a NULL value for score (does not make sense)
return Double.NaN;

score = ttest.tTest(arrA[0], arrB);

score = ttest.tTest(arrB[0], arrA);

score = ttest.tTest(arrA, arrB);

private static final TTest ttest = new TTestImpl();

}

}

}

}
else {

if (arrA.length == 1) {

}
return score;

e.printStackTrace();
score = Double.NaN;

}
catch(Exception e) {

double score = Double.NaN;
try {

}
else if (arrB.length == 1) {

1 import java.util.List;
2 import java.util.ArrayList;
3 import org.apache.commons.math.stat.inference.TTest;
4 import org.apache.commons.math.stat.inference.TTestImpl;
5
6 public class MathUtil {
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

}
else if (groupB.size() == 1) {

double score;
if (groupA.size() == 1) {

}
catch(Exception e) {

e.printStackTrace();
return Double.NaN;

score = tTest(groupA, groupB);

}
return score;

return Double.NaN;

}
else {

try {

try {

}

}

}

}

}

double[] arr = listToArray(group);
return ttest.tTest(d, arr);

double[] arrA = listToArray(groupA);
double[] arrB = listToArray(groupB);
return ttest.tTest(arrA, arrB);

score = tTest(groupB.get(0), groupA);

score = tTest(groupA.get(0), groupB);

private static double tTest(double d, List<Double> group) {

559

private static double tTest(List<Double> groupA, List<Double> groupB) {

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87 }

catch(Exception e) {

e.printStackTrace();
return 0.0d;

}

}

static double[] listToArray(List<Double> list) {

if ( (list == null) || (list.isEmpty()) ) {

return null;

}

double[] arr = new double[list.size()];
for (int i=0; i < arr.length; i++) {
arr[i] = list.get(i);

}
return arr;

}

22.7.15

Input for Spark Program

# cat ttestinput/timetable.txt
b1
b2
b3
b4

0.9
0.75
0.5
1.1

# cat ttestinput/biosets.txt
/ttest/input/b1.txt
/ttest/input/b2.txt
/ttest/input/b3.txt
/ttest/input/b4.txt

# hadoop fs -ls /ttest/input/
Found 4 items
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--

3 hadoop root,hadoop
3 hadoop root,hadoop
3 hadoop root,hadoop
3 hadoop root,hadoop

52 2014-07-06 22:10 /ttest/input/b1.txt
33 2014-07-06 22:10 /ttest/input/b2.txt
31 2014-07-06 22:10 /ttest/input/b3.txt
31 2014-07-06 22:10 /ttest/input/b4.txt

# hadoop fs -cat /ttest/input/b1.txt
G1,b1,1.0
G2,b1,0.6
G3,b1,0.09
G4,b1,2.2
G5,b1,1.03

# hadoop fs -cat /ttest/input/b2.txt
G1,b2,2.09
G2,b2,1.07
G3,b2,1.00

# hadoop fs -cat /ttest/input/b3.txt
G2,b3,2.9
G3,b3,1.03
G5,b3,2.9

# hadoop fs -cat /ttest/input/b4.txt
G1,b4,2.9
G2,b4,1.8
G4,b4,1.05

22.7.16 Spark on YARN Script

560

# cat ./run_ttest.sh
#!/bin/bash
/bin/date
source /home/hadoop/conf/env_2.4.0.sh
export HADOOP_HOME=/usr/local/hadoop/hadoop-2.4.0
export SPARK_HOME=/home/hadoop/spark-1.0.0
source /home/hadoop/spark_mahmoud_examples/spark_env_yarn.sh
source $SPARK_HOME/conf/spark-env.sh

# system jars:
CLASSPATH=$CLASSPATH:$HADOOP_HOME/etc/hadoop
#
jars=‘find $SPARK_HOME -name ’*.jar’‘
for j in $jars ; do

CLASSPATH=$CLASSPATH:$j

done

# app jar:
export MP=/home/hadoop/spark_mahmoud_examples
export CLASSPATH=$MP/mp.jar:$CLASSPATH
export CLASSPATH=$MP/commons-math3-3.0.jar:$CLASSPATH
export CLASSPATH=$MP/commons-math-2.2.jar:$CLASSPATH
export SPARK_CLASSPATH=$CLASSPATH
export SPARK_LIBRARY_PATH=$HADOOP_HOME/lib/native
export JAVA_HOME=/usr/java/jdk7
export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop
export YARN_CONF_DIR=$HADOOP_HOME/etc/hadoop
export MY_JAR=$MP/mp.jar
export SPARK_JAR=$MP/spark-assembly-1.0.0-hadoop2.4.0.jar
export YARN_APPLICATION_CLASSPATH=$CLASSPATH:$HADOOP_HOME/etc/hadoop
export THEJARS=$MP/commons-math-2.2.jar,$MP/commons-math3-3.0.jar
$SPARK_HOME/bin/spark-submit --clas SparkTtest \

--master yarn-cluster \
--num-executors 12 \
--driver-memory 3g \
--executor-memory 7g \
--executor-cores 12 \
--jars $THEJARS \
$MY_JAR $MP/ttestinput/timetable.txt $MP/ttestinput/biosets.txt

22.7.17 Sample Run of Script

# ./run_ttest.sh
<timetable-file>=/home/hadoop/spark_mahmoud_examples/ttestinput/timetable.txt
<bioset-file>=/home/hadoop/spark_mahmoud_examples/ttestinput/biosets.txt
createTimeTable() map={b1=0.9, b3=0.5, b2=0.75, b4=1.1}
...
14/07/06 22:26:13 INFO yarn.Client: Uploading file:/home/hadoop/spark_mahmoud_examples/mp.jar to

hdfs://myserver100:8020/user/hadoop/.sparkStaging/application_1403538869175_0253/mp.jar

14/07/06 22:26:14 INFO yarn.Client: Uploading file:/home/hadoop/spark_mahmoud_examples/spark-assembly-1.0.0-hadoop2.4.0.jar
to hdfs://myserver100:8020/user/hadoop/.sparkStaging/application_1403538869175_0253/spark-assembly-1.0.0-hadoop2.4.0.jar

...
14/07/06 22:26:16 INFO impl.YarnClientImpl: Submitted application application_1403538869175_0253
...

appTrackingUrl: http://myserver100:8088/proxy/application_1403538869175_0253/

...

22.7.18 Generated Outputs

22.7.18.1 Outputs for Debugging

561

# hadoop fs -cat /ttest/output/1/part*
G1,b1,1.0
G2,b1,0.6
G3,b1,0.09
G4,b1,2.2
G5,b1,1.03
G1,b4,2.9
G2,b4,1.8
G4,b4,1.05
G1,b2,2.09
G2,b2,1.07
G3,b2,1.00
G2,b3,2.9
G3,b3,1.03
G5,b3,2.9

# hadoop fs -cat /ttest/output/2/part*
(G1,b1)
(G2,b1)
(G3,b1)
(G4,b1)
(G5,b1)
(G1,b4)
(G2,b4)
(G4,b4)
(G1,b2)
(G2,b2)
(G3,b2)
(G2,b3)
(G3,b3)
(G5,b3)

# hadoop fs -cat /ttest/output/3/part*
(G3,[b3, b1, b2])
(G4,[b1, b4])
(G5,[b1, b3])
(G1,[b1, b4, b2])
(G2,[b1, b4, b2, b3])

22.7.18.2 Final Output

# hadoop fs -cat /ttest/output/4/part*
(G3,0.08146847659449757)
(G4,0.14994028688738084)
(G5,0.48769401782708255)
(G1,0.05441315690970782)
(G2,0.0)

562

Chapter 23

Computing Pearson Correlation

What is Pearson Correlation? The Pearson Correlation measures how well
two sets of data are related (linear relationship). The common measure of
correlation in Math. and Statistics is the Pearson Correlation. In a nutshell,
Pearson Correlation answers this question: is it possible to draw a line graph
to represent the data? According to onlinestatbook 1: ”the Pearson product-
moment correlation coeﬃcient is a measure of the strength of the linear
relationship between two variables. It is referred to as Pearson’s correlation or
simply as the correlation coeﬃcient. If the relationship between the variables
is not linear, then the correlation coeﬃcient does not adequately represent
the strength of the relationship between the variables.”

The goal of this chapter is to provide two MapReduce solutions for Pear-

son2 Correlation:

• Pearson Correlation using MapReduce/Hadoop: this will be a simple

case using classical MapReduce/Hadoop

• Pearson Correlation using Spark/Hadoop: this will coorelate ”all-vs-

all” using Java/Spark/Hadoop.

The algorithms presented for Pearson correlations can be easily adapted
to Spearman ranked correlations. To perform Spearman ranked correlation,
I have provided a Java wrapper class called Spearman.java.

1 http://onlinestatbook.com/chapter4/pearson.html
2Karl Pearson (27 March 1857 27 April 1936) was an English mathematician who has
been credited with establishing the discipline of mathematical statistics. For details on
undestanding Pearson Correlation , see http://en.wikipedia.org/wiki/Karl_Pearson

563

By end of this chapter you will be able to replace Pearson correlation with
Spearman’s3 ranked correlation algorithm.

23.1 Pearson Correlation Formula

Formula for Pearson Correlation can be written in many diﬀerent equivalent
forms. Let x = (x1, x2, ..., xn) and y = (y1, y2, ..., yn), then Pearson Corre-
lation for x and y can be expressed as:

r =

b

Σ(xi − ¯x)(yi − ¯y)
Σ(xi − ¯x)2Σ(yi − ¯y)2

r =

c

where

ΣxΣy
n

Σxy −
(Σx)2

(Σx2 −

n )(Σy2 −

(Σy)2
n )

¯x =

¯y =

Σx
n

Σy
n

Pearson Correlation has the following properties:

• Range: −1 ≤ r ≤ 1

• Correlation coeﬃcient is a unitless index of strength of association be-

tween two variables:

r > 0 means positive association

r < 0 means negative association

r = 0 means no association

• Measures the linear relationship between x and y

3http://en.wikipedia.org/wiki/Spearman’s_rank_correlation_coefficient

564

Figure 23.1: Positive Correlation

Given two sets of data, what are the possible values for the Pearson correla-
tion? The results will be between -1.00 and 1.00. The values can be classiﬁed
as:

• No correlation: close to 0.00

• High/Positive correlation: 0.6 to 1.0 or -0.6 to 1.0

• Medium correlation: 0.3 to 0.6 or -0.3 to 0.6

• Low/Negative correlation: 0.1 to 0.3 or -0.1 to -0.3

The following images shows the meaning of positive, negative, and no

correlations.

565

Figure 23.2: Negative Correlation

566

Positive Correlation

Negative Correlation

No Correlation

567

02468100246810No Correlationx axisy axis23.2 Pearson Correlation by Example

Below are the data for seven participants giving their number of years in col-
lege (x) and their subsequent yearly income (y). Income here is in thousands
of dollars, but this fact does not require any changes in our computations.

Participant x
0
Alex
1
Mary
3
Jane
4
John
4
Rafa
6
Roger
7
Ken
Σx = 18 Σy = 140 Σx2 = 78 Σy2 = 3600 Σxy = 505

xy
0
15
60
100
120
210
210

y
15
18
20
25
30
35
40

y2
225
225
400
625
900
1225
1225

x2
0
0
9
16
16
36
36

Plugging the values into the Pearson Correlation will result in r = 0.95.

23.3 Data Set for Pearson Correlation

We want to process a generalized data set as a matrix (in CSV format),
where the columns correspond to variables (such as x, y, z, ...) and rows
correspond to instances. The sample data might look like the following:

ROW-1: 1, 1, 3, -1
ROW-2: 2, 2, 1, -2
ROW-3: 3, 3, 8, -3
...

23.4 POJO Solution for Pearson Correlation

Let data be a 2-dimensional array of doubles, then we can write:

Listing 23.1: Computing Pairwise Correlations

569

Figure 23.3: No Correlation

570

1 public void computeAllPairwiseCorrelations(double[][] data) {
2

int numColumns = data[0].length;
for(int i=0; i < numColumns; i++) {

for(int j=i+1; j < numColumns; j++) {

//compute the correlation between the i-th and j-th columns/variables
double correlation = computeCorrelation(i, j, data);
System.out.println("i="+i+" j="+j+" correlation="+correlation);

}

}

9
10 }

The Java method to compute the pairwise Pearson correlation might look

like the following.

Listing 23.2: Computing Pearson Correlation

1 public double computePearsonCorrelation(int i, int j, double[][] data) {
2

double x = 0;
double y = 0;
double xx = 0;
double yy = 0;
double xy = 0;
double n = data.length;
for(int row=0; row < data.length; row++) {

x += data[row][i];
y += data[row][j];
xx += Math.pow(data[row][i], 2.0d);
yy += Math.pow(data[row][j], 2.0d);
xy += data[row][i] * data[row][j];

}
double numerator = xy - ((x * y) / n);
double denominator1 = xx - (Math.pow(x, 2.0d) / n);
double denominator2 = yy - (Math.pow(y, 2.0d) / n);
double denominator = Math.sqrt(xx * yy);
double correlation = numerator / denominator;
return correlation;

3

4

5

6

7

8

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20
21 }

Test Drive POJO Solution

To test drive Pearson correlation, a small sample is used to show how it is
done:

Listing 23.3: Test Drive Pearson Correlation

571

1 public class PearsonCorrelation {
2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

public void computeAllPairwiseCorrelations(double[][] data) {

...

}

public double computeCorrelation(int i, int j, double[][] data) {

...

}

public static void main(String[] args) throws Exception {

double[][] matrix = new double[][] {

{1, 1, 3, -1},
{2, 2, 1, -2},
{3, 3, 8, -3}

};
PearsonCorrelation pc = new PearsonCorrelation();
pc.computeAllPairwiseCorrelations(matrix);
System.exit(0);

}

20
21 }

Sample run is provided below::

$ javac PearsonCorrelation.java
$ java PearsonCorrelation
i=0 j=1 correlation=0.14285714285714285
i=0 j=2 correlation=0.15534244150030002
i=0 j=3 correlation=-0.14285714285714285
i=1 j=2 correlation=0.15534244150030002
i=1 j=3 correlation=-0.14285714285714285
i=2 j=3 correlation=-0.15534244150030002

From this output we can conclude that our MapReduce solution has to

generate six unique reducer keys.

23.5 MapReduce Solution for Pearson Cor-

relation

For MapReduce solution, we will focus on map() and reduce()functions.

572

23.5.1 map() for Pearson Correlation

Listing 23.4: Mapper for Pearson Correlation

1 /**
2

3

* key is MapReduce generated, ignored here
* value is one row of the matrix
*/

4
5 map(key, value) {
6

double[] arr = line.split(",");
int size = arr.length;
for(int i=0; i < size -1; i++) {

for(int j=i+1; j < size; j++) {

reducerKey = PairOfLongs(i, j);
reducerValue = PairOfDoubles(arr[i], arr[j]);
emit(reducerKey, reducerValue);

}

7

8

9

10

11

12

13

}

14
15 }

Now let’s see what each map() function will generate:

map(ROW-1): will generate:

K2=(0,1) and V2=(1,1)
K2=(0,2) and V2=(1,3)
K2=(0,3) and V2=(1,-1)
K2=(1,2) and V2=(1,3)
K2=(1,3) and V2=(1,-1)
K2=(2,3) and V2=(3,-1)

map(ROW-2): will generate:

K2=(0,1) and V2=(2,2)
K2=(0,2) and V2=(2,1)
K2=(0,3) and V2=(2,-2)
K2=(1,2) and V2=(2,1)
K2=(1,3) and V2=(1,-2)
K2=(2,3) and V2=(1,-2)

map(ROW-3): will generate:

K2=(0,1) and V2=(3,3)
K2=(0,2) and V2=(3,8)
K2=(0,3) and V2=(3,-3)

573

K2=(1,2) and V2=(3,8)
K2=(1,3) and V2=(3,-3)
K2=(2,3) and V2=(8,-3)

23.5.2 reduce() for Pearson Correlation

Six unique keys are generated for reducers:

K2=(0,1) and List_of_V2=[(1,1), (2,2), (3,3)]
K2=(0,2) and List_of_V2=[(1,3), (2,1), (3,8)]
K2=(0,3) and List_of_V2=[(1,-1), (2,-2), (3,-3)]
K2=(1,2) and List_of_V2=[(1,3), (2,1), (3,8)]
K2=(1,3) and List_of_V2=[(1,-1), (1,-2), (3,-3)]
K2=(2,3) and List_of_V2=[(3,-1), (1,-2), (8,-3)]

23.5.3 reduce() for Pearson Correlation

Listing 23.5: Reducer for Pearson Correlation

1 reduce(PairOfLongs key, Iterable<PairOfDoubles> values) {
2

double x = 0.0d;
double y = 0.0d;
double xx = 0.0d;
double yy = 0.0d;
double xy = 0.0d;
double n = 0.0d;

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19
20 }

for(PairOfDoubles pair : values) {
x += pair.getLeftElement();
y += pair.getRightElement();
xx += Math.pow(pair.getLeftElement(), 2.0d);
yy += Math.pow(pair.getRightElement(), 2.0d);
xy += (pair.getLeftElement() * pair.getRightElement());
n += 1.0d;

}

PearsonComputation pearson = new PearsonComputation(x, y, xx, yy, xy, n);
emit(key, pearson);

574

23.6 Hadoop Implementation for Pearson Cor-

relation

For Hadoop implementation, we will provide a driver, map(), reduce(),
and some custom data structures and classes to hold intermediate values for
Pearson Correlation.

Description
A driver program to submit Hadoop jobs
Deﬁnes map()

Class name
PearsonCorrelationDriver
PearsonCorrelationMapper
PearsonCorrelationReducer Deﬁnes reduce()
PearsonCorrelation
HadoopUtil
TestDataGeneration
PairOfWritables<L,R>

Implements Pearson correlation algorithm
Deﬁnes some utility functions
Generates test data for Pearson correlation
edu.umd.cloud9.io.pair.PairOfWritables<L,R>

In our Hadoop implementation, we use a PairOfWritables<L,R> class,
which can be instantited to generate PairOfWritables<Long,Long> and
PairOfWritables<Double,Double>. The deﬁnition of PairOfWritables (a
class representing pair of Writables) is given below:

Listing 23.6: PairOfWritables Class

1 package edu.umd.cloud9.io.pair;
2
3 import java.io.DataInput;
4 import java.io.DataOutput;
5 import java.io.IOException;
6 import org.apache.hadoop.io.Writable;
7
8 public class PairOfWritables<L extends Writable,
R extends Writable>
9

implements Writable {

private L leftElement;
private R rightElement;
...

10

11

12

13

14
15 }

We use PairOfWritables.getLeftElement() and PairOfWritables.getRightElement()

to retrieve leftElement and rightElement respectively.

575

23.7 Pearson Correlation using Spark/Hadoop

This goal of this section is to correlate ”all-vs-all”. What does this mean?
Let’s deﬁne a speciﬁc problem case and then explain correlation of ”all-vs-
all”. Note that you may easily adapt the algorithm presented here to your
speciﬁc input data. For sure input data formats will be diﬀerent per diﬀerent
application domains. Let P = {P1, P2, ..., Pn} be a set of patients (each
patient is identiﬁed by a Patient-ID). Let each patient to have a ﬁnite set
of biomarker data, which has the following format:

<Gene-ID><,><Reference><,><Patient-ID><,><Biomarker-Value-As-Double-Data-Type>

where Reference = {

r1, // normal
r2, // disease
r3
r4

// paired
// unknown

}

To achieve correct results of correlation, only one type of ”reference” is used
(the reference will be used as a ﬁlter). For example, two sample biomarker
rows might look like:

G1234,r3,P100,0.04
G1345,r1,P200,0.90
G2155,r2,P200,0.86

Let G = {G1, G2, ..., Gm} be a set of genes (expresses as Gene-IDs). For
example for RNA-Expression data type the number of unique genes might
be about 40,000. Then the correlation of all-vs-all will generate

40, 000 × 40, 000 = 1600, 000, 000

Pearson correlations. But since correlation of (Gi, Gj) is the same as (Gj,
Gi), then this calculation can be reduced to (where N = 40, 000).

N × (N − 1)
2

576

Threfore, for example, if G = {G1, G2, G3, G4, G5}, then we will generate
the Pearson correlation for the following pairs:

(G1, G2)
(G1, G3)
(G1, G4)
(G1, G5)
(G2, G3)
(G2, G4)
(G2, G5)
(G3, G4)
(G3, G5)
(G4, G5)

To generate correct pair of genes for correlation, we will make sure that

Gi < Gj

this will guarantee that we do not generate both of these pairs: (Gi, Gj) and
(Gj, Gi).

23.7.1 Input

We will read biomarker data from HDFS. We will assume that the following
data exist in HDFS (biomarker data are in text format and identiﬁed by text
ﬁles {b1, b2, b3, ...}:

/biomarker/input/b1
/biomarker/input/b2
/biomarker/input/b3
...

where each record in these biomarker ﬁles has the following format:

<Gene-ID><,><Reference><,><Patient-ID><,><Biomarker-Value-As-Double-Data-Type>

577

23.7.2 Output

Let G = {G1, G2, ..., Gm} be a set of gene IDs. The goal is to generate the
following set of output records for every pair of genes (Gi, Gj):

(Gi, Gj), (pearson-correlation, p-value)

where

• Gi < Gj
• Gi ∈ {G1, G2, ..., Gm}
• Gj ∈ {G1, G2, ..., Gm}
• 0.00 ≤ p-value ≤ 1.00

• −1.00 ≤ pearson-correlation ≤ +1.00

23.7.3 Spark Solution

We presnt our Spark solution as a single Java driver class, which uses rich
Spark API (such as filter() and cartesian() functions) to ﬁnd correlation
of all-vs-all genes. Note that, here we present a Spark solution for all-genes-
vs-all-genes, but you may apply this technique to any kind of data. The input
to Spark program will be a set of biomarker ﬁles and a reference (where the
value will be in {r1, r2, r3, r4}). All biomarker inputs are read from HDFS
into a single JavaRDD and then partitioned by the following Spark API:

public JavaRDD<T> coalesce(int numberOfPartitions)
// Description: return a new RDD that is
// reduced into numberOfPartitions partitions.

After JavaRDD is created and partitioned, then we ﬁlter all biomark-
ers by reference value. For example, if reference = r2, then all records,
which does not have reference of r2 are tossed out. This is accomplished
by JavaRDD.filter() function. Next we map all ﬁltered records by using
JavaRDD.mapToPair() function, which generates the following JavaPairRDD<K,V>:

578

K = Gene-ID (as String)
V = Tuple2<String, Double>(patientID, geneValue)

The next obvious thing to do is group all biomarker data by Gene-ID, which
generates the following JavaPairRDD (let’s call this grouped):

JavaPairRDD<String, Iterable<Tuple2<String,Double>>>

where

K = Gene-ID
V = Iterable<Tuple2(patientID, geneValue)>

To correlate all-vs-all genes, we have to create a cartesian product of
grouped by grouped: this will generate all possible combinations of (Gi,
Gj). Let’s call the result of the cartesian product as cart. Before doing any
correlation, we will ﬁlter the cartesian product result (cart) and keep only
pairs where Gi < Gj. Filtering is accomplished by

cart.filter(...);

After ﬁltering the cartesian product, we are ready to calculate Pearson
correlation and its associated p-value for all possible combinations of (Gi,
Gj). To compute Pearson correlation for (Gi, Gj), we will make the follow-
ing matrix:

PatientID1 PatientID2 PatientID3
avg(values)
avg(values)
avg(values)
avg(values)
avg(values)
avg(values)

...
...
...

Gi
Gj

Now, we are ready to present a complete solution using Spark API. First, we
present the entire structure of the Spark program as a set of high-level steps
and then each step is presented in detail.

579

23.7.4 Spark Solution: High-Level Steps

A workﬂow for Spark solution is presented below.

Listing 23.7: Spark Solution: High-Level Steps

1 // STEP-0: import required classes and interfaces
2 /**
3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

(g1, g2)
(g1, g3)
(g1, g4)
(g2, g3)
(g2, g4)
(g3, g4)

* What does All-vs-All correlation means?
*
* Let selected genes be: G = (g1, g2, g3, g4).
* Then all-vs-all will corrolate between the following pair of genes:
*
*
*
*
*
*
*
*
* Note that pairs (Ga, Gb) are generated if and only if (Ga < Gb).
* Correlation of (Ga, Gb) and (Gb, Ga) are the same, so there is no
* need to calculate correlation for duplicate genes.
*
*
*
*
*
* @author Mahmoud Parsian
*
*/

format:
example: 37761,r2,p10001,1.287

<geneID><,>,<r{1,2,3,4}><,><patientID><,><value>

Biomarker record example:

25
26 public class AllVersusAllCorrelation implements java.io.Serializable {
27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

static boolean smaller(String g1, String g2) {...}
static class MutableDouble implements java.io.Serializable {...}
static Map<String, MutableDouble> toMap(List<Tuple2<String,Double>> list) {...}
static List<String> toListOfString(Path hdfsFile) throws Exception {...}
static JavaRDD<String> readBiosets(JavaSparkContext ctx, List<String> biosets) {...}

public static void main(String[] args) throws Exception {

// STEP-1: handle input parameters
// STEP-2: create a Spark context object
// STEP-3: create list of input files/biomarkers
// STEP-4: broadcast reference as global shared object
which can be accessed from all cluster nodes
//
// STEP-5: read all biomarkers from HDFS and create the first RDD
// STEP-6: filter biomarkers by reference
// STEP-7: create (Gene-ID, (Patient-ID, Gene-Value) pairs
// STEP-8: group biomarkers by geneID
// STEP-9: create Cartesian product of all genes
// STEP-10: filter redundant pairs of genes
// STEP-11: calculate Pearson Correlation and p-value

System.exit(0);

580

Figure 23.4: Pearson Correlation of All-vs-All

581

}

48
49 }

23.7.5 STEP-0: import required classes and interfaces

This step import the required classes and interfaces. The classes and inter-
faces we need for our solution are contined in the following Spark packages:

• org.apache.spark.api.java, which we use the following classes: JavaPairRDD,

JavaRDD, and JavaSparkContext.

• org.apache.spark.api.java.function, which we use the following

interfaces: Function and PairFunction,

Listing 23.8: STEP-0: import required classes and interfaces

1 // STEP-0: import required classes and interfaces
2 import java.util.Map;
3 import java.util.HashMap;
4 import java.util.List;
5 import java.util.ArrayList;
6 import java.io.BufferedReader;
7 import java.io.InputStreamReader;
8 import scala.Tuple2;
9 import org.apache.spark.api.java.JavaRDD;
10 import org.apache.spark.api.java.JavaPairRDD;
11 import org.apache.spark.api.java.JavaSparkContext;
12 import org.apache.spark.api.java.function.PairFunction;
13 import org.apache.spark.api.java.function.Function;
14 import org.apache.spark.broadcast.Broadcast;
15 import org.apache.hadoop.fs.Path;
16 import org.apache.hadoop.fs.FileSystem;
17 import org.apache.hadoop.fs.FSDataInputStream;
18 import org.apache.hadoop.conf.Configuration;

23.7.6 Method smaller()

The smaller() method enable us to avoid generating duplicate pair of genes.
The pairs (g1, g2) and (g2, g1) will generate the sample correlation, so
we will only generate a single pair (g1, g2) where g1 is smaller than g2.
After Cartesian product of genes are generated (by using the cartesian()
function), we use the smaller() method to ﬁlter out the non-needed pair of
genes.

582

Listing 23.9: Method smaller()

1 static boolean smaller(String g1, String g2) {
2

if (g1.compareTo(g2) < 0){

3

4

5

6

return true;

}
else {

return false;

}

7
8 }

23.7.7 MutableDouble Class

The MutableDouble class is used to store all biomarker values for a single
patient. This class just sums up the double values and keeps the count and
it provides a convenient avg() method. This class will hold all values for
single gene and a single patient.

Listing 23.10: MutableDouble Class

1 static class MutableDouble implements java.io.Serializable {
2

private double value = 0.0;
private double count = 0.0;

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

public MutableDouble(double d) {

value = d;
count = 1.0;

}
public MutableDouble(Double d) {

if (d == null) {

value = 0.0;

}
else {

value = d;

}
count = 1.0;

}

public void increment(Double d) {

if (d == null) {

// value does not change

}
else {

value += d;

}
count++;

}

public void increment(double d) {

count++;

583

31

32

33

34

35

value += d;

}

public double avg() {

return value/count;

}

36
37 }

23.7.8 Method toMap()

This method converts a list of Tuple2<PatientID, BiomakerValue> into
a Map<PatientID, MutableDouble> (basically aggregates values for all pa-
tients for a single gene).

Listing 23.11: Method toMap()

1 static Map<String, MutableDouble> toMap(Iterable<Tuple2<String,Double>> list) {
Map<String, MutableDouble> map = new HashMap<String, MutableDouble>();
2
for (Tuple2<String,Double> entry : list) {

3

MutableDouble md = map.get(entry._1);
if (md == null) {

map.put(entry._1, new MutableDouble(entry._2));

}
else {

md.increment(entry._2);

}

}
return map;

4

5

6

7

8

9

10

11

12
13 }

23.7.9 Method toListOfString()

This method create a List<String>, where each element is an HDFS ﬁle
represneting a biomarker ﬁle for a patient (each patient may have any number
of biomarker ﬁles). The input to this method is an HDFS ﬁle, which contains
all biomarker ﬁles involved for the Pearson correlation. To understand this
method, I provide the following example used for a demo.

# hadoop fs -cat /biomarkers/biomarkers.txt
/biomarker/input/b1
/biomarker/input/b2
/biomarker/input/b3
/biomarker/input/b4
/biomarker/input/b5
/biomarker/input/b6

584

/biomarker/input/b7
/biomarker/input/b8
/biomarker/input/b9
/biomarker/input/b10
/biomarker/input/b11
/biomarker/input/b12
/biomarker/input/b13
/biomarker/input/b14
/biomarker/input/b15

# hadoop fs -cat /biomarker/input/b1
g1,r2,p1,1.86
g2,r2,p1,0.74
g3,r2,p1,1.24
...

# hadoop fs -cat /biomarker/input/b2
g1,r2,p2,2.46
g2,r2,p2,3.24
g3,r1,p2,1.44
...

For this example, the result is a List<String>, which contains the fol-

lowing list of Strings:

/biomarker/input/b1
/biomarker/input/b2
...
/biomarker/input/b14
/biomarker/input/b15

Listing 23.12: Method toListOfString()

1 static List<String> toListOfString(Path hdfsFile) throws Exception {
2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

FSDataInputStream fis = null;
BufferedReader br = null;
FileSystem fs = FileSystem.get(new Configuration());
List<String> list = new ArrayList<String>();
try {

fis = fs.open(hdfsFile);
br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null) {

String value = line.trim();
list.add(value);

}

}
finally {

if (br != null) {

585

br.close();

}

}
return list;

17

18

19

20
21 }

23.7.10 Method readBiosets()

This method reads all biomarkers (ﬁles in HDFS) and generates the ﬁrst
RDD for further processing. Each RDD element is a record of biomarker ﬁle.
You may further partition this RDD by using the following Spark API:

public JavaRDD<T> coalesce(int numPartitions)
// Description: return a new RDD that is reduced
// reduced into numPartitions partitions.

The question is how to select the right number of partitions for an RDD. The
answer depends on the number of cluster nodes, number of cores per server,
and the amount of RAM. There is no silver bullet formula for ﬁnding the the
right number of partitions for an RDD (you may ﬁnd and set this for your
environment by some trial and error).

Listing 23.13: Method readBiosets()

1 static JavaRDD<String> readBiosets(JavaSparkContext ctx,
2

List<String> biosets) {

int size = biosets.size();
int counter = 0;
StringBuilder paths = new StringBuilder();
for (String biosetFile : biosets) {

counter++;
paths.append(biosetFile);
if (counter < size) {

paths.append(",");

}

}
JavaRDD<String> rdd = ctx.textFile(paths.toString());
return rdd;

3

4

5

6

7

8

9

10

11

12

13

14
15 }

586

23.7.11 STEP-1: handle input parameters

This step reads 3 input:

• The ﬁrst parameter is a YARN’s resource manager host name, which

is used to create JavaSparkContent object

• The second parameter is a reference value, which can be any of {”r1”,

”r2”, ”r3”, ”r4”}

• The last parameter is an HDFS ﬁle, which contains the list of all
biomarker ﬁles (persisted as HDFS ﬁles) required for Pearson corre-
lation.

Listing 23.14: STEP-1: handle input parameters

1 // STEP-1: handle input parameters
2 if (args.length < 3) {
3

System.err.println("Usage: AllVersusAllCorrelation <resource-manager-host-name>

" +

4

5

6

System.err.println("Usage: OneVersusAllCorrelation myserver100

r2 " +

"<reference> <all-bioset-ids-as-filename>");

" <all-bioset-ids-as-filename>");

System.exit(1);

7
8 }
9 final String yarnResourceManagerHostName = args[0]; // myserver100
10 final String reference = args[1]; // {"r1", "r2", "r3", "r4"}
11 final String biomarkersFileName = args[2];

23.7.12 STEP-2: create a Spark context object

This step creates a JavaSparkContext object by using YARN’s resource
manager. An instance of JavaSparkContext can be created many diﬀerent
ways; the SparkUtil class provides two convenient methods to create an in-
stance of JavaSparkContext object. SparkUtil’s methods are:

public class SparkUtil {

/**

* Create a JavaSparkContext object from a given YARN’s resource manager host
*
* @param yarnResourceManagerHost the YARN’s resource manager host
* @return a JavaSparkContext
*
*/

587

public static JavaSparkContext

createJavaSparkContext(String yarnResourceManagerHost)
throws Exception {...}

/**

"spark://<spark-master-host-name>:7077"

* Create a JavaSparkContext object from a given Spark’s master URL
*
* @param sparkMasterURL Spark master URL as
*
* @param description program description
* @return a JavaSparkContext
*
*/

public static JavaSparkContext

createJavaSparkContext(String sparkMasterURL, String description)
throws Exception {...}

}

Listing 23.15: STEP-2: create a Spark context object

1 // STEP-2: create a Spark context object
2 JavaSparkContext ctx = SparkUtil.createJavaSparkContext(yarnResourceManagerHostName);

23.7.13 STEP-3: create list of input ﬁles/biomarkers

This step reads an HDFS ﬁle, which contains all biomarker ﬁles required for
Pearson correlation. The biomarkersFileName is a text HDFS ﬁle, which
contains all input biomarker ﬁles (one biomarker ﬁle per line).

Listing 23.16: STEP-3: create list of input ﬁles/biomarkers

1

List<String> list = toListOfString(new Path(biomarkersFileName));

588

23.7.14 STEP-4: broadcast ”reference” as global shared

object

Since ”reference” (values are in {”r1”, ”r2”, ”r3”, ”r4”}) value is used for
ﬁltering RDD elements, it should be broadcasted to all cluster nodes.
In
Spark, to broadcast (as a read only shared object) a data structure, we
can use the Broadcast class. This is how we can use a Broadcast class to
broadcast a shared data structure:

• To broadcast a shared data structure of type T

T t = <create-object-of-type-T>;
final Broadcast<T> broadcastT = ctx.broadcast(t);

• To read/access a broadcasted shared data structure of type T

T t = broadcastT.value();

In MapReduce/Hadoop, you may broadcast a shared data to map() or
reduce() functions by using Hadoop’s Configuration object. You may use
Configuration.set(...) to brodcast and use Configuration.get(...)
to read/access broadcasted objects. Spark’s API is much richer than Hadoop’s
API since you may broadcast any type of data structures.

Listing 23.17: STEP-4: broadcast reference as global shared object

1 // broadcast reference which can be accessed from all cluster nodes
2 final Broadcast<String> REF = ctx.broadcast(reference); // "r2"

23.7.15 STEP-5: read all biomarkers from HDFS and

create the ﬁrst RDD

This step reads all biomarker ﬁles an create a single JavaRDD<String>, which
can be partitioned further by the following method:

JavaRDD<T> coalesce(int numPartitions)

Listing 23.18: STEP-5: read all biomarkers from HDFS and create the ﬁrst

RDD

589

1 // STEP-5: read all biomarkers from HDFS and create the first RDD
2 JavaRDD<String> biosets = readBiosets(ctx, list);
3 biosets.saveAsTextFile("/output/1");

To debug, a sample output of this step is provided:

# hadoop fs -cat /output/1/*
g1,r2,p1,1.86
g2,r2,p1,0.74
g3,r2,p1,1.24
g4,r1,p1,2.44
g5,r2,p1,1.69
g6,r2,p1,0.93
g7,r2,p1,1.44
g8,r2,p1,2.11
g1,r2,p2,2.46
g2,r2,p2,3.24
...

Note that the methods JavaRDD.saveAsTextFile() and JavaPairRDD.saveAsTextFile()
are not required for our Spark solution (these methods saves the RDDs in
HDFS). These methods are provided for debugging and understanding of the
provided steps.

23.7.16 STEP-6: ﬁlter biomarkers by reference

Spark provides a very simple and powerful API for ﬁltering RDDs. To ﬁlter
elements, we just need to implement a ﬁlter() function: return true for the
records you want to keep and return false for the records you want to toss
out.

Listing 23.19: STEP-6: ﬁlter biomarkers by reference

1 // JavaRDD<T> filter(Function<T,Boolean> f)
2 // Return a new RDD containing only the elements that satisfy a predicate.
3 JavaRDD<String> filtered = biosets.filter(new Function<String,Boolean>() {
4

public Boolean call(String record) {

5

6

7

8

String ref = REF.value();
String[] tokens = record.split(",");
if (ref.equals(tokens[1]))

{

return true; // do return these records

590

9

10

11

12

}
else {

return false; // do not retrun these records

}

}

13
14 });
15 filtered.saveAsTextFile("/output/2");

To debug, a sample output of this step is provided: note that only ”r2”
references will be present in the output (all other references {r1, r3, r4} are
dropped from the resulting RDD).

# hadoop fs -cat /output/2/*
g1,r2,p1,1.86
g2,r2,p1,0.74
g3,r2,p1,1.24
g5,r2,p1,1.69
g6,r2,p1,0.93
g7,r2,p1,1.44
g8,r2,p1,2.11
g1,r2,p2,2.46
g2,r2,p2,3.24
g4,r2,p2,2.11
g5,r2,p2,1.69
g6,r2,p2,1.25
...

23.7.17 STEP-7: create (Gene-ID, (Patient-ID, Gene-

Value) pairs

This step implements a map() function, which transforms (note that from
this point on ”reference” is not needed for subsequent steps.)

<GeneID<><,><reference><,><PatientID><,><BiomarkerValue>

into

591

(K, V) pair
where

K = GeneID
V = Tuple2<PatientID, BiomarkerValue>

Listing 23.20: STEP-7: create (Gene-ID, (Patient-ID, Gene-Value) pairs

1 // STEP-7: create (Gene-ID, (Patient-ID, Gene-Value) pairs
2 // PairMapFunction<T, K, V>
3 // T => Tuple2<K, V> = Tuple2<gene, Tuple2<patientID, value>>
4 //
5 JavaPairRDD<String,Tuple2<String,Double>> pairs = filtered.mapToPair(new PairFunction<
6

String,
String,
Tuple2<String,Double>
>() {
public Tuple2<String,Tuple2<String,Double>> call(String rec) {

// T
// K = g1234 (as GeneID)
// V = <patientID, value>

String[] tokens = rec.split(",");
// tokens[0] = 1234
// tokens[1] = 2 (this is a ref in {"1", "2", "3", "4"}
// tokens[2] = patientID
// tokens[3] = value
Tuple2<String,Double> V =

new Tuple2<String,Double>(tokens[2], Double.valueOf(tokens[3]));

return new Tuple2<String,Tuple2<String,Double>>(tokens[0], V);

7

8

9

10

11

12

13

14

15

16

17

18

}

19
20 });
21 pairs.saveAsTextFile("/output/3");

To debug, a sample output of this step is provided:

# hadoop fs -cat /output/3/*
(g1,(p1,1.86))
(g2,(p1,0.74))
(g3,(p1,1.24))
(g5,(p1,1.69))
(g6,(p1,0.93))
(g7,(p1,1.44))
(g8,(p1,2.11))
(g1,(p2,2.46))
(g2,(p2,3.24))
...

592

23.7.18 STEP-8: group by gene

This step groups data by GeneID. The result of this grouping is a new RDD
as:

JavaPairRDD<String, Iterable<Tuple2<String,Double>>>

where

K = GeneID
V = Iterable<Tuple2<PatientID, BiomarkerValue>>

Listing 23.21: STEP-8: group by gene

1 // STEP-8: group by gene
2 JavaPairRDD<String, Iterable<Tuple2<String,Double>>>
3 grouped.saveAsTextFile("/output/4");
4 // grouped = (K, V)
5 //
where
6 //
7 //
8 grouped.saveAsTextFile("/output/5");

K = gene
V = Iterable<Tuple2<patientID,value>>

grouped = pairs.groupByKey();

To debug, a partial sample output of this step is provided: the output is

formatted to ﬁt the page.

# hadoop fs -cat /output/5/*
(g1,[(p1,1.86), (p1,1.76), (p1,1.16), (p3,1.06),
(p1,1.86), (p2,1.46), (p2,1.33), (p2,2.46),
(p2,2.46), (p2,1.33), (p3,2.61), (p1,2.86),
(p2,2.06), (p2,1.43)])

(g2,[(p2,3.24), (p2,1.24), (p2,2.0), (p3,1.55),

(p1,1.74), (p2,3.2), (p2,2.5), (p1,0.74),
(p1,2.84), (p1,1.33), (p3,1.24), (p3,2.1),
(p1,2.74), (p2,2.24), (p2,2.0)])

...

23.7.19 STEP-9: create Cartesian product of all genes

To perform all-genes-vs-all-genes correlation of all genes, we have to create a
Cartesian product of all genes. This is accomplished by JavaPairRDD.cartesian()
function.

593

Listing 23.22: STEP-9: create Cartesian product of all genes

1 // STEP-9: create Cartesian product of all genes
2 // <U> JavaPairRDD<T,U> cartesian(JavaRDDLike<U,?> other)
3 // Return the Cartesian product of this RDD and another one,
4 // that is, the RDD of all pairs of elements (a, b)
5 // where a is in this and b is in other.
6 JavaPairRDD< Tuple2<String, Iterable<Tuple2<String,Double>>>,
7

Tuple2<String, Iterable<Tuple2<String,Double>>>

> cart = grouped.cartesian(grouped);

8
9 cart.saveAsTextFile("/output/6");
10 // cart =
11 //
12 //
13 //
14 //

(g1, g1), (g1, g2),
(g2, g1), (g2, g2),
(g3, g1), (g3, g2),
(g4, g1), (g4, g2),

(g1, g3), (g1, g4)
(g2, g3), (g2, g4)
(g3, g3), (g3, g4)
(g4, g3), (g4, g4)

23.7.20 STEP-10: ﬁlter redundant pairs of genes

Let g1 and g2 be two genes; since Pearson correlation for (g1, g2) is the same
as (g2, g1), therefore, to reduce computation time, we will ﬁlter duplicate
pairs. We only keep the gene pairs of (g1, g2) if and only if g1 < g2.

Listing 23.23: STEP-10: ﬁlter redundant pairs of genes

if and only if (Ga < Gb).

1 // STEP-10: filter redundant pairs of genes
2 // filter it and keep the ones (Ga, Gb)
3 // after filtering, we will have:
4 // filtered2 =
5 //
6 //
7 //
8 //
9 // JavaRDD<T> filter(Function<T,Boolean> f)
10 // Return a new RDD containing only the elements that satisfy a predicate.
11 JavaPairRDD<Tuple2<String, Iterable<Tuple2<String,Double>>>,
12

(g1, g2),
(g2, g3), (g2, g4)
(g3, g4)

Tuple2<String, Iterable<Tuple2<String,Double>>>> filtered2 =

(g1, g3), (g1, g4)

13

14

15

16

17

18

19

20

21

22

23

24

25

26

cart.filter(new Function<Tuple2<Tuple2<String, Iterable<Tuple2<String,Double>>>,

Tuple2<String, Iterable<Tuple2<String,Double>>>

>,
Boolean>() {

public Boolean call(Tuple2<Tuple2<String, Iterable<Tuple2<String,Double>>>,

Tuple2<String, Iterable<Tuple2<String,Double>>>> pair) {

// pair._1 = Tuple2<String, Iterable<Tuple2<String,Double>>>
// pair._2 = Tuple2<String, Iterable<Tuple2<String,Double>>>
if (smaller(pair._1._1,

pair._2._1))

{

return true; // do return these records

}
else {

return false; // do not retrun these records

}

594

}

27
28 });
29 filtered2.saveAsTextFile("/output/7");

To debug this step, partial output of this step is displayed below. Output

is formatted to ﬁt the page.

# hadoop fs -cat /output/7/*

...
((g1,[(p2,2.46), (p2,2.46), (p2,1.33), (p3,2.61), (p1,2.86),
(p2,2.06), (p2,1.43), (p1,1.86), (p1,1.76), (p1,1.16),
(p3,1.06), (p1,1.86), (p2,1.46), (p2,1.33)]),

(g2,[(p2,3.24), (p2,1.24), (p2,2.0), (p3,1.55), (p1,1.74),
(p2,3.2), (p1,0.74), (p1,2.84), (p1,1.33), (p3,1.24),
(p3,2.1), (p1,2.74), (p2,2.24), (p2,2.0), (p2,2.5)])

)
...
((g3,[(p1,1.24), (p1,1.24), (p1,1.64), (p1,2.66),

(p3,2.22), (p1,1.24)]),

(g4,[(p2,2.11), (p2,2.11), (p2,1.77), (p2,2.01),

(p3,2.87), (p2,1.11), (p2,1.77), (p2,1.78)])

)
...

23.7.21 STEP-11: calculate Pearson Correlation and

p-value

Now, our generated pairs are aggregated with proper data and it is time to
perform a Pearson correlation and ﬁnd its associated p-value. If there is no
suﬃcient data for correlation, then we return Double.NaN for correlation and
p-value. The Pearson correlation is implemented by using Apache’s Common
Math3 package (provided in the following sections).

Listing 23.24: STEP-11: calculate Pearson Correlation and p-value

595

1 // STEP-11: calculate Pearson Correlation and p-value
2 // next iterate through all mappedValues
3 // JavaPairRDD<String, List<Tuple2<String,Double>>> mappedvalues
4 // create (K,V), where
5 //
6 //
7 //
8 JavaPairRDD<Tuple2<String,String>,Tuple2<Double,Double>> finalresult =
9

K = Tuple2<String,String>(g1, g2)
V = Tuple2<Double,Double>(corr, pvalue)

filtered2.mapToPair(new PairFunction<

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 });

Tuple2<Tuple2<String,Iterable<Tuple2<String,Double>>>,

Tuple2<String,Iterable<Tuple2<String,Double>>>>, // input

Tuple2<String,String>,
Tuple2<Double,Double>

>() {

// K
// V

public Tuple2<Tuple2<String,String>,Tuple2<Double,Double>>

call(Tuple2<Tuple2<String,Iterable<Tuple2<String,Double>>>,

Tuple2<String,Iterable<Tuple2<String,Double>>>> t) {

Tuple2<String,Iterable<Tuple2<String,Double>>> g1 = t._1;
Tuple2<String,Iterable<Tuple2<String,Double>>> g2 = t._2;
//
Map<String, MutableDouble> g1map = toMap(g1._2);
Map<String, MutableDouble> g2map = toMap(g2._2);
// now perform a correlation(one, other)
// make sure we order the values accordingly by patientID
// each patientID may have one or more values
List<Double> x = new ArrayList<Double>();
List<Double> y = new ArrayList<Double>();
for (Map.Entry<String, MutableDouble> g1Entry : g1map.entrySet()) {

String g1PatientID = g1Entry.getKey();
MutableDouble g2MD = g2map.get(g1PatientID);
if (g2MD != null) {

// both one and other for patientID have values
x.add(g1Entry.getValue().avg());
y.add(g2MD.avg());

}

}

System.out.println("x="+x);
System.out.println("y="+y);
// K = pair of genes
Tuple2<String,String> K = new Tuple2<String,String>(g1._1,g2._1);
if (x.size() < 3) {

// not enough data to perform correlation
return new Tuple2<Tuple2<String,String>,Tuple2<Double,Double>>
(K, new Tuple2<Double,Double>(Double.NaN, Double.NaN));

}
else {

// Pearson
double correlation = Pearson.getCorrelation(x, y);
double pvalue = Pearson.getPvalue(correlation, (double) x.size() );
return new Tuple2<Tuple2<String,String>,Tuple2<Double,Double>>

(K, new Tuple2<Double,Double>(correlation, pvalue));

}

}

596

57 finalresult.saveAsTextFile("/output/corr");

To debug, a complete output of ﬁnal step is provided. You should note
that if two genes do have not enough data to correlate, then for a lack of
proper value, we have emitted Double.NaN.

# hadoop fs -cat /output/corr/part*
((g1,g2),(-0.5600331663273436,0.6215767617117369))
((g1,g3),(NaN,NaN))
((g1,g4),(NaN,NaN))
((g1,g5),(-0.02711004213333685,0.9827390963782845))
((g1,g6),(0.19358340989347553,0.8759779754044315))
((g1,g7),(-0.8164277145788058,0.3919024816433061))
((g1,g8),(0.1671231007563918,0.8931045335800389))
((g1,g9),(0.6066217061857698,0.5850485651167254))
((g2,g3),(NaN,NaN))
((g2,g4),(NaN,NaN))
((g2,g5),(-0.8129831655334596,0.3956841419099777))
((g2,g6),(-0.9212118275674606,0.25440121369269475))
((g2,g7),(0.9356247601371344,0.22967428006843038))
((g2,g8),(-0.9104130933946509,0.271527771868302))
((g2,g9),(-0.9983543136507176,0.036528196595012385))
((g3,g4),(NaN,NaN))
((g3,g5),(NaN,NaN))
((g3,g6),(NaN,NaN))
((g3,g7),(NaN,NaN))
((g3,g8),(NaN,NaN))
((g3,g9),(NaN,NaN))
((g4,g5),(NaN,NaN))
((g4,g6),(NaN,NaN))
((g4,g7),(NaN,NaN))
((g4,g8),(NaN,NaN))
((g4,g9),(NaN,NaN))
((g5,g6),(0.9754751741958164,0.1412829282172836))
((g5,g7),(-0.5551020210096935,0.625358421978409))
((g5,g8),(0.9810429471659294,0.12415637004167612))
((g5,g9),(0.7782528977513095,0.4322123385049901))
((g6,g7),(-0.7245714063087034,0.4840754937611247))
((g6,g8),(0.9996381540187659,0.017126558175602602))
((g6,g9),(0.8973843455132996,0.2909294102877069))
((g7,g8),(-0.7057703774748613,0.5012020519367326))
((g7,g9),(-0.9543282445223156,0.19314608347341866))
((g8,g9),(0.885190414128154,0.30805596846331396))

23.7.22 Pearson Class

This is a wrapper class, which provides two methods: getCorrelation()
and getPvalue(). The underlying implementation uses Apache’s Commons

597

Math3 package4.

Listing 23.25: Pearson Wrapper Class

1 import java.util.List;
2 import java.util.Arrays;
3 import org.apache.commons.math3.distribution.TDistribution;
4 import org.apache.commons.math3.stat.correlation.PearsonsCorrelation;
5 /**
6

* Class for calculating the Pearson Correlation Coefficient and p-value
*
*/

7

8
9 public class Pearson {
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

final static PearsonsCorrelation PC = new PearsonsCorrelation();

public static double getCorrelation(List<Double> X, List<Double> Y) {

double[] xArray = toDoubleArray(X);
double[] yArray = toDoubleArray(Y);
double corr = PC.correlation(xArray, yArray);
return corr;

}

private static double[] toDoubleArray(List<Double> list) {

if (list == null) {
return null;

}
double[] arr = new double[list.size()];
for (int i=0; i < list.size(); i++) {

arr[i] = list.get(i);

}
return arr;

}

public static double getPvalue(final double corr, final int n) {

return getPvalue(corr, (double) n);

}

public static double getPvalue(final double corr, final double n) {

double t = Math.abs(corr * Math.sqrt( (n-2.0) / (1.0 - (corr * corr)) ));
System.out.println("
TDistribution tdist = new TDistribution(n-2);
double pvalue = 2* (1.0 - tdist.cumulativeProbability(t));
return pvalue;

t = "+ t);

}

41
42 }

23.7.23 Test Pearson Class

Here we test our wrapper class.

4http://commons.apache.org/proper/commons-math/

598

Listing 23.26: Pearson Wrapper Class

1 import java.util.List;
2 import java.util.Arrays;
3 public class TestPearson {
4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

public static void main(String[] args) {

test(args);

}

/**

* test/debug
*/

public static void test(String[] args) {

0

2

index

1
3
//
List<Double> X = Arrays.asList(2.0,
4.0, 45.0, 6.0, 7.0);
List<Double> Y = Arrays.asList(23.0, 5.0, 54.0, 6.0, 7.0);
double n = X.size(); // 5.0;
double corr = Pearson.getCorrelation(X, Y);
double pvalue = Pearson.getPvalue(corr, n);
System.out.println("corr
System.out.println("pvalue = "+ pvalue);

= "+ corr);

4

}

21
22 }

23.7.24 Pearson Correlation Using R

Here we show how to use R language for Pearson correlation. You may use
this to compare Java implementation with R.

Listing 23.27: Pearson Correlation using R Language

1 > x=c(2,4,45,6,7)
2 > y=c(23,5,54,6,7)
3 > cor.test(x,y)
4
5 Pearson’s product-moment correlation
6
7 data: x and y
8 t = 3.6026, df = 3, p-value = 0.03669
9 alternative hypothesis: true correlation is not equal to 0
10 95 percent confidence interval:
11
12 sample estimates:
cor
13
14 0.9012503

0.09266873 0.99352355

599

23.7.25 YARN Script to Run Spark Program

To run our Spark program, AllVersusAllCorrelation, the following shell script
is used to run it on YARN.

Listing 23.28: YARN Script to Run Spark Program

1 # cat run_all_vs_all.sh
2 #!/bin/bash
3 export SPARK_HOME=/usr/local/spark-1.0.0
4 # app jar:
5 export MY_JAR=/home/mahmoud/mp.jar
6 prog=AllVersusAllCorrelation
7 yarnResourceManagerHostName=myserver100
8 reference=r2
9 biomarkers=/home/hadoop/spark_mahmoud_examples/biomarkers.txt
10 $SPARK_HOME/bin/spark-submit --class $prog \
11

--master yarn-cluster \
--num-executors 12 \
--driver-memory 3g \
--executor-memory 7g \
--executor-cores 12 \
$MY_JAR $yarnResourceManagerHostName

12

13

14

15

16

$reference

$biomarkers

23.8 Spearman Correlation

To calculate Spearman correlation instead of Pearson, you just need to re-
place the following two lines:

// Pearson
double correlation = Pearson.getCorrelation(x, y);
double pvalue = Pearson.getPvalue(correlation, (double) x.size() );

with

// Spearman
double correlation = Spearman.getCorrelation(x, y);
double pvalue = Spearman.getPvalue(correlation, (double) x.size() );

and use the Spearman wrapper class provided below.

600

23.8.1 Spearman Correlation Wrapper Class

This is a wrapper class, which provides two methods: getCorrelation()
and getPvalue(). The underlying implementation uses Apache’s Commons
Math3 package.

Listing 23.29: Spearman Wrapper Class

1 import java.util.Arrays;
2 import java.util.List;
3 import java.util.ArrayList;
4 import org.apache.commons.math3.distribution.TDistribution;
5 import org.apache.commons.math3.stat.correlation.SpearmansCorrelation;
6
7 /**
8

* Class for calculating Spearman’s Rank Correlation between two vectors.
*
* @author Mahmoud Parsian
*
*/

9

10

11

12
13 public class Spearman {
14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

final static SpearmansCorrelation SC = new SpearmansCorrelation();

public static double getCorrelation(List<Double> X, List<Double> Y) {

double[] xArray = toDoubleArray(X);
double[] yArray = toDoubleArray(Y);
double corr = SC.correlation(xArray, yArray);
return corr;

}

public static double getPvalue(double corr, double n) {

double t = Math.abs(corr * Math.sqrt( (n-2.0) / (1.0 - (corr * corr)) ));
System.out.println("
TDistribution tdist = new TDistribution(n-2);
double pvalue = 2.0 * (1.0 - tdist.cumulativeProbability(t));
return pvalue;

t = "+ t);

}

static double[] toDoubleArray(List<Double> list) {

double[] arr = new double[list.size()];
for (int i=0; i < list.size(); i++) {

arr[i] = list.get(i);

}
return arr;

}

38
39 }

23.8.2 Test Spearman Correlation Wrapper Class

This class tests Spearman’s wrapper class.

601

Listing 23.30: TestSpearman Class

1 import java.util.Arrays;
2 import java.util.List;
3 public class TestSpearman {
4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

public static void main(String[] args) {

test(args);

}

3

5

1

public static void test(String[] args) {
2
4
//
List<Double> X = Arrays.asList(2.0,
4.0, 45.0, 6.0, 7.0);
List<Double> Y = Arrays.asList(23.0, 5.0, 54.0, 6.0, 7.0);
double n = X.size(); // 5.0;
double corr = getCorrelation(X, Y);
double pvalue = getPvalue(corr, n);
System.out.println("corr
System.out.println("pvalue = "+ pvalue);
2
//
4
List<Double> X2 = Arrays.asList(12.0,
14.0, 45.0, 6.0, 17.0);
List<Double> Y2 = Arrays.asList(3.0, 5.0, 15.0, 16.0, 17.0);
double n2 = X2.size(); // 5.0;
double corr2 = getCorrelation(X2, Y2);
double pvalue2 = getPvalue(corr2, n2);
System.out.println("corr2
System.out.println("pvalue2 = "+ pvalue2);

= "+ corr2);

= "+ corr);

5

1

3

}

26
27 }

602

Chapter 24

DNA Base Count

24.1

Introduction

The purpose of this chapter is to count DNA1 bases. Human DNA’s code
is written in only four letters: A, C, T and G; and when when we cannot
recognize the code, we label it as N. The meaning of this DNA code lies in
the sequence of the letters A, T, C and G in the same way that the meaning
of a word lies in the sequence of English alphabet letters (A–Z).

The goal of this chapter is is to ﬁnd frequencies (or percentages) of A, T,
C, G, and N (anything other than A, T, C, or G) in a given set of DNA
sequences. Another goal of this chapter is to provide custom record readers
for Hadoop’s input ﬁles. What does ATCG stand for when talking about
DNA? It does refer to 4 of the nitrogenous bases associated with DNA:

• A = Adenine

• T = Thymine

• C = Cytosine

1”Deoxyribonucleic acid (DNA) is a molecule that encodes the genetic instructions
used in the development and functioning of all known living organisms and many viruses.
Along with RNA and proteins, DNA is one of the three major macromolecules essential
for all known forms of life. Genetic information is encoded as a sequence of nucleotides
(guanine, adenine, thymine, and cytosine) recorded using the letters G, A, T, and C.”
(source: http://en.wikipedia.org/wiki/DNA)

603

• G = Guanine

For example, ACGGGTACGAAT is a very small DNA sequence. DNA se-
quences can be huge2. DNA base counting for our example will generate the
following table:

Table 24.1: DNA Base Count Example

Base Count

a
t
c
g
n

4
2
2
4
0

DNA sequences can be represented in many diﬀerent formats including FASTA
and FASTQ popular text-based formats. Our solution will handle FASTA
and FASTQ formats. Note that Hadoop’s default record reader reads records
line-by-line and therefore we can not use the Hadoop’s default record reader
fro reading ﬁles in FASTQ format. We do need to plugin (inject custom
record readers) FastaInputFormat (to read fasta ﬁle formats) and FastqInputFormat
(to read fastq ﬁle formats).

24.2 FASTA Format

A sequence ﬁle in FASTA format can contain several sequences. Each se-
quence in FASTA format begins with a single-line description, followed by
one or many lines of sequence data. The description line must begin with a
greater-than (” > ”) symbol in the ﬁrst column.

2”The haploid human genome (contained in egg and sperm cells) consists of three
billion DNA base pairs, while the diploid genome (found in somatic cells) has twice the
DNA content.” source: http://en.wikipedia.org/wiki/Human_genome

604

24.2.1 FASTA Format Example

An example sequence in FASTA format is (this ﬁle has 4 sequences and case
(upper-case or lower-case) of characters are irrelevant):

cat test_fasta.fasta
>seq1
cGTAaccaataaaaaaacaagcttaacctaattc
>seq2
agcttagTTTGGatctggccgggg
>seq3
gcggatttactcCCCCCAAAAANNaggggagagcccagataaatggagtctgtgcgtccaca
gaattcgcacca
AATAAAACCTCACCCAT
agagcccagaatttactcCCC
>seq4
gcggatttactcaggggagagcccagGGataaatggagtctgtgcgtccaca
gaattcgcacca

24.3 FASTQ Format

FASTQ3 format is a text-based format for storing both a biological sequence
(usually nucleotide sequence) and its corresponding quality scores. Both the
sequence letter and quality score are encoded with a single ASCII character
for brevity. A FASTQ ﬁle normally uses four lines per sequence deﬁned as:

• Line 1 begins with a ’@’ character and is followed by a sequence iden-

tiﬁer and an optional description

• Line 2 is the raw sequence letters (A, T, C, G, ...)

• Line 3 begins with a ’+’ character and is optionally followed by the

same sequence identiﬁer (and any description) again.

• Line 4 encodes the quality values for the sequence in Line 2, and must

contain the same number of symbols as letters in the sequence.

3source: http://en.wikipedia.org/wiki/FASTQ_format

605

24.3.1 FASTQ Format Example

A FASTQ ﬁle containing a single sequence might look like this:

@SEQ_ID
GATTTGGGGTTCAAAGCAGTATCGATCAAATAGTAAATCCATTTGTTCAACTCACAGTTT
+
!’’*((((***+))%%%++)(%%%%).1***-+*’’))**55CCF>>>>>>CCCCCCC65

24.4 MapReduce Solution: FASTA Format

For DNA base counting, we use a mapper, a reducer, and custom FASTA for-
mat reader (FASTA reader is accomplished by injecting FastaInputFormat
class to Job.setInputFormatClass() method).

24.4.1 Reading FASTA Files

How did we instruct MapReduce/Hadoop framework to read FASTA format
data? The default reader in Hadoop reads input records line-by-line, but a
FASTA record may span many (one or more) lines. Hadoop provides a plug-in
framework for ”input format” and ”record reader”. We developed two cus-
tom plug-in classes FastaInputFormat and FastaRecordReader to enable
us to read FASTA format (one or more lines is a single record). In Hadoop,
default input format is provided by the TextInputFormat class. Our cus-
tom class FastaInputFormat extends this class and overrides two methods:
createRecordReader() and isSplitable(). The override createRecordReader()
method returns a new custom ”record reader”, called FastaRecordReader.

24.4.2 MapReduce Solution: map()

To ﬁnd count of DNA bases, the map() will get a record of FASTA ﬁle
which can be one or more lines of DNA sequences. The map() will then
tokenize each line and count the bases. To make our mapper more eﬃ-
cient, we will not emit(letter, 1) for each letter, but we will emit a total
for each base by using a hash table (M ap < Character, Long >). Finally,
by using the Hadoop’s cleanup() method, we will iterate the hash table and
emit(letter, countOf Letter). The hash table is a very eﬃcient solution, since
the number of keys are limited to the very small number of DNA letters.

606

Furthermore this smart map() algorithm reduces the network traﬃc by just
emitting the minimum number of (letter, countOf Letter) to the MapReduce
framework. The mapper class, FastaCountBaseMapper, will have the follow-
ing structure:

Listing 24.1: FastaCountBaseMapper Class
public class FastaCountBaseMapper ... {

Map<Character, Long> dnaBasesCounter = null;

// this function is called once at the beginning of the map task.
setup() {

dnaBasesCounter = new HashMap<Character, Long>();

}

map(Object key, String value) {

...

}

// called once at the end of the map task.
cleanup() {

// now iterate the baseCounter and emit <key, value>
for (Map.Entry<Character, Long> entry : dnaBaseCounter.entrySet())

{

emit(entry.getKey(), entry.getValue());

}

}

}

The map() function is listed below:

Listing 24.2: DNA Base Count map()
/**
* @param key is the key generated by Hadoop (ignored here)
* @param value is one line of input for a given document
*/
map(Object key, String value) {

// fasta is a string comprised of many DNA-seq lines
String fasta = value.trim().toLowerCase();
String[] lines = fasta.split("[\\r\\n]+");
for (int i=1; i < lines.length; i++) {

607

char[] array = lines[i].toCharArray();
for(char c : array){

Long v = dnaBaseCounter.get(c);
if (v == null) {

dnaBaseCounter.put(c, 1);

}
else {
v++;
dnaBaseCounter.put(c, v);

}

}

}

}

24.4.3 MapReduce Solution: reduce()

Since the number of DNA alphabet is very limited, we might just set the
number of reducers to 5 (one for every DNA letter). The reducer is almost
identical to the word-count reducer. It just sums up the counters for each
DNA letter.

Listing 24.3: DNA Base Count reduce() Function
/**
* @param key is the unique DNA letter generated by mapper
* @param value is a list of integers (partial count of a unique word)
*/
reduce(String key, List<long> value) {

long sum = 0;
for (int count : value) {

sum += count;

}
emit(key, sum);

}

608

24.5 Hadoop Implementation: FASTA For-

mat

24.5.1 Hadoop Sample Run

# ./run.sh
JAVA_HOME=/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Note: src/CountBaseMapper.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
added manifest
adding: BaseComparator.class(in = 622) (out= 374)(deflated 39%)
adding: BaseComparator.java(in = 530) (out= 242)(deflated 54%)
...
adding: FastaInputFormat.class(in = 4744) (out= 1976)(deflated 58%)
adding: FastaInputFormat.java(in = 3908) (out= 1191)(deflated 69%)
adding: FastaRecordReader.class(in = 4683) (out= 2181)(deflated 53%)
adding: FastaRecordReader.java(in = 4060) (out= 1373)(deflated 66%)
Deleted hdfs://localhost:9000/dna-base-count/output
13/03/15 09:16:22 INFO CountBaseDriver: inputDir=/dna-base-count/input
13/03/15 09:16:22 INFO CountBaseDriver: outputDir=/dna-base-count/output
13/03/15 09:16:22 INFO input.FileInputFormat: Total input paths to process : 1
13/03/15 09:16:23 INFO mapred.JobClient: Running job: job_201303150852_0002
13/03/15 09:16:24 INFO mapred.JobClient: map 0% reduce 0%
13/03/15 09:16:38 INFO mapred.JobClient: map 14% reduce 0%
...
13/03/15 09:17:53 INFO mapred.JobClient: map 100% reduce 100%
13/03/15 09:17:58 INFO mapred.JobClient: Job complete: job_201303150852_0002
...
13/03/15 09:17:58 INFO mapred.JobClient:
13/03/15 09:17:58 INFO mapred.JobClient:
13/03/15 09:17:58 INFO mapred.JobClient:
13/03/15 09:17:58 INFO mapred.JobClient:
13/03/15 09:17:58 INFO mapred.JobClient:
13/03/15 09:17:58 INFO mapred.JobClient:
13/03/15 09:17:58 INFO mapred.JobClient:
13/03/15 09:17:58 INFO mapred.JobClient:

Map-Reduce Framework

Map output materialized bytes=948
Map input records=7
Reduce shuffle bytes=828
Spilled Records=88
Map output bytes=440
Total committed heap usage (bytes)=2142334976
Combine input records=0

609

13/03/15 09:17:58 INFO mapred.JobClient:
13/03/15 09:17:58 INFO mapred.JobClient:
13/03/15 09:17:58 INFO mapred.JobClient:
13/03/15 09:17:58 INFO mapred.JobClient:
13/03/15 09:17:58 INFO mapred.JobClient:
13/03/15 09:17:58 INFO mapred.JobClient:
13/03/15 09:17:58 INFO CountBaseDriver: run(): status=true
13/03/15 09:17:58 INFO CountBaseDriver: returnStatus=0

SPLIT_RAW_BYTES=868
Reduce input records=44
Reduce input groups=9
Combine output records=0
Reduce output records=9
Map output records=44

# hadoop fs -cat /dna-base-count/output/p*
c 82
G 10
g 80
T 5
A 7
t 82
C 7
a 110
N 5

24.5.2 What If 1

What if you wanted to send ”a” and ”A” to the same reducer and wanted to
sum up ”a”’s with ”A”’s (since they are the same DNA letter). There are at
least two ways to accomplish this:

• Option-1: Convert all input of map() to lowercase letters. This can be

done very easily in the mapper code (map() function):

Replace the following line

String fasta = value.toString();

with this one:

String fasta = value.toString().toLowerCase();

• Option-2: Provide a outcome sorter, which will be injected to the
MapReduce framework. We can deﬁne the comparator that controls
how the keys are sorted before they are passed to the reducer. This is
how we do it:

610

job.setSortComparatorClass(BaseComparator.class);

And this is how we implement our comparator:

import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.io.WritableComparable;

public class BaseComparator extends WritableComparator {
protected BaseComparator(){
super(Text.class, true);
}

@Override
public int compare(WritableComparable w1, WritableComparable w2) {

Text t1 = (Text) w1;
Text t2 = (Text) w2;
String s1 = t1.toString().toUpperCase();
String s2 = t2.toString().toUpperCase();
int cmp = s1.compareTo(s2);
return cmp;

}
}

In Hadoop, for writing a ”custom comparator,” you just need to extend
the org.apache.hadoop.io.WritableComparator class and implement the
compare() method. Here, the ”custom comparator” (BaseComparator class)
sorts the keys (”a”, ”A”, ”t”, ”T”, ”c”, ”C”, ”g”, ”G”, ”n”, ”N”) ignoring
cases so that the same DNA base with diﬀerent cases will be next to each
other. By default, classes injected to methods setSortComparatorClass()
and setGroupingComparatorClass() use the same comparator, for exam-
ple, if we set setSortComparatorClass() and leave setGroupingComparator-
Class() unsetted, setGroupingComparatorClass() will use the same com-
paritor as we set for setSortComparatorClass(), but the opposite case (vice
versa) is not true. You can use this example to test and verify it.

611

24.5.3 What If 2

What if we wanted to send all of our keys just to only 5 reducers (one
reducer per DNA letter: A, T, C, G, N). The answer is to provide a custom
partitioner. The default partitioner in Hadoop is the HashPartitioner,
which hashes a mapper generated key to determine which partition (which
reducer) the (key, value) belongs in. The number of partition is then equal
to the number of reduce tasks for the job. So the main question is when a
map() generates a (key, value), does it have to be sent to a reducer? If so,
which one? We can use Job.setPartitionerClass() method to enable our
custom partitioner. This is how: we send all keys with letter a/A to reducer
1, b/B to reducer 2 , and so on.

Listing 24.1: Custom Partitioner

1 import org.apache.hadoop.mapreduce.Partitioner;

2
3 /** Partition keys by bases{A,T,G,C,a,t,g,c}. */
4 public class BasePartitioner<K, V> extends Partitioner<K, V> {

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23 }

public int getPartition(K key, V value, int numReduceTasks) {

String base = key.toString();
if (base.compareToIgnoreCase("A") == 0) {

return 0;

}
else if (base.compareToIgnoreCase("C") == 0) {

return 1;

}
else if (base.compareToIgnoreCase("G") == 0) {

return 2;

}
else if(base.compareToIgnoreCase("T") == 0) {

return 3;

}
else{

return 4;

}

}

612

Then in our driver class inject our custom classes as:

Listing 24.2: DNA Base Count Driver

1 public class CountBaseDriver extends Configured implements Tool {

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23
24 }

public int run(String[] args) throws Exception {

Job job = new Job(getConf(), "count-dns-bases");
job.setJarByClass(CountBaseMapper.class);
job.setMapperClass(CountBaseMapper.class);
job.setReducerClass(CountBaseReducer.class);
job.setNumReduceTasks(5);

//job.setCombinerClass(CountBaseCombiner.class);

job.setInputFormatClass(FastaInputFormat.class);
job.setPartitionerClass(BasePartitioner.class);
job.setSortComparatorClass(BaseComparator.class);
job.setGroupingComparatorClass(BaseComparator.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));

boolean status = job.waitForCompletion(true);
theLogger.info("run(): status="+status);
return status ? 0 : 1;

}
...

Now, when we run our job, we will have:

mahmoud@mahmouds-macbook:~/zmp/map_reduce_book/hadooptests/dna-base-count# ./run.sh
JAVA_HOME=/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Note: src/CountBaseMapper.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
added manifest
adding: BaseComparator.class(in = 622) (out= 374)(deflated 39%)
adding: BaseComparator.java(in = 530) (out= 242)(deflated 54%)
adding: BasePartitioner.class(in = 758) (out= 463)(deflated 38%)

613

adding: BasePartitioner.java(in = 553) (out= 265)(deflated 52%)
...
adding: FastaInputFormat.class(in = 4744) (out= 1976)(deflated 58%)
adding: FastaInputFormat.java(in = 3908) (out= 1191)(deflated 69%)
adding: FastaRecordReader.class(in = 4683) (out= 2181)(deflated 53%)
adding: FastaRecordReader.java(in = 4060) (out= 1373)(deflated 66%)
Deleted hdfs://localhost:9000/dna-base-count/output
13/03/15 09:44:26 INFO CountBaseDriver: inputDir=/dna-base-count/input
13/03/15 09:44:26 INFO CountBaseDriver: outputDir=/dna-base-count/output
13/03/15 09:44:27 INFO input.FileInputFormat: Total input paths to process : 1
13/03/15 09:44:27 INFO mapred.JobClient: Running job: job_201303150852_0004
13/03/15 09:44:28 INFO mapred.JobClient: map 0% reduce 0%
13/03/15 09:44:43 INFO mapred.JobClient: map 14% reduce 0%
...
13/03/15 09:45:58 INFO mapred.JobClient: map 100% reduce 100%
13/03/15 09:46:03 INFO mapred.JobClient: Job complete: job_201303150852_0004
13/03/15 09:46:03 INFO mapred.JobClient: Counters: 25
...
13/03/15 09:46:03 INFO mapred.JobClient:
13/03/15 09:46:03 INFO mapred.JobClient:
13/03/15 09:46:03 INFO mapred.JobClient:
13/03/15 09:46:03 INFO mapred.JobClient:
13/03/15 09:46:03 INFO mapred.JobClient:
13/03/15 09:46:03 INFO mapred.JobClient:
13/03/15 09:46:03 INFO mapred.JobClient:
13/03/15 09:46:03 INFO mapred.JobClient:
13/03/15 09:46:03 INFO mapred.JobClient:
13/03/15 09:46:03 INFO mapred.JobClient:
13/03/15 09:46:03 INFO mapred.JobClient:
13/03/15 09:46:03 INFO mapred.JobClient:
13/03/15 09:46:03 INFO mapred.JobClient:
13/03/15 09:46:03 INFO mapred.JobClient:
13/03/15 09:46:03 INFO CountBaseDriver: run(): status=true
13/03/15 09:46:03 INFO CountBaseDriver: returnStatus=0

Map output materialized bytes=948
Map input records=7
Reduce shuffle bytes=828
Spilled Records=88
Map output bytes=440
Total committed heap usage (bytes)=2142334976
Combine input records=0
SPLIT_RAW_BYTES=868
Reduce input records=44
Reduce input groups=5
Combine output records=0
Reduce output records=5
Map output records=44

Map-Reduce Framework

Now we have only 5 reducers:

$ hadoop fs -ls /dna-base-count/output/p*

614

-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--

1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff

6 2013-03-15 10:06 /dna-base-count/output/part-r-00000
5 2013-03-15 10:06 /dna-base-count/output/part-r-00001
5 2013-03-15 10:06 /dna-base-count/output/part-r-00002
5 2013-03-15 10:06 /dna-base-count/output/part-r-00003
4 2013-03-15 10:06 /dna-base-count/output/part-r-00004

$ hadoop fs -cat /dna-base-count/output/p*
a 117
c 89
g 90
t 87
n 5

24.6 MapReduce Solution: FASTQ Format

For DNA base counting, we use a mapper and a reducer. This solution
is very similar to the FASTA solution, with the diﬀerence of injecting a
diﬀerent class for handling input format. For FASTQ format, we will inject
FastqInputFormat class:

job.setInputFormatClass(FastqInputFormat.class);

Using FastqInputFormat, the mapper will get a value as Text object,

which has the following format (the line delimiter is ",;,"):

<line-1><,;,><line-2><,;,><line-3><,;,><line-4>

We have 4 lines per mapper value, since each FASTQ record corresponds
to lines of data. The mapper class for FASTQ format will be diﬀerent from
FASTA classes, due to the fact that input formats are diﬀerent, but the
reducer class will not change.

24.6.1 MapReduce Solution: map()

To ﬁnd count of DNA bases, the map() will get a record of FASTQ ﬁle,
which is exactly 4 lines of text and only the second line contains a DNA
sequence. The map() will then tokenize the second line which contains
DNA sequences and counts the bases. To make our mapper more eﬃ-
cient, we will not emit(letter, 1) for each letter, but we will emit total of

615

each base by using a hash table (M ap < Character, Long >). Finally,
by using the Hadoop’s cleanup() method, we will iterate the hash table and
emit(letter, countOf Letter). The hash table is a very eﬃcient solution, since
the number of keys are limited to the very small number of DNA letters.
Furthermore this smart map() algorithm reduces the network traﬃc by just
emitting the minimum number of (letter, countOf Letter) to the MapReduce
framework.

Listing 24.4: DNA Base Count map() using FASTQ Format
Map<Character, Long> dnaBasesCounter = null;
/**
* this function is called once at the beginning of the map task.
*/
setup() {

dnaBasesCounter = new HashMap<Character, Long>();

}

/**
* @param key is the key generated by Hadoop (ignored here)
* @param value is one line of input for a given document
*/
map(Object key, String value) {

String fastq = value.toString();
// 4 lines lines are separated by a special delimiter: ",;,"
String[] lines = fastq.split(",;,");
// 2nd line = lines[1] = the DNA sequence
char[] array = lines[1].toCharArray();
for(char c : array){

Long v = dnaBaseCounter.get(c);
if (v == null) {

dnaBaseCounter.put(c, 1);

}
else {
v++;
dnaBaseCounter.put(c, v);

}

}

}

/**
* Called once at the end of the map task.
*/

616

cleanup() {

// now iterate the baseCounter and emit <key, value>
for (Map.Entry<Character, Long> entry : dnaBaseCounter.entrySet()) {

emit(entry.getKey(), entry.getValue());

}

}

24.6.2 MapReduce Solution: reduce()

Since the number of DNA alphabet is very limited, we might just set the
number of reducers to 5 (one for every DNA letter). The reducer is almost
identical to the word-count reducer. It just sums up the counters for each
DNA letter.

Listing 24.5: DNA Base Count reduce() Function using FASTQ Format
/**
* @param key is the unique DNA letter generated by mapper
* @param value is a list of integers (partial count of a unique word)
*/
reduce(String key, List<long> value) {

long sum = 0;
for (int count : value) {

sum += count;

}
emit(key, sum);

}

24.7 Hadoop Implementation

The Hadoop implementation consists of the following classes:

BaseComparator.java
BasePartitioner.java
FastqCountBaseDriver.java
FastqCountBaseMapper.java
FastqCountBaseReducer.java
FastqInputFormat.java
FastqRecordReader.java

617

24.7.1 Sample Run of Hadoop Implementation

mahmoud@Mahmouds-MacBook:~/zmp/map_reduce_book/hadooptests/dna-base-count# ./run_fastq.sh
JAVA_HOME=/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
added manifest
adding: BaseComparator.class(in = 622) (out= 374)(deflated 39%)
...
adding: FastqRecordReader.java(in = 3297) (out= 1046)(deflated 68%)
Deleted hdfs://localhost:9000/dna-base-count/fastq/output
13/03/19 09:24:45 INFO FastqCountBaseDriver: inputDir=/dna-base-count/fastq/input
13/03/19 09:24:45 INFO FastqCountBaseDriver: outputDir=/dna-base-count/fastq/output
13/03/19 09:24:45 INFO FastqCountBaseDriver: run(): input args[0]=/dna-base-count/fastq/input
13/03/19 09:24:45 INFO FastqCountBaseDriver: run(): output args[1]=/dna-base-count/fastq/output
13/03/19 09:24:46 INFO input.FileInputFormat: Total input paths to process : 1
13/03/19 09:24:46 INFO mapred.JobClient: Running job: job_201303190908_0003
13/03/19 09:24:47 INFO mapred.JobClient: map 0% reduce 0%
...
13/03/19 09:26:03 INFO mapred.JobClient: map 100% reduce 100%
13/03/19 09:26:08 INFO mapred.JobClient: Job complete: job_201303190908_0003
...
13/03/19 09:26:08 INFO mapred.JobClient:
...
13/03/19 09:26:08 INFO mapred.JobClient:
13/03/19 09:26:08 INFO mapred.JobClient:
13/03/19 09:26:08 INFO FastqCountBaseDriver: run(): status=true
mahmoud@Mahmouds-MacBook:~/zmp/map_reduce_book/hadooptests/dna-base-count# hadoop fs -ls /dna-base-count/fastq/output/
Found 12 items
-rw-r--r--
drwxr-xr-x
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--

0 2013-03-19 09:26 /dna-base-count/fastq/output/_SUCCESS
0 2013-03-19 09:24 /dna-base-count/fastq/output/_logs
5 2013-03-19 09:25 /dna-base-count/fastq/output/part-r-00000
0 2013-03-19 09:25 /dna-base-count/fastq/output/part-r-00001
0 2013-03-19 09:25 /dna-base-count/fastq/output/part-r-00002
0 2013-03-19 09:25 /dna-base-count/fastq/output/part-r-00003
5 2013-03-19 09:25 /dna-base-count/fastq/output/part-r-00004
0 2013-03-19 09:25 /dna-base-count/fastq/output/part-r-00005
0 2013-03-19 09:25 /dna-base-count/fastq/output/part-r-00006

1 mahmoud staff
- mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff

Reduce output records=4
Map output records=4

Map input records=5

618

1 mahmoud staff
1 mahmoud staff
1 mahmoud staff

-rw-r--r--
-rw-r--r--
-rw-r--r--
mahmoud@Mahmouds-MacBook:~/zmp/map_reduce_book/hadooptests/dna-base-count# hadoop fs -cat /dna-base-count/fastq/output/p*
c 36
g 22
t 67
a 55

5 2013-03-19 09:25 /dna-base-count/fastq/output/part-r-00007
5 2013-03-19 09:25 /dna-base-count/fastq/output/part-r-00008
0 2013-03-19 09:25 /dna-base-count/fastq/output/part-r-00009

24.7.2 Reading FASTQ Files

How did we instruct MapReduce/Hadoop framework to read FASTQ for-
mat data? The default reader in Hadoop reads input records line-by-line,
but for FASTQ format we need to read 4-lines-by-4-lines (each 4 lines is a
FASTQ record). Hadoop provides a plug-in framework for ”input format”
and ”record reader”. We developed two custom plug-in classes FastqInputFormat
and FastqRecordReader to enable us to read FASTQ format (each 4 lines
is a single record).
In Hadoop, default input format is provided by the
TextInputFormat class. Our custom class FastqInputFormat extends this
class and overrides two methods: createRecordReader() and isSplitable().
The override createRecordReader() method returns a new custom ”record
reader”, called FastqRecordReader. This is how FastqInputFormat class is
implemented:

Listing 24.6: FastqInputFormat Custom Class

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.JobContext;

/**
* This class define an InputFormat for FASTQ
* files for the Hadoop MapReduce framework.

619

*/
public class FastqInputFormat extends TextInputFormat {

@Override
public RecordReader<LongWritable, Text> createRecordReader(

InputSplit inputSplit,
TaskAttemptContext taskAttemptContext) {

return new FastqRecordReader();

}

@Override
public boolean isSplitable(JobContext context, Path file) {

return false;

}

}

The other custom class is the FastqRecordReader, which extends the
RecordReader<LongWritable, Text> class. The FastqRecordReader class
breaks the input data into (key, value) pairs for input to the Mapper. In this
case, FastqRecordReader create values (as a String object), which can hold
the 4 lines of a FASTQ record:

Listing 24.7: FastqRecordReader Custom Class

import ...
import org.apache.hadoop.mapreduce.RecordReader;

/**
* This class define a RecordReader for FASTQ files
* for the Hadoop MapReduce framework.
*/
public class FastqRecordReader extends RecordReader<LongWritable, Text> {

...

}

620

Chapter 25

RNA-Sequencing

25.1

Introduction

In recent years, RNA sequencing has revolutionized the exploration of gene
expression. The improvements of RNA-sequencing methods enable researchers
to rapid proﬁle and investigate the transcriptome.

RNA stands for ribonucleic acid (RiboN ucleic Acid). Dr. Ananya Man-
del1 deﬁnes RNA as: ”It is an important molecule with long chains of nu-
cleotides. A nucleotide contains a nitrogenous base, a ribose sugar, and a
phosphate. Just like DNA, RNA is vital for living beings.” What is the main
function of RNA? The main function of RNA is to transfer the genetic code
need for the creation of proteins from the nucleus to the ribosome. ”This
process prevents the DNA from having to leave the nucleus. This keeps
the DNA and genetic code protected from damage. Without RNA, proteins
could never be made.”2

Our main focus in this chapter is to provide a complete MapReduce solu-
tion for a computational pipeline for analyzing RNA-Sequencing (RNA-Seq)
data for diﬀerential gene expression. In our implementation, we will utilize
two open-source pacakges:

• TopHat3 (TopHat is a fast splice junction mapper for RNA-Seq reads.
It aligns RNA-Seq reads to mammalian-sized genomes using the ul-

1http://www.news-medical.net/health/What-is-RNA.aspx
2http://www.news-medical.net/health/What-is-RNA.aspx
3http://tophat.cbcb.umd.edu/

621

tra high-throughput short read aligner Bowtie, and then analyzes the
mapping results to identify splice junctions between exons.

• Cuﬄinks4 Cuﬄinks assembles transcripts, estimates their abundances,
and tests for diﬀerential expression and regulation in RNA-Seq samples.
It accepts aligned RNA-Seq reads and assembles the alignments into
a parsimonious set of transcripts. Cuﬄinks then estimate the relative
abundances of these transcripts based on how many reads support each
one, taking into account biases in library preparation protocols.

25.2 Data Size and Format

RNA-Seq data can be presented in FASTA, FASTQ, and many other formats
(like BAM format). The TopHat package handles FASTA and FASTQ data
formats. How big is an RNA-Seq data? Each sample of RNA-Seq data can
be from 20GB to 300GB of data (a single analysis of RNA-Seq can have up
to 500GB of data).

25.3 MapReduce Solution

RNA-Sequencing pipeline includes the following main steps:

• Input data validation (quality control of input data such as FASTQ

ﬁles)

• Alignment (mapping of short reads to the reference genome)

• Assemble transcripts (using Cufflink and Cuffdiff tools)

RNA-Seq workﬂow is presented below:

25.3.1

Input data validation

This step validates the format of FASTQ ﬁles. With validation, you want to
make sure that quality of input ﬁles are guaranteed. Input data validation
tools help to provide a way to do some quality control checks on raw sequence

4http://cufflinks.cbcb.umd.edu/

622

Figure 25.1: RNA-Seq WorkFlow

623

data (for example in FASTQ ﬁle format) coming from high throughput se-
quencing pipelines.

There are lots of open-source tools for input data validation. For example,

for FASTQ validation you may use the following open-source tools:

• FastQValidator (http://genome.sph.umich.edu/wiki/FastQValidator)

• FastQC (http://www.bioinformatics.babraham.ac.uk/projects/fastqc)

The input data validation step is very simple and straightforward and
we will not cover it here. Our focus will be on core of RNA-Sequencing,
on mapping/alignment and tests for diﬀerential expression and regulation in
RNA-Seq samples.

25.4 MapReduce Algorithms for RNA-Sequencing

Before we delve into MapReduce Algorithms for RNA-Sequencing, we need
to understand how data/samples are used in RNA-Seq analysis. To perform
an RNA-Seq analysis, we do need to compare two groups of RNA-Seq data
samples (this is a single comparison; an RNA-Seq analysis may have one or
more comparisons):

• Group-1: set of samples, where each sample may have one or more
FASTQ ﬁles. For example, this group might be set of ”normal” sam-
ples.

• Group-2: set of samples, where each sample may have one or more
FASTQ ﬁles. For example, this group might be set of ”cancer” (disease)
samples.

The goal is to ﬁnd signiﬁcant changes in transcript expression, splicing, and
promoter use between samples of Group-1 and Group-2 (typically, we will
use Cuﬄink’s Cuﬀdiﬀ program to perform RNA-Seq analysis between two
groups). Typically, an input to an RNA-Seq has one or more comparisons.
Each comparison has exactly two groups (Group-1 and Group-2, which are
discussed obove).

For example, the following is a sample input for RNA-Seq analysis. This
analysis has 3 comparisons (Comparison-1, Comparison-2, and Comparison-
3) and each comparison has exactly two groups: Group-1 and Group-2.

624

Comparison-1’s Group-1 has has 4 and Group-2 has 3 samples (sample data
for Comparison-2 and Comparison-3 are not shown here):

Comparison-1:

Group-1: {Sample-1, Sample-2, Sample-3, Sample-4}
Group-2: {Sample-7, Sample-8, sample-9}

where

Sample-1 = {file11.fastq, file12.fastq, file13.fastq}
Sample-2 = {file21.fastq, file22.fastq}
Sample-3 = {file31.fastq, file32.fastq, file33.fastq, file34.fastq}
Sample-4 = {file41.fastq}

Sample-7 = {file71.fastq, file72.fastq}
Sample-8 = {file81.fastq, file82.fastq, file83.fastq}
Sample-9 = {file91.fastq, file92.fastq, file93.fastq}

Comparison-2:

Group-1: {...}
Group-2: {...}

Comparison-3:

Group-1: {...}
Group-2: {...}

RNA-Seq data structures are presented below:

Input data for RNA-Seq can easily be represented by the following Java

class and data structures:

import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
import java.util.List;

625

Figure 25.2: RNA-Seq Data Structures

626

import java.util.ArrayList;

public class Comparison {

private Map<String, List<String>> group1 = null;
private Map<String, List<String>> group2 = null;
public void setGroup1(Map<String, List<String>> group1) {

this.group1 = group1;

}
public void setGroup2(Map<String, List<String>> group2) {

this.group2 = group2;

}
public Map<String, List<String>> getGroup1() {

return this.group1;

}
public Map<String, List<String>> getGroup2() {

return this.group2;

}

}

Now we may use the Comparison class to create proper RNA-Seq data

structures:

// create all 3 comparisons:
List<Comparison> comparisons = new ArrayList<Comparison>();
Comparison comparison_1 = new Comparison();
Comparison comparison_2 = new Comparison();
Comparison comparison_3 = new Comparison();
comparisons.add(comparison_1);
comparisons.add(comparison_2);
comparisons.add(comparison_3);

// prepare Group-1 for comparison_1
Map<String, List<String>> group1 = new HashMap<String, List<String>>()
group1.put("Sample-1", new ArrayList<String>(

Arrays.asList("file11.fastq", "file12.fastq", "file13.fastq")));

group1.put("Sample-2", new ArrayList<String>(

627

Arrays.asList("file21.fastq", "file22.fastq")));

group1.put("Sample-3", new ArrayList<String>(

Arrays.asList("file31.fastq", "file32.fastq", "file33.fastq", "file34.fastq")));

group1.put("Sample-4", new ArrayList<String>(Arrays.asList("file41.fastq")));

// prepare Group-2 for comparison_1
Map<String, List<String>> group2 = new HashMap<String, List<String>>()
group2.put("Sample-7", new ArrayList<String>(

Arrays.asList("file71.fastq", "file72.fastq")));

group2.put("Sample-8", new ArrayList<String>(

Arrays.asList("file81.fastq", "file82.fastq", "file83.fastq")));

group2.put("Sample-9", new ArrayList<String>(

Arrays.asList("file91.fastq", "file92.fastq", "file93.fastq")));

comparison_1.setGroup1(group1);
comparison_1.setGroup2(group2);
...

We further split the <filename>.fastq ﬁles (using Linux’s split function)
into 8 million records (exactly 2 million FASTQ records, since each 4 lines
is one FASTQ record). The reason for this split is to make sure that every
mapper will get fair share of input records.

Our solution for RNA-Seq analysis has 2 MapReduce algorithm steps:

• STEP-1: MapReduce Tophat mapping

• STEP-2: MapReduce Cuﬀdiﬀ Calling

25.4.1 STEP-1: MapReduce Tophat mapping

This step is comprised on a map() and reduce() functions: the mapper uses
Tophat to align input data and then reducers concatenate the output of
mappers.

The driver program for STEP-1, partitions data into small chunks and
passes each input ﬁle to a mapper. For example, an input for an RNA-Seq
might be the HDFS directory: /rnaseq/input/2397/ (2397 is an analysisID,
which uniquely identiﬁes each RNA Seq. analysis) where

628

# hadoop fs -ls /rnaseq/input/2397/
0000.txt
0001.txt
0002.txt
..
0090.txt
0091.txt

Each input ﬁle has one single record comprised of many tokens: (NOTE:
since each record is too long, it is formatted – each line contains one token
with delimiter of ”;”):

# hadoop fs -cat /rnaseq/input/2397/0090.txt
0090;
# counter
g1_vs_g2;
# comparison ID
10332;
# group ID
62586;
# sample ID
annotation;
# RNA seq input type
2397;
# GUID as analysis ID
2;
# segment mismatches
fr-unstranded;
# library type
55;
# segment length
Refseq;
# gene model
# reference genome
hg18;
/data/GSE29006/SRR192334_1_0026, # paired left file
/data/GSE29006/SRR192334_2_0026 # paired right file

25.4.1.1 The map() function

The map() function calls a BASH shell script5, which apply Tophat and
generate intermediate BAM ﬁles. The output of each Tophat mapper will be

5 For generating shell scripts we used FreeMarker. FreeMarker is a ”template engine”; a
generic tool to generate text output (anything from HTML to autogenerated source code)
based on templates. It’s a Java package, a class library for Java programmers. It’s not an
application for end-users in itself, but something that programmers can embed into their
products (source: http://freemarker.sourceforge.net/

629

an accepted hits.bam ﬁle, which is a list of read alignments in SAM format.
SAM is a compact short read alignment format that has been increasingly
adopted.

Listing 25.1: STEP-1: map()

1 // key is MR generated, ignored here.
2 // value: represents one record of input
3 map(key, value) {

"<analysis_id><;><comparison_id><;><group_id><;><sample_id>"

Map<String, String> tokens = tokenizeMapperRecord(value);
// The reducer key will be:
//
String reducerKey = getReducerKey(tokens);
RNASeq.tophat(tokens);
emit(reducerKey, value);

4

5

6

7

8

9
10 }

11
12 public static void tophat(Map<String, String> tokens)

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

throws Exception {
TemplateEngine.init();
Map<String, String> templateMap = new HashMap<String, String>();
templateMap.put("key", tokens.get("counter"));
templateMap.put("counter", tokens.get("counter"));
templateMap.put("comparison_id", tokens.get("comparison_id"));
templateMap.put("group_id", tokens.get("group_id"));
templateMap.put("sample_id", tokens.get("sample_id"));
templateMap.put("rna_seq_input_type", tokens.get("rna_seq_input_type"));
templateMap.put("analysis_id", tokens.get("analysis_id"));
templateMap.put("rna_seq_tophat_segment_mismatches",
tokens.get("rna_seq_tophat_segment_mismatches"));

templateMap.put("rna_seq_tophat_library_type",
tokens.get("rna_seq_tophat_library_type"));
templateMap.put("rna_seq_tophat_segment_length",
tokens.get("rna_seq_tophat_segment_length"));

templateMap.put("rna_seq_tophat_gene_model",
tokens.get("rna_seq_tophat_gene_model"));

templateMap.put("rna_seq_tophat_reference_genome",
tokens.get("rna_seq_tophat_reference_genome"));

630

33

34

35

36

37

38

39

40

41

// create the actual script from a template file
String scriptFileName = "/rnaseq/scripts/tophat." +

tokens.get("analysis_id") + "." + tokens.get("counter") + ".sh";

String logFileName = "/rnaseq/logs/tophat." +

tokens.get("analysis_id") + "." + tokens.get("counter") + ".log";

File scriptFile = TemplateEngine.createDynamicContentAsFile("tophat.template",

templateMap, scriptFileName);

if (scriptFile != null) {

ShellScriptUtil.callProcess(scriptFileName, logFileName);

}

42
43 }

25.4.1.2 The reduce() Function

The reduce() Function calls a BASH shell script, which uses samtools’ cat
function to concatenate accepted hits (accepted hits.bam) BAM ﬁles. Then
the script uses samtools’ sort function to generate sorted BAM ﬁle. So
for our example, for Comparison-1, the reducers will generate the following
sorted BAM ﬁles in HDFS:

/<hdfs-dir>/${analysis_id}/comparison_1/group_1/sample_1/reducer/sorted.bam
/<hdfs-dir>/${analysis_id}/comparison_1/group_1/sample_2/reducer/sorted.bam
/<hdfs-dir>/${analysis_id}/comparison_1/group_1/sample_3/reducer/sorted.bam
/<hdfs-dir>/${analysis_id}/comparison_1/group_1/sample_4/reducer/sorted.bam

/<hdfs-dir>/${analysis_id}/comparison_1/group_2/sample_7/reducer/sorted.bam
/<hdfs-dir>/${analysis_id}/comparison_1/group_2/sample_8/reducer/sorted.bam
/<hdfs-dir>/${analysis_id}/comparison_1/group_2/sample_9/reducer/sorted.bam

The reducer is deﬁned as:

Listing 25.2: STEP-1: reduce()

1 // key as : "<analysis_id><;><comparison_id><;><group_id><;><sample_id>"
2 // values: not used
3 reduce(key, values) {

631

RNASeqTophat.catenatePartitionedBamFiles(key);
emit(key, key);

4

5
6 }

7
8 /**
9 * This method catenates small/partitioned accepted_hits.bam files
10 * and creates a single sorted.bam file.
11 * @param key as : "<analysis_id><;><comparison_id><;><group_id><;><sample_id>"
12 */
13 public static void catenatePartitionedBamFiles(String key) {

throws Exception {
TemplateEngine.init();
// split the key (fields are separated by ";")
String[] tokens = reducerKey.split(";");
String analysisID = tokens[0];
String comparisonID = tokens[1];
String groupID = tokens[2];
String sampleID = tokens[3];
// create a template map to be passes tp FreeMarker template
Map<String, String> templateMap = new HashMap<String, String>();
templateMap.put("analysis_id", analysisID);
templateMap.put("comparison_id", comparisonID);
templateMap.put("group_id", groupID);
templateMap.put("sample_id", sampleID);

// create the actual script from a template file
String scriptFileName = "/rnaseq/scripts/catenate_partitioned_bam_files." +

analysisID + "." + comparisonID + "." + groupID + "." + sampleID + ".sh";

String logFileName = "/rnaseq/scripts/catenate_partitioned_bam_files." +

analysisID + "." + comparisonID + "." + groupID + "." + sampleID + ".log";

File scriptFile = TemplateEngine.createDynamicContentAsFile(

"cat_bam_files_partitioned.template.sh", templateMap, scriptFileName);

if (scriptFile != null) {

ShellScriptUtil.callProcess(scriptFileName, logFileName);

}

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 }

632

25.4.2 STEP-2: MapReduce Calling Cuﬀdiﬀ

This step is comprised on a map() and reduce() functions (the reducer is
optional – may be used for further analysis). The mapper calls cuffdiff
function for two groups for any given comparison, and then reducers generate
the ﬁnal desired output as a bioset/biomarker for further analysis.

25.4.2.1 map() function

The mapper will call cuﬀdiﬀ function for every comparison (in our example,
we have 3 comarisons, so cuﬀdiﬀ will be called 3 times). For example, for
Comparison-1, cuﬀdiﬀ will be called as:

group_1= {
/<hdfs-dir>/${analysis_id}/comparison_1/group_1/sample_1/reducer/sorted.bam
/<hdfs-dir>/${analysis_id}/comparison_1/group_1/sample_2/reducer/sorted.bam
/<hdfs-dir>/${analysis_id}/comparison_1/group_1/sample_3/reducer/sorted.bam
/<hdfs-dir>/${analysis_id}/comparison_1/group_1/sample_4/reducer/sorted.bam
}

group_2= {
/<hdfs-dir>/${analysis_id}/comparison_1/group_2/sample_7/reducer/sorted.bam
/<hdfs-dir>/${analysis_id}/comparison_1/group_2/sample_8/reducer/sorted.bam
/<hdfs-dir>/${analysis_id}/comparison_1/group_2/sample_9/reducer/sorted.bam
}

cuffdiff $group_1 $group_2

Cuﬀdiﬀ generates the following output ﬁles, which will be saved in HDFS:

• isoform_exp.diff

• isoforms.read_group_tracking

• read_groups.info

The mapper for STEP-2 is presented below:

Listing 25.3: STEP-2: map()

633

1 /**
2 * The mapper performs cuffdiff function for two groups of data.
3 *
4 * @param key will be: "<analysis_id><;><comparison_id><;><group_id><;><sample_id>"
5 * @param value is a String of 11 tokens:
6 * index content
7 * ---- ---------
8 *
9 *
10 *
11 *
12 *
13 *
14 *
15 *
16 *
17 *
18 *
19 *
20 */
21 map(key, value){

<counter-as-key>; (such as 0000, 0001, )
<comparison_id>;
<group1_id>;
<group2_id>;
constant "cuffdiff"; (ignored)
<analysis_id>;
<segment_mismatches>;
<library_type>;
<segment_length>;
<gene_model>;
<reference_genome>;

0
1
2
3
4
5
6
7
8
9
10

reducerKey =

Map<String, String> tokens = tokenizeMapperRecord(value);
//
String reducerKey = getReducerKey(tokens);
RNASeqCuffDiff.cuffdiff(tokens);
emit(reducerKey, value);

<analysis_id><;><comparison_id>

22

23

24

25

26
27 }

28

29 public static void cuffdiff(Map<String, String> tokens) throws Exception {

30

31

32

33

34

35

36

37

TemplateEngine.init();
String scriptFileName = "/rnaseq/scripts/run_cuffdiff." +

tokens.get("analysis_id") + "." + tokens.get("comparison_id") + ".sh";

String logFileName = "/rnaseq/logs/run_cuffdiff." +

tokens.get("analysis_id") + "." + tokens.get("comparison_id") + ".log";

File scriptFile = TemplateEngine.createDynamicContentAsFile("cuffdiff.sh.template",

tokens, scriptFileName);

if (scriptFile != null) {

634

ShellScriptUtil.callProcess(scriptFileName, logFileName);

38

39
40 }

}

25.4.2.2

reduce() function

There is no reducer for the STEP-2. But, reducers may be used to read the
output of cuffdiff function and generate biosets/biomarkers, which can be
used in further analysis and evaluation of RNA-Seq samples.

635

Chapter 26

Gene Aggregation

26.1

Introduction

This chapter provides a MapReduce solution to gene aggregation. We provide
two distinct solutions in MapReduce/Hadoop and MapReduce/Spark. The
input data for gene aggregation are patients biosets. A bioset, also called gene
signatures, encompass data in the form of experimental sample comparisons
(for transcriptomic, epigenetic, and copy number variation data), as well as
genotype signatures (for GWAS and mutational data). In simple terms, a
bioset is a list of (key, value) pairs, where key is a GENE-ID and value is a
list of associated attributes. Gene aggregation is used in clinical applications
to identify transcriptional signaturres and patterns of gene expression data.
Also, gene aggregation is used to see how genes are grouped together into
sets of genes and how this aﬀects the overall analysis. It is proven that gene
aggregation is an evolutionarily method and depends on chromosomal folding
and higher-order structures.

Gene aggregation is acheived by using three metrics:

• Rreference Type refers to type of patient data and they are:

r1=normal

r2=disease

r3=paired

r4=unknown

636

• Gene Filter Type refers to type of ﬁlter applied to the data. The
ﬁlter type indicates how gene values to be grouped and analyzed. For
example, if a ﬁlter type is ”up”, then only gene values which are greater
than (has ”up” value) a Filter Value Threshold will be considered for
further analysis. There are 3 gene ﬁlter types:

"absolute value (abs)"

"greater than (up)"

"less than (down)"

• Filter Value Threshold used by Gene Filter Type to exclude the

genes, which does not satisfy the threshold value).

Each bioset belong to a patient identiﬁed by a ”patient ID”. Given a set of
biosts (in thousands and tens of thousands), where a bioset may have up to
50,000 genes, we want to ﬁnd frequency of each gene which satisﬁes three
metrics: (1) ”reference type”, (2) ”gene ﬁlter type”, and (3) ”ﬁlter value
threshold”. Filter type indicates how (should we use absolute value, greater
than or less than operator) the gene value should be compared to the ”ﬁlter
value threshold”. The number of genes per bioset depends on the bioset data
type – bioset data types are ”copy number variation”, ”gene expression”,
”methylation”, and ”somatic mutation”). Before we delve into MapReduce
algorithm for gene aggregation, we discuss the input/output data.

26.2

Input

Each bioset may have 20,000 to 50,000 records and each record will have the
following format (patients are identiﬁed by p100 and p200):

format:

<geneID><,><referenceType><;><patientID><,><geneValue>

example-1:

7562135,r1;p100,1.04

example-2:

7570769,r1;p200,-1.09

637

26.3 Output

The goal of Gene Aggregation is to ﬁnd frequency of each gene along with
its reference type (r1, r2, r3, r4). The MapReduce solution will generate the
following output format in MapReduce’s distributed ﬁle system (for example,
Hadoop’s distributed ﬁle system):

format:

<geneID><,><referenceType><TAB><frequency-count>

example-1:

7562135,r1

1205

example-2:

7570769,r3

14067

Eventually, this output can be read into a Java object such as GeneAggregationFrequencyCount

, which will be discussed in Analysis of Output section.

26.4 MapReduce Solution

The question in gene aggregation algorithm is this: per patient, do we ﬁlter
by ”individual gene values” (patient ID is ignored) or by an ”average of gene
values” (patient ID is used). For example, if we have 10 values for GENE-1
(using real data, the number of values per geneID can be in thousands –
to understand algorithms, I use a toy data) for three patients (identiﬁed by
p100, p200, p300) with ”reference type” of ”r1”, ”gene ﬁlter type” as ”up”,
and ”ﬁlter value threshold” equal to 1.04,

GENE-1,r1;p100,1.00
GENE-1,r1;p100,1.06
GENE-1,r1;p100,1.10
GENE-1,r1;p100,1.20

GENE-1,r1;p200,1.00
GENE-1,r1;p200,1.02
GENE-1,r1;p200,1.04

GENE-1,r1;p300,1.01

638

GENE-1,r1;p300,1.06
GENE-1,r1;p300,1.08

Then we will get the following diﬀerent values (based on whether we ﬁlter
by ”individual gene values” or by ”average of gene values”:

• Filter by ”individual gene values”: this will produce the following out-

put:

GENE-1,r1

6

since only 6 records’ gene values are greater than or equal to 1.04,
which pass the ﬁlter.

• Filter by ”average of gene values”: this will produce the following out-

put:

GENE-1,r1

2

since average of values ( 1.00+1.06+1.10+1.20
) for patient p100 is
1.09, which is greater than 1.04 (passes the ﬁlter), average of values
(1.00+1.02+1.04
) for patient p200 is 1.02 (which does not pass the ﬁl-
3
ter), and average of values ( 1.01+1.06+1.08
) for patient p300 is 1.05
(which passes the ﬁlter). Therefore only two patients passed the test
by average, so the frequency will be 2.

3

4

We provide two distinct MapReduce solutions, which handles ﬁlter by ”indi-
vidual gene values” as well as ﬁlter by ”average of gene values”.

How will we pass these three dynamic parameters (”reference type”, ”gene
ﬁlter type”, and ”ﬁlter value threshold”) from MapReduce driver to map()
and reduce() functions. Using MapReduce/Hadoop Configuration ob-
ject, we can set these values by Configurtion.set() and retrieve them (by
Configurtion.get()) in the setup() function of map() or reduce().

639

The mapper gets one record of a bioset and tokenizes the input into a
<geneID><,><referenceType> and geneValue. If <geneID><,><referenceType>
contains the desired ”reference type”, then we check the geneValue to see if
it satisﬁes the ”ﬁlter value threshold”. If both conditions are satisﬁed, then
we emit (key, value) where key is the <geneID><,><referenceType> and the
value is an integer 1 (one). The reducer sums up the frequencies for a spe-
ciﬁc <geneID><,><referenceType> and emits (key, value), where key is the
<geneID><,><referenceType> and the value is the ”ﬁnal frequency count”.

26.4.1 Mapper: Filter by Individual

The mapper’s setup() will retrieve the desired parameters (metrics needed
for gene aggregation) to be used in the map() function.

Listing 26.1: Gene Aggregator’s mapper setup() Function

1 public class GeneAggregatorMapperByIndividual ... {
2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

private String referenceType = null;
private String filterType = null;
private double filterValueThreshold;

/**

* will be run only once
*/

public void setup(Context context) {

Configuration conf = context.getConfiguration();
this.referenceType = conf.get("gene.reference.type");
this.filterType = conf.get("gene.filter.type");
this.filterValueThreshold =

Double.parseDouble(conf.get("gene.filter.value.threshold"));

}

Listing 26.2: Gene Aggregator’s mapper map() Function

1 /**
2

3

4

8

9

10

11

12

* @param key is the key generated by MapReduce partitioner (ignored here)
* @param value is one record of bioset as:
*
*/

<geneID><,><referenceType><;><patientID><,><geneValue>

5
6 map(Long key, String value) {
7

String[] tokens = StringUtil.split(value, ";");
String geneIDAndReferenceType = tokens[0];
String patientIDAndGeneValue = tokens[1];
String[] val = StringUtil.split(patientIDAndGeneValue, ",");
// val[0] = patientID
// val[1] = geneValue

640

13

14

15

16

17

18

19

20

21

22

23

24

25

double geneValue = Double.parseDouble(val[1]);

String[] arr = StringUtil.split(geneIDAndReferenceType, ",");
// arr[0] = geneID
// arr[1] = referenceType
// check referenceType
if (arr[1].equals(this.referenceType)) {

if (checkFilter(geneValue)) {

// then create a counter for reducer,
// otherwise nothing will be written
// prepare key-value for reducer and send it to reducer
emit(geneIDAndReferenceType, 1);

}

}

26
27 }

Listing 26.3: Gene Aggregator’s checkFilter() Function

1 public boolean checkFilter(double value) {
2

if (filterType.equals("abs")) {

if (Math.abs(value) >= this.filterValueThreshold) {

return true;

}
else {

return false;

}

}
if (filterType.equals("up")) {

if (value >= this.filterValueThreshold) {

return true;

}
else {

return false;

}

}
if (filterType.equals("down")) {

if (value <= this.filterValueThreshold) {

return true;

}
else {

return false;

}

}
return false;

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 }

Since f ilterT ype is passed from MapReduce driver to map(), therefore
we know the value of f ilterT ype before any map() starts. For this reason,
in our Mapreduce/Hadoop implementation, we will provide custom mappers
(to avoid the if-statement so many times per map()). Note that in our
MapReduce solution, for readability purposes, we have avoided all excepton

641

checking and handling.

26.4.2 Reducer: Filter by Individual

Reducer will recieve a (key, List < integer >) where key is the unique ge-
neAndReferenceType and List < integer > is a partial frequencies of the
unique geneAndReferenceAsString.

The reducer job is to sum up the number of occurances of unique gene-

AndReferenceType.

Here is the reduce() function:

Listing 26.4: Gene Aggregator’s reduce() Function

* @param key is the unique geneAndReferenceAsString generated by he mapper
* @param values is a list of integers
*
*/

(partial count of a unique geneIDAndReferenceType)

5
6 reduce(String key, List<Integer> values) {
7

int sum = 0;
for (int count : values) {

1 /**
2

3

4

8

9

10

11
12 }

sum += count;

}
emit(key, sum);

26.4.3 Mapper: Filter by Average

The mapper’s setup() will retrieve the desired parameters (metrics needed
for gene aggregation) to be used in the map() function. since we are ﬁltering
by average of gene values per patient, we have to pass the patient IDs along
the gene values to reducers.

Listing 26.5: Gene Aggregator’s mapper setup() Function

1 public class GeneAggregatorMapperByIndividual ... {
2

3

4

5

6

7

8

9

private String referenceType = null;
private String filterType = null;
private double filterValueThreshold;

/**

* will be run only once
*/

10

public void setup(Context context) {

642

11

12

13

14

15

16

}

Configuration conf = context.getConfiguration();
this.referenceType = conf.get("gene.reference.type");
this.filterType = conf.get("gene.filter.type");
this.filterValueThreshold =

Double.parseDouble(conf.get("gene.filter.value.threshold"));

Listing 26.6: Gene Aggregator’s mapper map() Function

1 /**
2

3

4

8

9

10

11

12

13

14

15

16

17

* @param key is the key generated by MapReduce partitioner (ignored here)
* @param value is one record of bioset as:
*
*/

<geneID><,><referenceType><;><patientID><,><geneValue>

5
6 map(Long key, String value) {
7

String[] tokens = StringUtil.split(value, ";");
String geneIDAndReferenceType = tokens[0];
String patientIDAndGeneValue = tokens[1];

String[] arr = StringUtil.split(geneIDAndReferenceType, ",");
// arr[0] = geneID
// arr[1] = referenceType
// check referenceType
if (arr[1].equals(this.referenceType)) {

// prepare key-value for reducer and send it to reducer
emit(geneIDAndReferenceType, patientIDAndGeneValue);

}

18
19 }

Since f ilterT ype is passed from MapReduce driver to map(), therefore
we know the value of f ilterT ype before any map() starts. For this reason,
in our Mapreduce/Hadoop implementation, we will provide custom mappers
(to avoid the if-statement so many times per map()). Note that in our
MapReduce solution, for readability purposes, we have avoided all excepton
checking and handling.

26.4.4 Reducer: Filter by Average

Reducer will recieve a (K, List < V >) where K is the unique geneIDAn-
dReferenceType and V is a patientIDAndGeneValue.

The reducer job is to sum up the number of occurances of unique geneI-

DAndReferenceType by ﬁltering average of gene values.

Here is the reduce() function:

643

Listing 26.7: Gene Aggregator’s reduce() Function

1 /**
2

3

7

8

9

10

11

12

13

14

15
16 }

* @param key is the unique geneIDAndReferenceType generated by mappers
* @param values is a List<V> and V is a patientIDAndGeneValue
*/

4
5 reduce(String key, List<String> values) {
6

Map<String, Tuple2<Double,Integer>> patients =
GeneAggregatorUtil.buildPatientsMap(values);

int passedTheTest = GeneAggregatorUtil.getNumberOfPatientsPassedTheTest(

patients,
this.filterType,
this.filterValueThreshold

);

// emit the output of reducer
emit(key, passedTheTest);

26.5 Computing Gene Aggregation

Computing gene aggregation is handled by a utility class called GeneAggregatorUtil.
This class has two static methods:

• buildPatientsMap(): this method accepts a List<Tuple2<patientID, geneValue>>

and builds a Map<patientID, sumOfGeneValues>.

• getNumberOfPatientsPassedTheTest(): counts to see how many pa-
tients passed the test (satisﬁed the ﬁlter criteria). This is achieved by
examining each entry of Map built by buildPatientsMap() method.

Also, we use a simple class PairOfDoubleInteger to represent a Tuple2<Double, Integer>

and be able to update its values.

Listing 26.8: GeneAggregatorUtil.buildPatientsMap()

/**

* GeneAggregatorUtil.buildPatientsMap() method:
*
* @param values = List<Tuple2<patientID, geneValue>>
*
* THE RESULT Map:
*
*
*
*
*

where D = sum of values for the patientID
I = number of values (counter)

make sure we do not count more than once for the same patient
patients.key = patientID
patients.value = Tuple2<D, I>

644

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

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

*/

public static Map<String, PairOfDoubleInteger> buildPatientsMap(Iterable<Text> values)

throws IOException, InterruptedException {
Map<String, PairOfDoubleInteger> patients = new HashMap<String, PairOfDoubleInteger>();
for (Text patientIdAndGeneValue : values) {

String[] tokens = StringUtils.split(patientIdAndGeneValue.toString(), ",");
String patientID = tokens[0];
//tokens[1] = geneValue
double geneValue = Double.parseDouble(tokens[1]);
PairOfDoubleInteger pair = patients.get(patientID);
if (pair == null) {

pair = new PairOfDoubleInteger(geneValue, 1);
patients.put(patientID, pair);

}
else {

pair.increment(geneValue);

}

}

return patients;

}

Listing 26.9: GeneAggregatorUtil.getNumberOfPatientsPassedTheTest()

/**

* GeneAggregatorUtil.getNumberOfPatientsPassedTheTest() method:
*/

public static int getNumberOfPatientsPassedTheTest(

Map<String, PairOfDoubleInteger> patients,
double filterValue,
String filterType) { // filterType = {"up", "down", "abs"}

if (patients == null) {

return 0;

}

// now, we will average the values and see which patient passes the threshhold
int passedTheTest = 0;
for (Map.Entry<String, PairOfDoubleInteger> entry : patients.entrySet()) {

//String patientID = entry.getKey();
PairOfDoubleInteger pair = entry.getValue();
double avg = pair.avg();
if (filterType.equals("up")) {

if (avg >= filterValue) {

passedTheTest++;

}

}
if (filterType.equals("down")) {
if (avg <= filterValue) {

passedTheTest++;

}

}
else if (filterType.equals("abs")) {

if (Math.abs(avg) >= filterValue) {

passedTheTest++;

645

}

}

}

return passedTheTest;

31

32

33

34

35

}

36
37 }

26.6 Hadoop Implementation

We have a simple MapReduce solution for Gene Aggregation. The following
classes are used to implement the MapReduce solution in Hadoop.

• GeneAggregationDriverByIndividual: a driver for setting input/output

and launching the job

• GeneAggregationMapperByIndividual: a mapper to ﬁlter by individula

values

• GeneAggregationReducerByIndividual: a reducer to to ﬁlter by indi-

vidula values

• GeneAggregationDriverByAvergae: a driver for setting input/output

and launching the job

• GeneAggregationMapperByAvergae: a mapper to ﬁlter by avergae of

values

• GeneAggregationReducerByAverage: a reducer to to ﬁlter by avergae

of values

In order to achieve better performance, it is better to have a separate
classes for handling ﬁlter type (”up”, ”down”, ”abs”). Therefore, GeneAg-
gregationMapperByIndividual can be replaced by three plug-in classes:

• GeneAggregationMapperByIndividualUP: when ﬁlterType = ”up”

• GeneAggregationMapperByIndividualDOWN when ﬁlterType = ”down”

• GeneAggregationMapperByIndividualABS: when ﬁlterType = ”abs”

646

Note that for performance eﬃcieny purposes, we provided three mappers (one
for each ”gene ﬁlter type”). This enables us to avoid ”gene ﬁlter type” check-
ing by an if-statement. For example, if we ar processing 20,000 biosets and
each bioset has over 40,000 geneIDs, then we have avoided executing/calling
800 million non-needed if-statement.

Also, GeneAggregationReducerByAverage reducer calss can be optimized

by three plug-in classes:

• GeneAggregationReducerByAverageUP: when ﬁlterType = ”up”

• GeneAggregationReducerByAverageDOWN when ﬁlterType = ”down”

• GeneAggregationReducerByAverageABS: when ﬁlterType = ”abs”

Similar to plug-in mapper cclasses, custom plug-in reducers avoid unnec-

essary if-statement checks millions to times.

We set the plug-in mapper classes in the driver classes when we check

gene-values individually:

Listing 26.10: GeneAggregationDriverByIndividual Class

1 public class GeneAggregationDriverByIndividual extends Configured implements Tool {
2

String filterType = ...;

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

public int run(String[] args) throws Exception {

Job job = ...;
...
// set the optimized mapper class
if (filterType.equals("up")) {

job.setMapper(GeneAggregationMapperByIndividualUP.class);

else if (filterType.equals("down")) {

job.setMapper(GeneAggregationMapperByIndividualDOWN.class);

}
else if (filterType.equals("abs")) {

job.setMapper(GeneAggregationMapperByIndividualABS.class);

}
else {

throw new Exception("filterType is undefined");

}

// set the reducer class
job.setReducer(GeneAggregationReducerByIndividualDOWN.class);
...

}

23
24 }

We set the plug-in reducer classes in the driver classes when we check

gene-values by average:

647

Listing 26.11: GeneAggregationDriverByAverage Class

1 public class GeneAggregationDriverByAverage extends Configured implements Tool {
2

String filterType = ...;

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

public int run(String[] args) throws Exception {

Job job = ...;
...
// set the mapper class
job.setMapper(GeneAggregationMapperByAverage.class);

// set the optimized reducer class
if (filterType.equals("up")) {

job.setReducer(GeneAggregationReducerByAverageUP.class);

else if (filterType.equals("down")) {

job.setReducer(GeneAggregationReducerByAverageDOWN.class);

}
else if (filterType.equals("abs")) {

job.setReducer(GeneAggregationReducerByAverageABS.class);

}
else {

throw new Exception("filterType is undefined");

}
...

}

23
24 }

Therefore, the optimized set of implementation classes will be:

• GeneAggregationDriverByIndividual: a driver for setting input/output

and launching the job

• GeneAggregationMapperByIndividualUP: a mapper to ﬁlter by indi-

vidula values

• GeneAggregationMapperByIndividualDOWN: a mapper to ﬁlter by in-

dividula values

• GeneAggregationMapperByIndividualABS: a mapper to ﬁlter by indi-

vidula values

• GeneAggregationReducerByIndividual: a reducer to to ﬁlter by indi-

vidula values

• GeneAggregationDriverByAverage: a driver for setting input/output

and launching the job

• GeneAggregationMapperByAverage: a mapper to ﬁlter by average val-

ues

648

• GeneAggregationReducerByAverageUP: a reducer to to ﬁlter by aver-

age of values

• GeneAggregationReducerByAverageDOWN: a reducer to to ﬁlter by

average of values

• GeneAggregationReducerByAverageABS: a reducer to to ﬁlter by av-

erage of values

Therefore the checkFilter() method is broken down into 3 segments
(one segment per mapper class). Since we have a custom plug-in mapper
class per ﬁlterType, the if-statement(s) are dropped. Now, each mapper
class knows what is the exact ﬁlterType value.

Listing 26.12: checkFilter()

for GeneAggregationMapperByIndividualUP

Class

1 // GeneAggregationMapperByIndividualUP class:
2 public boolean checkFilter(double value) {
3

//if (filterType.equals("up")) {

if (value >= this.filterValueThreshold) {

return true;

}
else {

return false;

}

//}

4

5

6

7

8

9

10
11 }

Listing 26.13: checkFilter() for GeneAggregationMapperByIndividualDOWN

Class

1 // GeneAggregationMapperByIndividualDOWN class:
2 public boolean checkFilter(double value) {
//if (filterType.equals("down")) {
3

if (value <= this.filterValueThreshold) {

return true;

}
else {

return false;

}

//}

4

5

6

7

8

9

10
11 }

Listing 26.14: checkFilter()

for GeneAggregationMapperByIndividualABS

Class

649

1 // GeneAggregationMapperByIndividualABS class:
2 public boolean checkFilter(double value) {
//if (filterType.equals("abs")) {
3

if (Math.abs(value) >= this.filterValueThreshold) {

return true;

}
else {

return false;

}

//}

4

5

6

7

8

9

10
11 }

26.7 Analysis of Output

The output (saved in Hadoop’s HDFS system as a SequenceFile – (key,value)
as a binary data) of our MapReduce/Hadoop solution will have the following
format:

format:

<geneID><,><referenceType><TAB><frequency-count>

example-1:

7562135,r1

1205

example-2:

7570769,r1

14067

We can easily read these output ﬁles and pass the values into Java objects.

public interface FrequencyItem {

public Integer getGeneId();
public void setGeneId(Integer id);

public Integer getFrequency();
public void setFrequency(Integer frequency);

public String getReferenceType();
public void setReferenceType(String referenceType);

public String toString();

}

650

Then we invoke the following, where dir is the Hadoop output path:

List<FrequencyItem> list = readDirectoryIntoFrequencyItem(dir);

The GeneAggregatorAnalyzerUsingFrequencyItem class is deﬁned as:

/**

* This class analyzes output directory of Hadoop distributed file system (HDFS)
* and returns the result as a List<FrequencyItem> object.
*
* @author Mahmoud Parsian
*
*/

public class GeneAggregatorAnalyzerUsingFrequencyItem {

static List<FrequencyItem> readDirectoryIntoFrequencyItem(String pathAsString) {

return readDirectoryIntoFrequencyItem(new Path(pathAsString));

}

static List<FrequencyItem> readDirectoryIntoFrequencyItem(Path path) {

FileSystem fs = null;
try {

fs = FileSystem.get(new Configuration());

}
catch (IOException e) {

THE_LOGGER.error("Unable to access the hadoop file system!", e);
throw new RuntimeException("Unable to access the hadoop file system!");

}

List<FrequencyItem> list = new ArrayList<FrequencyItem>();
try {

FileStatus[] status = fs.listStatus(path);
for (int i = 0; i < status.length; ++i) {
Path hdfsFile = status[i].getPath();
if (hdfsFile.getName().startsWith("part")) {

List<FrequencyItem> pairs = readFileIntoFrequencyItem(hdfsFile, fs);

651

list.addAll(pairs);

}

}

}
catch (IOException e) {

THE_LOGGER.error("Unable to access the hadoop file system!", e);
throw new RuntimeException("Error reading the hadoop file system!");

}

return list;

}

@SuppressWarnings("unchecked")
public static List<FrequencyItem> readFileIntoFrequencyItem(Path path, FileSystem fs) {

List<FrequencyItem> list = new ArrayList<FrequencyItem>();
SequenceFile.Reader reader = null;
try {

reader = new SequenceFile.Reader(fs, path, fs.getConf());

Text key = (Text) reader.getKeyClass().newInstance();
IntWritable value = (IntWritable) reader.getValueClass().newInstance();

while (reader.next(key, value)) {

list.add(createFrequencyItem(key, value));
key = (Text) reader.getKeyClass().newInstance();
value = (IntWritable) reader.getValueClass().newInstance();

}

}
catch (Exception e) {

THE_LOGGER.error("Error reading SequenceFile " + path, e);
throw new RuntimeException("Error reading SequenceFile " + path);

}
finally {

closeAndIgnoreException(reader);

}

return list;

}

652

private static FrequencyItem createFrequencyItem(Text key, IntWritable frequency) {

// key = <geneID><,><referenceType> where referenceType in {r1, r2, r3, r4}
// value = integer
if (key == null) {
return null;

}
String geneIDAndReference = key.toString();
String[] tokens = StringUtils.split(geneIDAndReference, ",");
String geneID = tokens[0];
String referenceType = tokens[0];
FrequencyItem item = FrequencyItemFactory.createFrequencyItem(geneID, referenceType, frequency.get());
return item;

}

static void closeAndIgnoreException(SequenceFile.Reader reader) {

if (reader == null) {

return;

}

try {

reader.close();

}
catch(Exception ignore) {

THE_LOGGER.error("Error closing SequenceFile.Reader.", ignore);

}

}

public static void main(String[] args) throws Exception {

//test1(args);
Path path = new Path(args[0]);
List<FrequencyItem> list = readDirectoryIntoFrequencyItem(path);
THE_LOGGER.info("list="+list.toString());

}

}

653

26.8 Gene Aggregation in Spark

This section presents a MapReduce Spark solution for Gene Aggregation.
From HDFS input ﬁles, we will create RDDs and manipulate them in Spark.
Spark’s main data representation is an RDD, which enables parallel (such as
map(), reduce(), and groupByKey() functions) operations on the data. Spark
can read and save RDDs from many diﬀerent sources (including HDFS data
source). Another way to create RDDs are from Java collection objects.

Similar to hadoop silution, we provide two distict spark solutions for gene
aggregation (the entire Spark solution is presented in one Java driver class):

• Filter by ”individual gene values”: this is implmented
by the SparkGeneAggregationByIndividual class.

• Filter by ”average of gene values”: this is implmented

by the SparkGeneAggregationByAverage class.

26.9 Gene Aggregation in Spark: Filter by

Individual

The ﬁrst step is to create a JavaRDD<String> for all input biosets, where each
item of RDD will be a record of a bioset.The second step is to ﬁlter out the
values, which do not meet the Rreference Type and Filter Value Threshold
values. The third step will be to map RDD (generated by the second step)
items into JavaPairRDD<K,V>, where K is a <geneID><,><referenceType>
and V is an integer one (similar to the word count). The ﬁnal step will be
to group by K (as <geneID><,><referenceType>).

Sharing Data Between cluster Nodes

The question is how to pass the three metic values (referenceType, ﬁlter-
Type, and ﬁlterValueThreshold) to Spark’s actions and transformations for
manipulating RDDs? Spark provides Broadcast<T>1 class for sharing read-
1org.apache.spark.broadcast.Broadcast. Spark’s Broadcast variables allow the
programmer to keep a read-only variable cached on each cluster node rather than shipping
a copy of it with MapReduce tasks. Broadcast variables provide every cluster node a copy
of a input dataset in an eﬃcient manner. Spark attempts to distribute Broadcast variables
using eﬃcient broadcast algorithms to reduce communication cost.

654

only variables among all cluster nodes. Broadcast<T> variables allow the
programmer to keep a read-only variable cached on each cluster node rather
than shipping a copy of it with tasks. In MapReduce/Hadoop, sharing vari-
ables among mappers and reducers are accomplished by using the Hadoop’s
Configuration object. The driver class (which submits jobs to the MapRe-
duce framework), sets/deﬁnes shared variables and the map() or reduce() use
these shared variables. Sharing is achieved by mapper’s or reducer’s setup()
function, which is called once for each mapper or reducer.

In Spark, for our three metric values, we deﬁne three Broadcast objects
and when we need them for manipulating RDDs (using map and reduce
functions), we read them. This is how to deﬁne Broadcast objects

JavaSparkContext ctx = createJavaSparkContext();

...

Broadcast<String> broadcastVarReferenceType = ctx.broadcast(referenceType);
Broadcast<String> broadcastVarFilterType = ctx.broadcast(filterType);
Broadcast<Double> broadcastVarFilterValueThreshold = ctx.broadcast(filterValueThreshold);

and this is how we use/read them when needed:

String referenceType = (String) broadcastVarReferenceType.value();
String filterType = (String) broadcastVarFilterType.value();
Double filterValueThreshold = (Double) broadcastVarFilterValueThreshold.value();

The general form of using Broadcast<T> is deﬁned below:

DEFINITION:

JavaSparkContext ctx = <create-context-object>;
T t = <some-data-structure>;
final Broadcast<T> broadcastVariable = ctx.broadcast(t);

USAGE:

T t = (T) broadcastVariable.value();

Spark API indicates that after the broadcast variable is created, it should be
used instead of the value t in any functions run on the cluster so that t is
not shipped to the nodes more than once.

655

1

2

3

4

5

6

7

1

2

3

4

5

1

2

3

4

5

6

7

8

9

26.9.1 High Level Solution

The Spark solution is a single Java driver class manipulating several RDDs.
This section provides main steps of the Java driver class and then we will
provide details for each high-level step.

Listing 26.15: SparkGeneAggregationByIndividual Class

1 //STEP-0: import required classes and interfaces
2 public class SparkGeneAggregationByIndividual {
3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

public static void main(String[] args) throws Exception {

//STEP-1: handle input parameters

//STEP-2: create a spark context object

//STEP-3: broadcast shard variables

//STEP-4: create a single JavaRDD from all bioset files

//STEP-5: map bioset records into JavaPairRDD(K,V) pairs
// where K = "<geneID><,><referenceType>", V = 1

//STEP-6: filter out the redundant RDD elements

//STEP-7: reduce by Key and sum up the frequency count

//STEP-8: prepare the final output

System.exit(0);

}

23
24 }

26.9.2 High Level Solution

To use RDD’s, we need Spark’s org.apache.spark.api.java package. The
org.apache.spark.api.java.function package deﬁnes functions for ac-
tions and transformations. Also, org.apache.spark.broadcast.Broadcast
class is needed to deﬁne/broadcast shared global data structures among all
cluster nodes.

Listing 26.16: STEP-0: import required classes and interfaces

1 //STEP-0: import required classes and interfaces
2 import scala.Tuple2;
3 import org.apache.spark.api.java.JavaPairRDD;
4 import org.apache.spark.api.java.JavaRDD;
5 import org.apache.spark.api.java.JavaSparkContext;

656

6 import org.apache.spark.api.java.function.Function;
7 import org.apache.spark.api.java.function.Function2;
8 import org.apache.spark.api.java.function.PairFunction;
9 import org.apache.commons.lang.StringUtils;
10 import org.apache.spark.broadcast.Broadcast;
11 import org.apache.spark.SparkConf;
12
13 import java.util.Arrays;
14 import java.util.List;
15 import java.util.ArrayList;
16 import java.io.FileReader;
17 import java.io.BufferedReader;

26.9.3 STEP-1: handle input parameters

This section reads three metric parameters (referenceType, ﬁlterType, ﬁlter-
ValueThreshold) for gene aggregation and all biosets involved in the analysis.
Each bioset is identiﬁed by an HDFS ﬁle.

Listing 26.17: STEP-1: handle input parameters

1 //STEP-1: handle input parameters
2 if (args.length != 4) {
3

System.err.println("Usage: SparkGeneAggregationByIndividual <referenceType>" +

4

"<filterType> <filterValueThreshold> <biosets>");

System.exit(1);

5
6 }
7
8 final String referenceType = args[0];
9 final String filterType = args[1];
10 final Double filterValueThreshold = new Double(args[2]);
11 final String biosets = args[3];
12
13 System.out.println("args[0]: <referenceType>="+referenceType);
14 System.out.println("args[1]: <filterType>="+filterType);
15 System.out.println("args[2]: <filterValueThreshold>="+filterValueThreshold);
16 System.out.println("args[3]: <biosets>="+biosets);

// {"r1", "r2", "r3", "r4"}
// {"up", "down", "abs"}

26.9.4 STEP-2: Create a Spark Context Object

This step creates a JavaSparkContext, which is needed for creation of RDDs
(fundamental data abstraction and parallelism in Spark). Context object can
be created in many diﬀerent ways. Here, we create a a JavaSparkContext
object by using SparkConf object. SparkConf is a conﬁguration class for a

657

Spark application. SparkConf has set(K, V) method for parameter deﬁni-
tions.

Listing 26.18: STEP-2: create a spark context object

1 //STEP-2: create a spark context object
2 JavaSparkContext ctx =

createJavaSparkContext();

26.9.5 STEP-3: Broadcast Shard Variables

Spark enables sharing variables and data structures among cluster nodes by
Broadcast<T> class, where T is a type of shared data. Spark has an eﬃcient
mechanism for broadcasting shared variables and objects. Shared variables
can be accessed in Sparks’s map() and reduce() functions.

Listing 26.19: STEP-3: broadcast shard variables

1 //STEP-3: broadcast shard variables
2 final Broadcast<String> broadcastVarReferenceType = ctx.broadcast(referenceType);
3 final Broadcast<String> broadcastVarFilterType = ctx.broadcast(filterType);
4 final Broadcast<Double> broadcastVarFilterValueThreshold = ctx.broadcast(filterValueThreshold);

26.9.6 STEP-4: Create a JavaRDD For Biosets

The main data for gene aggregation analysis comes from bioset ﬁles. This
step creates a single JavaRDD<String> for all records of biosets involved in
the analysis. A debugging step has been included as well.

Listing 26.20: STEP-4: create a single JavaRDD from all bioset ﬁles

1 //STEP-4: create a single JavaRDD from all bioset files
2 JavaRDD<String> records = readInputFiles(ctx, biosets);
3
4 // debug1
5 List<String> debug1 = records.collect();
6 for (String rec : debug1) {
7
8 }

System.out.println("debug1 => "+ rec);

658

26.9.7 STEP-5: Map Biosets into JavaPairRDD(K,V)

This step creates JavaPairRDD(K,V) object from all bioset records, where
K = "<geneID><,><referenceType>" and V = 1. This will enable us to
count frequency of genes for all patients represented by biosets. When a
bioset record does not match our metric criteria, we create a dummy object
(Tuple2("null", 0)), which will be ﬁltered out before ﬁnializing the output.
In Spark, RDD elements cannot be Java null objects and this is the reason
for creating objects such as Tuple2Null (to be a replacement for Java null
object).

Listing 26.21: STEP-5: map bioset records into JavaPairRDD(K,V) pairs

1 //STEP-5: map bioset records into JavaPairRDD(K,V) pairs
2 // where K = "<geneID><,><referenceType>", V = 1
3 JavaPairRDD<String, Integer> genes =
4

records.mapToPair(new PairFunction<String, String, Integer>() {

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

public Tuple2<String, Integer> call(String record) {
String[] tokens = StringUtils.split(record, ";");
String geneIDAndReferenceType = tokens[0];
String patientIDAndGeneValue = tokens[1];
String[] val = StringUtils.split(patientIDAndGeneValue, ",");
// val[0] = patientID
// val[1] = geneValue
double geneValue = Double.parseDouble(val[1]);
String[] arr = StringUtils.split(geneIDAndReferenceType, ",");
// arr[0] = geneID
// arr[1] = referenceType
// check referenceType and geneValue
String referenceType = (String) broadcastVarReferenceType.value();
String filterType = (String) broadcastVarFilterType.value();
Double filterValueThreshold = (Double) broadcastVarFilterValueThreshold.value();

if ( (arr[1].equals(referenceType)) &&

(checkFilter(geneValue, filterType, filterValueThreshold)) ){

// prepare key-value for reducer and send it to reducer
return new Tuple2<String, Integer>(geneIDAndReferenceType, 1);

}
else {

// otherwise nothing will be counted
// later we will filter out these "null" keys
return Tuple2Null;

}

}

31
32 });

The following debugs STEP-5:

659

// debug2
List<Tuple2<String, Integer>> debug2 = genes.collect();
for (Tuple2<String, Integer> pair : debug2) {

System.out.println("debug2 => key="+ pair._1 + "\tvalue="+pair._2);

}

26.9.8 STEP-6: ﬁlter out the redundant RDD elements

Step-5 created redudant (K,V) = ("null", 0) pairs. This step ﬁlters non-
necessary data and provides a clean JavaPairRDD<String,Integer>. This is
accomplished by implementing Spark’s filter() function. The filter()
is deﬁned as:

public JavaPairRDD<K,V> filter(Function<Tuple2<K,V>,Boolean> f)
DESCRIPTION: Return a new RDD containing only the

elements that satisfy a predicate;

Here is the ﬁlter implementation:

Listing 26.22: STEP-6: ﬁlter out the redundant RDD elements

1 //STEP-6: filter out the redundant RDD elements
2 // If a counter (i.e., V) is 0, then exclude them
3 JavaPairRDD<String,Integer> filteredGenes =
4

genes.filter(new Function<Tuple2<String,Integer>,Boolean>() {

5

6

7

8

9

10

11

12

public Boolean call(Tuple2<String, Integer> s) {

int counter = s._2;
if (counter > 0) {
return true;

}
else {

return false;

}

}

13
14 });

660

26.9.9 STEP-7: reduce by Key and sum up the fre-

quency count

This step implememnts reduce()function. It basically groups up the genes
by GENE-ID and sums up the frequency counts.

Listing 26.23: STEP-7: reduce by Key and sum up the frequency count

1 //STEP-7: reduce by Key and sum up the frequency count
2 JavaPairRDD<String, Integer> counts =
3

filteredGenes.reduceByKey(new Function2<Integer, Integer, Integer>() {

4

5

public Integer call(Integer i1, Integer i2) {

return i1 + i2;

}

6
7 });

26.9.10 STEP-8: prepare the ﬁnal output

This ﬁnal step emits the ﬁnal desired output for gene aggregation analysis.

Listing 26.24: STEP-8: prepare the ﬁnal output

1 //STEP-8: prepare the final output
2 List<Tuple2<String, Integer>> output = counts.collect();
3 for (Tuple2<String, Integer> tuple : output) {
4
5 }

System.out.println("final output => "+ tuple._1 + ": " + tuple._2);

26.9.11 Utitilty Functions

The toList() method accepts a ﬁle, which contains all biosets involved in
the analysis phase. Each record of input ﬁle is an HDFS ﬁle, which represents
a single bioset.

Listing 26.25: Utitilty Function: toList()

1

2

3

4

5

6

7

8

/**

* Convert all bioset files into a List<biosetFileName>
*
* @param biosets is a filename, which holds all bioset files as HDFS entries
* an example will be:
*
*
*

/biosets/1000.txt
/biosets/1001.txt
...

661

9

10

11

12

13

14

15

16

17

18

19

20

21

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

*
*/

/biosets/1408.txt

private static List<String> toList(String biosets) throws Exception {

List<String> biosetFiles = new ArrayList<String>();
BufferedReader in = new BufferedReader(new FileReader(biosets));
String line = null;
while ((line = in.readLine()) != null) {
String aBiosetFile = line.trim();
biosetFiles.add(aBiosetFile);
}
in.close();
return biosetFiles;

}

Listing 26.26: Utitilty Function: readInputFiles()

static JavaRDD<String> readInputFiles(JavaSparkContext ctx,

String filename)

throws Exception {
List<String> biosetFiles = toList(filename);
int counter = 0;
JavaRDD[] rdds = new JavaRDD[biosetFiles.size()];
for (String biosetFileName : biosetFiles) {

System.out.println("readInputFiles(): biosetFileName=" + biosetFileName);
JavaRDD<String> record = ctx.textFile(biosetFileName);
rdds[counter] = record;
counter++;

}
JavaRDD<String> allBiosets = ctx.union(rdds);
return allBiosets;

}

Listing 26.27: Utitilty Function: checkFilter()

static boolean checkFilter(double value, String filterType, Double filterValueThreshold) {

if (filterType.equals("abs")) {

if (Math.abs(value) >= filterValueThreshold) {

return true;

}
else {

return false;

}

}
if (filterType.equals("up")) {

if (value >= filterValueThreshold) {

return true;

}
else {

return false;

}

}
if (filterType.equals("down")) {

662

if (value <= filterValueThreshold) {

return true;

}
else {

return false;

}

}
return false;

}

19

20

21

22

23

24

25

26

27

28
29 }

26.9.12 Running Spark on YARN

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

1

2

3

4

5

6

7

8

9

10

11

12

13

26.9.12.1

Input

# cat biosets.txt
/biosets/b1.txt
/biosets/b2.txt
/biosets/b3.txt
# hadoop fs -cat /biosets/b1.txt
GENE-1,r1;p100,1.00
GENE-1,r1;p100,1.06
GENE-1,r1;p100,1.10
GENE-1,r1;p100,1.20
# hadoop fs -cat /biosets/b2.txt
GENE-1,r1;p200,1.00
GENE-1,r1;p200,1.02
GENE-1,r1;p200,1.04
# hadoop fs -cat /biosets/b3.txt
GENE-1,r1;p300,1.01
GENE-1,r1;p300,1.06
GENE-1,r1;p300,1.08

26.9.12.2 Script

# cat run_gene_aggregation_by_individual_yarn.sh
#!/bin/bash
export HADOOP_HOME=/usr/local/hadoop/hadoop-2.4.0
export SPARK_LIBRARY_PATH=$HADOOP_HOME/lib/native
export JAVA_HOME=/usr/java/jdk7
export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop
export YARN_CONF_DIR=$HADOOP_HOME/etc/hadoop
export SPARK_HOME=/home/hadoop/spark-1.0.0
export MP=/home/hadoop/spark_mahmoud_examples
export MY_JAR=$MP/mp.jar
export SPARK_JAR=$MP/spark-assembly-1.0.0-hadoop2.4.0.jar
export YARN_APPLICATION_CLASSPATH=$CLASSPATH:$HADOOP_HOME/etc/hadoop
prog=SparkGeneAggregationByIndividual

663

14

15

16

17

18

19

20

21

22

23

24

25

26

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

biosets=/home/hadoop/spark_mahmoud_examples/biosets.txt
referenceType=r1
#{"r1", "r2", "r3", "r4"}
filterType=up
# {"up", "down", "abs"}
filterValueThreshold=1.04
$SPARK_HOME/bin/spark-submit --class $prog \

--master yarn-cluster \
--num-executors 6 \
--driver-memory 1g \
--executor-memory 1g \
--executor-cores 12 \
$MY_JAR $referenceType $filterType $filterValueThreshold $biosets

26.9.12.3 Log of Script Run

./run_gene_aggregation_by_individual_yarn.sh

args[0]: <referenceType>=r1
args[1]: <filterType>=up
args[2]: <filterValueThreshold>=1.04
args[3]: <biosets>=/home/hadoop/spark_mahmoud_examples/biosets.txt

readInputFiles(): biosetFileName=/biosets/b1.txt
readInputFiles(): biosetFileName=/biosets/b2.txt
readInputFiles(): biosetFileName=/biosets/b3.txt

value=0

debug2 => key=null
debug2 => key=GENE-1,r1
debug2 => key=GENE-1,r1
debug2 => key=GENE-1,r1
debug2 => key=null
debug2 => key=null
debug2 => key=GENE-1,r1
debug2 => key=null
debug2 => key=GENE-1,r1
debug2 => key=GENE-1,r1

value=1
value=1
value=1

value=1

value=1
value=1

value=0
value=0

value=0

final output => GENE-1,r1: 6

26.10 Gene Aggregation in Spark: Filter by

Average

Gene Aggregation using ”Filter by Average” algorithm is implemented in
Spark. The ﬁrst step is to create a JavaRDD<String> for all input biosets,
where each item of RDD will be a record of a bioset.The second step is to

664

create a JavaPairRDD<K,V>, where K is a <geneID><,><referenceType>
and V is a <patientID><,><geneValue>. The third step will be to group
by K (as <geneID><,><referenceType>). The ﬁnal step will be to ﬁnd fre-
quencies of GENE-ID by average value of genes (per patient), which satisﬁes
all given metrics. The core of Gene Aggregation using ”Filter by Average”
algorithm is presented by an example: let

K = Tuple2(geneID, referenceType)
V = List(Tuple2(patientID, geneValue))

To ﬁnd average per patient, using V, we build a hash table as:

Map(patientID, Tuple2(sum(geneValue), count)).

Next, we ﬁnd the average per patient as: Map(patientID, average), where
If the average passes the "filter
average = sum(geneValue)/count.
value threhold", then that will be counted as 1 (means passed the test),
otherwise it will be counted as 0 (means did not pass the test).

First, we present the main steps for Spark solution and in subsequent

sections, we present the details of each step.

Listing 26.28: Gene Aggregation by Average: High-Level Steps

1 // STEP-0: import required classes and interfaces
2
3 public class SparkGeneAggregationByAverage {
4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

// used as a dummy object for filtering
static final Tuple2<String, String> Tuple2Null =

new Tuple2<String, String>("n", "n");

public static void main(String[] args) throws Exception {

//STEP-1: handle input parameters

//STEP-2: create a Java Spark context object

//STEP-3: share global variables in all cluster nodes

//STEP-4: read all bioset records and create an RDD as
//

JavaRDD<String> records = readInputFiles(ctx, biosets);

//STEP-5: map bioset records and create JavaPairRDD<K, V>

665

//
//

where K = "<geneID><,><referenceType>",

V = "<patientID><,><geneValue>"

//STEP-6: filter redundant records created by STEP-5

//STEP-7: group biosets by "<geneID><,><referenceType>"
// genesByID = JavaPairRDD<K, List<V>>
//
//

where K = "<geneID><,><referenceType>"

V = "<patientID><,><geneValue>"

//STEP-8: prepare the final desired output

//STEP-9: emit the final output

System.exit(0);

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

}

35
36 }

26.10.1 STEP-0:

import required classes and inter-

faces

Listing 26.29: STEP-0: import required classes and interfaces

1 //STEP-0: import required classes and interfaces
2 import scala.Tuple2;
3 import org.apache.spark.api.java.JavaRDD;
4 import org.apache.spark.api.java.JavaPairRDD;
5 import org.apache.spark.api.java.JavaSparkContext;
6 import org.apache.spark.api.java.function.Function;
7 import org.apache.spark.api.java.function.PairFunction;
8 import org.apache.commons.lang.StringUtils;
9 import org.apache.spark.broadcast.Broadcast;
10 import org.apache.spark.SparkConf;
11
12 import java.io.FileReader;
13 import java.io.BufferedReader;
14 import java.util.Map;
15 import java.util.HashMap;
16 import java.util.List;
17 import java.util.ArrayList;

26.10.2 STEP-1: handle input parameters

666

Listing 26.30: STEP-1: handle input parameters

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

//STEP-1: handle input parameters
if (args.length != 4) {

System.err.println("Usage: SparkGeneAggregationByAverage"+

" <referenceType> <filterType> <filterValueThreshold> <biosets>");

System.exit(1);

}

final String referenceType = args[0];
final String filterType = args[1];
final Double filterValueThreshold = new Double(args[2]);
final String biosets = args[3];

// {"r1", "r2", "r3", "r4"}
// {"up", "down", "abs"}

System.out.println("args[0]: <referenceType>="+referenceType);
System.out.println("args[1]: <filterType>="+filterType);
System.out.println("args[2]: <filterValueThreshold>="+filterValueThreshold);
System.out.println("args[3]: <biosets>="+biosets);

26.10.3 STEP-2: create a Java Spark context object

You need to create a JavaSparkContext in order to create and manipulate
your RDDs. There are many ways to create this context object. One way to
create it is to create a Spark’s conﬁguration object (as SparkConf and then
inject it into the JavaSparkContext’s constructor.

Listing 26.31: STEP-2: create a Java Spark context object

1

2

//STEP-2: create a Java Spark context object
JavaSparkContext ctx = createJavaSparkContext();

Note that I have hard coded the YARN resource manager server (as
myserver100), you need to replace it accordingly by some conﬁguration ﬁles.

Listing 26.32: createJavaSparkContext() Method

1

2

3

4

5

6

7

8

9

10

11

static JavaSparkContext createJavaSparkContext() throws Exception {

SparkConf conf = new SparkConf();
conf.set("yarn.resourcemanager.hostname", "myserver100");
conf.set("yarn.resourcemanager.scheduler.address", "myserver100:8030");
conf.set("yarn.resourcemanager.resource-tracker.address", "myserver100:8031");
conf.set("yarn.resourcemanager.address",
conf.set("mapreduce.framework.name", "yarn");
conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
conf.set("spark.executor.memory", "1g");
JavaSparkContext ctx =

"myserver100:8032");

new JavaSparkContext("yarn-cluster", "SparkGeneAggregationByAverage", conf);

667

12

13

}

return ctx;

26.10.4 STEP-3: share global variables in all cluster

nodes

In Spark, the Broadcast<T> class enable us to share data structures of type
T among all cluster nodes. Basically, you can share/broadcast your data
structues in your driver program (the class submitting the job to the Spark
or YARN cluster) and then you may read them from any cluster node inside
map() and reduceByKey() functions. For our three global variables, we do
it as:

Listing 26.33: STEP-3: share global variables in all cluster nodes

//STEP-3: share global variables in all cluster nodes
final Broadcast<String> broadcastVarReferenceType = ctx.broadcast(referenceType);
final Broadcast<String> broadcastVarFilterType = ctx.broadcast(filterType);
final Broadcast<Double> broadcastVarFilterValueThreshold = ctx.broadcast(filterValueThreshold);

26.10.5 STEP-4: read all bioset records and create an

RDD

This step reads all bioset ﬁles from HDFS and create a single RDD (JavaRDD<String>).
This functionality is explained in detail when we discuss the readInputFiles()
method.

Listing 26.34: STEP-4: read all bioset records and create an RDD

//STEP-4: read all bioset records and create an RDD
JavaRDD<String> records = readInputFiles(ctx, biosets);

// debug1
List<String> debug1 = records.collect();
for (String rec : debug1) {

System.out.println("debug1 => "+ rec);

}

668

1

2

3

4

1

2

3

4

5

6

7

8

26.10.6 STEP-5: map bioset records and create Java-

PairRDD(K, V)

This step creates JavaPairRDD(K,V) object from all bioset records, where K
= "<geneID><,><referenceType>" and V = "<patientID><,><geneValue>".
This will enable us to count frequency of genes by average for all patients
represented by patients for all biosets. When a bioset record does not
match our metric criteria, we create a dummy (marked as null object) object
(Tuple2("n", "n")), which will be ﬁltered out before ﬁnializing the output.
In Spark, RDD elements cannot be Java null objects and this is the rea-
son for creating objects such as Tuple2Null (to be a replacement for Java
null object). Note that the Spark’s approach for ignoring some RDD ele-
ments is diﬀerent from MapReduce/Hadoop’s approach, which just ignores
them without emitting any redundant (key, value) pairs. For example, in
MapReduce/Hadoop, if your mapper/reducer input is not your desired cri-
teria, then you may ignore to emit any new (key, value) pairs. But in Spark,
mapToPair() method has to return a non-null (key, value) pair.

Listing 26.35: STEP-5: map bioset records and create JavaPairRDD(K, V)

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

//STEP-5: map bioset records and create JavaPairRDD<K, V>
// JavaPairRDD<K, V>,
//
//
JavaPairRDD<String, String> genes =

where K = "<geneID><,><referenceType>",

V = "<patientID><,><geneValue>"

records.mapToPair(new PairFunction<String, String, String>() {

public Tuple2<String, String> call(String record) {

String[] tokens = StringUtils.split(record, ";");
String geneIDAndReferenceType = tokens[0];
String patientIDAndGeneValue = tokens[1];
String[] arr = StringUtils.split(geneIDAndReferenceType, ",");
// arr[0] = geneID
// arr[1] = referenceType
// check referenceType and geneValue
String referenceType = (String) broadcastVarReferenceType.value();
if ( arr[1].equals(referenceType) ){

// prepare key-value for reducer and send it to reducer
return new Tuple2<String, String>(geneIDAndReferenceType,
patientIDAndGeneValue);

}
else {

// otherwise nothing will be counted
// later we will filter out these "null" keys
return Tuple2Null;

}

}
});

669

26.10.7 STEP-6: ﬁlter redundant records created by

STEP-5

Step-5 created redudant (K,V) = Tuple2("n", "n") pairs (as a replacement
for Java null values, since Spark is unable to have null RDD elements). This
step ﬁlters out redundant data and provides a clean JavaPairRDD<String,String>.
This is accomplished by implementing Spark’s filter() function. The
filter() is deﬁned as:

public JavaPairRDD<K,V> filter(Function<Tuple2<K,V>,Boolean> f)
DESCRIPTION: Return a new RDD containing only the elements that

satisfy a predicate defined by function f.

Here is the ﬁlter implementation:

Listing 26.36: STEP-6: ﬁlter redundant records created by STEP-5

//STEP-6: filter redundant records created by STEP-5
// public JavaPairRDD<K,V> filter(Function<Tuple2<K,V>,Boolean> f)
// Return a new RDD containing only the elements that satisfy a predicate;
// If K = "n", then exclude them
JavaPairRDD<String,String> filteredGenes =

genes.filter(new Function<Tuple2<String,String>,Boolean>() {

public Boolean call(Tuple2<String, String> s) {

String value = s._1;
if (value.equals("n")) {

// exclude null entries
return false;

}
else {

return true;

}

}
});

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

26.10.8 STEP-7: group biosets by geneID and refer-

enceType

This step groups all bioset records by <geneID><,><referenceType>. The
grouped values will be ready for the ﬁnal reductionm which we will calculate

670

gene aggregation by average per patient.

Listing 26.37: STEP-7: group biosets by ”¡geneID¿¡,¿¡referenceType¿

1 // STEP-7: group biosets by "<geneID><,><referenceType>"
2 // genesByID = JavaPairRDD<K, List<V>>
3 //
4 //
5 JavaPairRDD<String, Iterable<String>> genesByID = filteredGenes.groupByKey();

where K = "<geneID><,><referenceType>"

V = "<patientID><,><geneValue>"

26.10.9 STEP-8: prepare the ﬁnal desired output

This step applies the core gene aggregation by average algorithm to all
bioset records. Now we have a list of <patientID><,><geneValue> per
<geneID><,><referenceType>. This step is implemented by mapValues()
method. This is how it works:

mapValues[U](f: (V) => U): JavaPairRDD[K, U]
Description: Pass each value in the key-value

pair RDD through a map function
without changing the keys; this also
retains the original RDD’s partitioning.

This step uses Spark’s broadcated global variables (so called shared vari-
ables). You can deﬁne shared data structures by creating Broadcast<T>
(where T is your data structure). To use shared/broadcasted variables, you
may use Broadcast.value() method (this is how we read shared variables
in all cluster nodes – the value() method returns data structure of type T).

Listing 26.38: STEP-8: prepare the ﬁnal desired output

4

5

6

7

8

9

10

1 //STEP-8: prepare the final desired output
2 JavaPairRDD<String, Integer> frequency =
3

genesByID.mapValues(new Function< Iterable<String>,

Integer

>() {

// input
// output

public Integer call(Iterable<String> values) {

Map<String, PairOfDoubleInteger> patients = buildPatientsMap(values);
String filterType = (String) broadcastVarFilterType.value();
Double filterValueThreshold = (Double) broadcastVarFilterValueThreshold.value();
int passedTheTest = getNumberOfPatientsPassedTheTest(patients,

671

11

12

13

}

14
15 });

return passedTheTest;

filterType,
filterValueThreshold);

26.10.10 STEP-9: emit the ﬁnal output

This step prints the ﬁnal desired output.

Listing 26.39: STEP-9: emit the ﬁnal output

1 //STEP-9: emit the final output
2 List<Tuple2<String, Integer>> finalOutput = frequency.collect();
3 for (Tuple2<String, Integer> tuple : finalOutput) {
4
5 }

System.out.println("final output => "+ tuple._1 + ": " + tuple._2);

The following sections provide explantion of some of the important meth-

ods used in solving gene aggregation by average algorithm.

26.10.11

toList() Method

This method collects all HDFS bioset ﬁles and saves them as a List<String>,
where each list element is an HDFS bioset ﬁle.

Listing 26.40: Support Method toList()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

/**

* Convert all bioset files into a List<biosetFileName>
*
* @param biosets is a filename, which holds all bioset files as
* HDFS entries; an example will be:
*
*
*
*
*/

/biosets/1000.txt
/biosets/1001.txt
...
/biosets/1408.txt

private static List<String> toList(String biosets) throws Exception {

List<String> biosetFiles = new ArrayList<String>();
BufferedReader in = new BufferedReader(new FileReader(biosets));
String line = null;
while ((line = in.readLine()) != null) {
String aBiosetFile = line.trim();
biosetFiles.add(aBiosetFile);
}
in.close();

672

20

21

}

return biosetFiles;

26.10.12

readInputFiles() Method

This method reads all HDFS bioset ﬁles and creates a new RDD as JavaRDD<String>,
where each element is a bioset record. All bioset records are merged by us-
ing JavaContextObject.union() method. Then we partition this RDD by
applying JavaRDD.coalesce() method for further parallel processing.

Listing 26.41: Support Method readInputFiles()

private static JavaRDD<String> readInputFiles(JavaSparkContext ctx,

String filename)

throws Exception {

List<String> biosetFiles = toList(filename);

int counter = 0;
JavaRDD[] rdds = new JavaRDD[biosetFiles.size()];
for (String biosetFileName : biosetFiles) {

System.out.println("debug1 biosetFileName=" + biosetFileName);
JavaRDD<String> record = ctx.textFile(biosetFileName);
rdds[counter] = record;
counter++;
}

JavaRDD<String> allBiosets = ctx.union(rdds);
return allBiosets.coalesce(9, false);

} // readInputFiles

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

26.10.13 buildPatientsMap() Method

This method builds a Map<String, PairOfDoubleInteger>, where key is a
patientID and value is a PairOfDoubleInteger object, which keeps track of
sum of gene values and its count.

Listing 26.42: Support Method buildPatientsMap()

1 private static Map<String,PairOfDoubleInteger> buildPatientsMap(Iterable<String> values) {
Map<String, PairOfDoubleInteger> patients = new HashMap<String, PairOfDoubleInteger>();
2
for (String patientIdAndGeneValue : values) {

3

4

5

6

7

8

9

String[] tokens = StringUtils.split(patientIdAndGeneValue, ",");
String patientID = tokens[0];
//tokens[1] = geneValue
double geneValue = Double.parseDouble(tokens[1]);
PairOfDoubleInteger pair = patients.get(patientID);
if (pair == null) {

673

pair = new PairOfDoubleInteger(geneValue, 1);
patients.put(patientID, pair);

}
else {

pair.increment(geneValue);

}

}
return patients;

10

11

12

13

14

15

16

17
18 }

26.10.14 buildPatientsMap() Method

This method iterates the Map<String, PairOfDoubleInteger> built by the
buildPatientsMap() method. Each entry of this map denotes a single pa-
tient. If each patient passes the desired metrics (i.e., the average of gene val-
ues passes the deﬁned metrics – metrics are filterType and filterValueThreshold),
then that is counted as the one, which passes the test.

Listing 26.43: Support Method getNumberOfPatientsPassedTheTest()

1 private static int getNumberOfPatientsPassedTheTest(
Map<String, PairOfDoubleInteger> patients,
2
String filterType,
Double filterValueThreshold) {

4

3

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

if (patients == null) {

return 0;

}

// now, we will average the values and see which
// patient passes the threshhold
int passedTheTest = 0;
for (Map.Entry<String, PairOfDoubleInteger> entry : patients.entrySet()) {

//String patientID = entry.getKey();
PairOfDoubleInteger pair = entry.getValue();
double avg = pair.avg();
if (filterType.equals("up")) {

if (avg >= filterValueThreshold) {

passedTheTest++;

}

}
if (filterType.equals("down")) {

if (avg <= filterValueThreshold) {

passedTheTest++;

}

}
else if (filterType.equals("abs")) {

if (Math.abs(avg) >= filterValueThreshold) {

passedTheTest++;

}

}

674

}
return passedTheTest;

31

32
33 }

26.10.15 Running Spark on YARN

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

26.10.15.1

Input

# cat biosets.txt
/biosets/b1.txt
/biosets/b2.txt
/biosets/b3.txt
# hadoop fs -cat /biosets/b1.txt
GENE-1,r1;p100,1.00
GENE-1,r1;p100,1.06
GENE-1,r1;p100,1.10
GENE-1,r1;p100,1.20
# hadoop fs -cat /biosets/b2.txt
GENE-1,r1;p200,1.00
GENE-1,r1;p200,1.02
GENE-1,r1;p200,1.04
# hadoop fs -cat /biosets/b3.txt
GENE-1,r1;p300,1.01
GENE-1,r1;p300,1.06
GENE-1,r1;p300,1.08

26.10.15.2 Script

# cat run_gene_aggregation_by_average_yarn.sh
#!/bin/bash
export HADOOP_HOME=/usr/local/hadoop/hadoop-2.4.0
export SPARK_LIBRARY_PATH=$HADOOP_HOME/lib/native
export JAVA_HOME=/usr/java/jdk7
export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop
export YARN_CONF_DIR=$HADOOP_HOME/etc/hadoop
export SPARK_HOME=/home/hadoop/spark-1.0.0
export MP=/home/hadoop/spark_mahmoud_examples
export MY_JAR=$MP/mp.jar
export SPARK_JAR=$MP/spark-assembly-1.0.0-hadoop2.4.0.jar
export YARN_APPLICATION_CLASSPATH=$CLASSPATH:$HADOOP_HOME/etc/hadoop
#export THEJARS=$MP/commons-math-2.2.jar,$MP/commons-math3-3.0.jar
prog=SparkGeneAggregationByAverage
biosets=/home/hadoop/spark_mahmoud_examples/biosets.txt
referenceType=r1
#{"r1", "r2", "r3", "r4"}
filterType=up
# {"up", "down", "abs"}
filterValueThreshold=1.04
$SPARK_HOME/bin/spark-submit --class $prog \

675

--master yarn-cluster \
--num-executors 6 \
--driver-memory 1g \
--executor-memory 1g \
--executor-cores 12 \
$MY_JAR $referenceType $filterType $filterValueThreshold $biosets

26.10.15.3 Log of Script Run

./run_gene_aggregation_by_average_yarn.sh

args[0]: <referenceType>=r1
args[1]: <filterType>=up
args[2]: <filterValueThreshold>=1.04
args[3]: <biosets>=/home/hadoop/spark_mahmoud_examples/biosets.txt

debug1 biosetFileName=/biosets/b1.txt
debug1 biosetFileName=/biosets/b2.txt
debug1 biosetFileName=/biosets/b3.txt

final output => GENE-1,r1: 2

22

23

24

25

26

27

1

2

3

4

5

6

7

8

9

10

11

12

13

14

676

Chapter 27

Linear Regression

27.1

Introduction

In this chapter we present a very important statistical cocept, linear re-
gression1, which is used by many applications including clinical applications
such as genome analysis using patient sample data. What are the main ap-
plications of linear regression? ”Linear regression is widely used in biological,
behavioral and social sciences to describe possible relationships between vari-
ables. It ranks as one of the most important tools used in these disciplines.”2
Of course implementing linear regression for small data is very straightfor-
ward (we might use many existing Java class such as the one from Apache
common: SimpleRegression3, but these classes and packages can not handle
huge amount of data due to limitation of memory and CPU in a single server).
Our primary goal in this chapter is to solve linear regression for huge data
sets (such as genomic data represented by biosets for many patients samples
data).

1The linear regression model analyzes the relationship between the response or de-
pendent variable and a set of independent or predictor variables. This relationship is
expressed as an equation that predicts the response variable as a linear function of the
parameters. These parameters are adjusted so that a measure of ﬁt is optimized. Much
of the eﬀort in model ﬁtting is focused on minimizing the size of the residual, as well as
ensuring that it is randomly distributed with respect to the model predictions (source:
http://en.wikipedia.org/wiki/Predictive_analytics

2source: http://en.wikipedia.org/wiki/Linear_regression
3 org.apache.commons.math3.stat.regression.SimpleRegression

677

The most common form of linear regression is least squares ﬁtting4. Be-
fore getting into details of linear regression, let’s see what is Linear Regression
and What Does it Tell You. In simple terms, we are trying to ﬁt an equation
to a real set of data (kind of how to predict the future by observing a real
set of data).

This chapter provides two distinct MapReduce/Hadoop solutions for linear
regression:

• The ﬁrst solution utilizes Apache’s Commons SimpleRegression

• The second solution implements MapReduce by using R’s Linear Model

27.2 Simple Facts about Linear Regression

We borrow some of the following facts from http://www.biddle.com/documents/
bcg_comp_chapter3.pdf.

1. Linear regression is modeled by a linear equation y = ax + b.

In a
nutshell, regression analysis is used to ﬁnd equations that ﬁt data (data
is represented by a set of (x, y)).

2. Linear regression uses the fact that there is a statistically signiﬁcant
correlation between two variables to allow you to make predictions
about one variable based on your knowledge of the other.

3. You should not do linear regression unless your correlation coeﬃcient

is statistically signiﬁcant

4. For linear regression to work there needs to be a linear relationship

between the variables

Next we need some deﬁnitions for regression and linear Regression. A
regression is a statistical analysis assessing the association between two vari-
ables (such as x and y in regression equation y = ax+b, in the simplest form,
it is used to ﬁnd the relationship between two variables x and y, but you may
use more than two variables). Therefore, linear regression deﬁnes/estimates
the relation between variables when the regression equation is linear: e.g.,

4http://mathworld.wolfram.com/LeastSquaresFitting.html

678

y = ax + b, where a is the the intercept point of the regression line and the
y axis and b is the slope of the regression line. So, the main goal of the
linear regression is that to ﬁnd a (intercept - the value of y when x = 0)
and b (slope) for a given set of x, y. Typically variable x is the explanatory
variable and y is the dependent variable.

27.3 Simple Example

Here we present a simple example to demonstrate the basic concept of a
linear regression. The goal of Linear Regression analysis is to ﬁnd a linear
equation(s) that ﬁt data. Once we have the linear equation (y = ax+b), then
you can use the Linear Regression model (expressed as a linear equation) to
make predictions. Here, we shows how to use a sample data, calculate linear
regression, and ﬁnd the equation y = ax + b. Our two variables are ”age”
and ”glucose level” for a set of very small patients: ﬁrst we make a chart of
our data:

Subject Age (x) Glucose Level (y)
90
93
98
64
78
71
88
86
668

1
2
3
4
5
6
7
8
sum

41
42
43
20
25
40
58
60
329

xy
3690
3906
4214
1280
1950
2840
5104
5160
28144

x2
1681
1764
1849
400
625
1600
3364
3600
14883

y2
8100
8649
9604
4096
6084
5041
7744
7396
56714

Next, we use the following formulas to calculate a and b:

a =

((cid:80) y)((cid:80) x2) − ((cid:80) x)((cid:80) xy)
n((cid:80) x2) − ((cid:80) x)2

679

n((cid:80) xy) − ((cid:80) x)((cid:80) y)
n((cid:80) x2) − ((cid:80) x)2
Note that n is the number of samples for regression (in our example n = 8.

b =

Now by plugging the pre-calculated values, we will have:

a =

b =

Next, we plot linear regression by R programming language:

1 # R
2 R version 2.15.1 (2012-06-22) -- "Roasted Marshmallows"
3 > x <- c(41, 42, 43, 20, 25, 40, 58, 60)
4 > y <- c(90, 93, 98, 64, 78, 71, 88, 86)
5 > mod1 <- lm(y ~ x)
6 > plot(x, y, xlim=c(min(x)-5, max(x)+5), ylim=c(min(y)-10, max(y)+10))
7 > abline(mod1, lwd=2)

As you can observe from the plot, linear regression attempts to model
the relationship between two variables (x and y) by ﬁtting a linear equation
to observed data (the most common algorithm for ﬁtting a regression line is
the method of least-squares).

27.4 Problem Statement

Assume a set of patient data for a clinical trial of some medication or treat-
met. We are assuming that each patient may have a set of biosets/biomarkers
and each bioset/biomarker has a set of (key, value) where key is the GENE-
ID and value can represent ”segment value”, ”copy change number”, or
other related genomic data value (here value represent variable x and vari-
able y can be the survival time of that speciﬁc patient for this treatment).
Number of (key, value) pairs for each biomarker depends on the type of
bioset (bioset types are ”methylation”, ”copy number variation”, ”gene ex-
pression”, and ”somatic mutation”). For example for ”gene expression” type,

680

Figure 27.1: Linear Regression by R

681

each biomarker will have 45,000+ (key, value) pairs. Imagine, you want to
do a linear regression for 40,000 biosets, this will lead us to 1.8 billion data
points, which is not possible to do the linear regression computation in a
single server. Here our interest is to do a linear regression per GENE-ID.
Explicitly, our objective is to ﬁnd the following per GENE-ID:

• Intercept (the intercept of the estimated regression line)

• Slope (the slope of the estimated regression line).

• Signiﬁcance (pvalue or signiﬁcance level of the slope correlation).

27.5

Input Data

Input data will be comprised of a set of biosets/biomarkers (each bioset
is identiﬁed by a unique BIOSET-ID. Each bioset is comprised of 45,000+
records and each record will contain the following (here, we consider gene\_value
as variable x)

Format: <gene_id><,><reference><;><bioset_id><,><gene_value>

where <gene_id> = a gene represented by an ID

<reference> will be one the following:
r1 = reference to normal patient
r2 = reference to disease
r3 = reference to paired
r4 = none

Example-1: 1234,r2;3344550,0.43
Example-2: 122765,r1;3344550,1.78

Also, we will have another input vector (to represent variable y) such as
”survival time” for patients (which is an array of ”double” data type and
each item corrospnds with a bioset). For example, to analyze 5000 biosets,
we do need to pass an array of ”survival time” for size of 5000.

27.6 Expected Ouput

After linear regression job is completed, we should have our analysis result
in the following format (one record per GENE-ID):

682

Format: <gene_id><,><reference><,><slope><,><intercept><,><pvalue>

Example: 1234,r2,1.002,3.12007,0.000098

27.7 MapReduce Solution using Apache Com-

mons SimpleRegression

MapReduce solution for linear regression is comprised of a mapper and a
reducer. The main task of map() function is to identify variable x and pass
it to a reducer (reducer key will be the GENE-ID-and-REFERENCE and its
associated value will be the GENE-VALUE (variable x in linear regression).
Variable y (here in our example is the ”survival time”) is passed from driver
class to MapReduce/Hadoop Conﬁguration object, which will be retrived by
the reducer (for performing linear regression).

Each reducer will handle a (key, value) received. The key id the GENE-
ID-and-REFERENCE and value is a list of GENE-VALUE. The reduce()
function will get the y values from MapReduce/Hadoop Conﬁguration object
(in Hadoop this will be done by setup() method). Once we have x’s and y’s,
then we will use SimpleRegression5 class to perform linear regression and
then write the result (slope, intercept, and pvalue) back to HDFS. Using
SimpleRegression class is very simple:

// y = intercept + slope * x
SimpleRegression sr = new SimpleRegression();
sr.addData(1d, 2d); // x = 1, y = 2
sr.addData(3d, 3d); // x = 3, y = 3
sr.addData(2d, 4d); // x = 2, y = 4
// we may add any number of sr.addData(x, y)
// now all statistics are defined.
double pvalue = sr.getSignificance());
double intercept = sr.getIntercept());
double slope = sr.getSlope());

Note that the GENE-VALUE represents x’s and we will pass bioset IDs
and ”survival time” (represent’s y’s). Why do we need to pass bioset IDs (

5org.apache.commons.math3.stat.regression.SimpleRegression

(Apache Commons

Math)

683

through Job’s Conﬁguration object)? Because bioset id[i] corroponds with
survival time[i], we have to make sure that we are using proper x’s and y’s
for linear regression.

Listing 27.1: map() for Linear Regression
/**
* @param key is generated by Hadoop (ignored here)
* @param value's format: <gene_id><,><reference><;><bioset_id><,><

gene_value>

*/
map(key, value) {

String line = value.toString().trim();
if ((line == null) || (line.length() == 0)) {

return;

}

String[] tokens = StringUtils.split(line, ";");

//String <gene_id><,><reference> = tokens[0];
//String <bioset_id><,><gene_value> = tokens[1];
if (tokens.length == 2) {

// prepare (key, value) for reducer

emit(tokens[0], tokens[1]);

}

}

The reduce class, LinearRegressionReducer, is presented below.

Listing 27.2: LinearRegressionReducer for Linear Regression

public class LinearRegressionReducer ... {

// instance variables
private Configuration conf = null;
private List<Double> time = null;
// biosetIDs as Strings : NOTE oreder of biosets are VERY IMPORTANT
private List<String> biosets = null;

// will be run only once
public void setup(Context context)

this.conf = context.getConfiguration();

684

// get parameters from Hadoop's configuration
String biosetsAsString = conf.get("biosets");
this.biosets = DataStructuresUtil.splitOnToListOfString(

biosetsAsString, ",");

String timeAsCommaSeparatedString = conf.get("time");
this.time = DataStructuresUtil.splitOnToListOfDouble(

timeAsCommaSeparatedString, ",");

}

// key = <gene_id><,><reference>
// values = { bioset_id,value }
// biosets are: B1, B2, B3, ..., Bn
// time are : T1, T2, T3, ..., Tn
public void reduce(Text key, Iterable<Text> values) {

// see next section ...

}

}

Listing 27.3: reduce() for Linear Regression

public class LinearRegressionReducer ... {

...

// key = <gene_id><,><reference>
// values = { bioset_id,value }
// biosets are: B1, B2, B3, ..., Bn
// time are : T1, T2, T3, ..., Tn
public void reduce(Text key, Iterable<Text> values) {

int numberOfValues = 0;
SimpleRegression sr = new SimpleRegression();
Iterator<Text> iter = values.iterator();
while (iter.hasNext()) {

Text pairAsText = iter.next();
if (pairAsText == null) {

continue;

}
String pairAsString = pairAsText.toString();
String[] tokens = StringUtils.split(pairAsString, ",");
// biosetID = tokens[0]
// value = tokens[1]
if (tokens.length != 2) {

// then ignore that (value, time) from regression

685

continue;

}

int index = biosets.indexOf(tokens[0]);
if (index == -1) {

// biosetID not found
continue;

}

// biosetID found at index
// sr.addData(xPos.get(i), yPos.get(i));
double dvalue = Double.parseDouble(tokens[1]);
sr.addData(dvalue, time.get(index));
numberOfValues++;

}

if (numberOfValues > 0) {
StringBuilder builder = new StringBuilder();
builder.append(key.toString()); // gene_id_and_reference: 1234,r2
builder.append(",");
builder.append(sr.getSignificance()); // pvalue
builder.append(",");
builder.append(sr.getIntercept()); // intercept
builder.append(",");
builder.append(sr.getSlope()); // slope

// prepare reducer for output
Text reducerValue = new Text(builder.toString()); // pvalue,

intercept,slope

emit(null, reducerValue);

}

}

}

27.8 Hadoop Implementation using Apache

Commons SimpleRegression

Our Mapreduce/Hadoop Implementation is comprised of the following classes:

686

Class Name
LinearRegressionDriver.java

Class Description
The driver class, deﬁnes input/output
and registers plug-in classes.
Deﬁnes the map() function

LinearRegressionMapper.java
LinearRegressionReducer.java Deﬁnes the reduce() function
LinearRegressionAnalyzer.java Deﬁnes how output data will

LinearRegressionClient.java

be read from HDFS
Client class to submit job

27.9 MapReduce Solution using R’s Linear

Model

MapReduce solution for linear regression using R’s Linear Model is com-
prised of two MapReduce jobs. The ﬁrst job aggregates required data and
generates input ﬁles, to be read/used in the second MapReduce job. The
second MapReduce job reads input (generated by reducers in phase 1) and
then applies the R’s Linear Model (lm()) function (for details, see http:
//data.princeton.edu/R/linearModels.html). R’s Linear Model is more
accurate and comprehensive than Apache’s SimpleRegression class. The rea-
son for having second Mapreduce job is to avoid calling R’s Linear Model
(lm()) function for evry single GENE-ID. We basically collect as many as
possible in a text ﬁle and then call R’s Linear Model (lm()) function.

Before I describe 2-phase MapReduce solution, let me show you how R’s

Linear Model (lm() function) can be used:

1 # R
2 R version 2.15.1 (2012-06-22) -- "Roasted Marshmallows"
3 Copyright (C) 2012 The R Foundation for Statistical Computing
4 Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)

5

6 > x <- c(-1.0, 1.1, 2.2, 3.3, 4.4, 5.5, -1.5)
7 > y <- c(-1.1, 1.88, 2.88, 3.44, 4.44, 5.99, -1.8)
8 > fit = lm(x ~ y)
9 > intercept = fit$coef[1]
10 > intercept
11 (Intercept)
12 -0.07142071

687

Figure 27.2: Linear Regression Model

13 > slope = fit$coef[2]
14 > slope

y
15
16 0.921802
17 > pvalue = anova(fit)$’Pr(>F)’[1]
18 > pvalue
19 [1] 1.279226e-05
20 > rsquare = summary(fit)$r.squared
21 > rsquare
22 [1] 0.9830423
23 > plot(x, y, xlim=c(min(x)-2, max(x)+2), ylim=c(min(y)-5, max(y)+5))
24 > abline(fit, lwd=1)

Plotting by R’s plot and abline functions generates the following linear

model (image: 27.2).

688

27.9.1 MapReduce Solution using R’s Linear Model:

Phase 1

The main task of map() function for Phase-1 is to identify variable x and pass
it to a reducer (reducer key will be the GENE-ID-and-REFERENCE and its
associated value will be the GENE-VALUE (variable x in linear regression).
Variable y (here in our example is the ”survival time”) is passed from driver
class to MapReduce/Hadoop Conﬁguration object, which will be retrived
by the Phase-1 reducer function (for generating proper input data to be
consumed by the Phase-2 map() function). So, we pass BIOSET-ID(s) and
SURVIVAL-TIME(s) by MapReduce/Hadoop Conﬁguration object, which
will be retrived by the Phase-1 reducer function. Let BIOSET-ID(s) be
{B1, B2, ..., Bn} and SURVIVAL-TIME(s) be {T1, T2, ..., Tn} (note that the
size of BIOSET-ID(s) and SURVIVAL-TIME(s) must be the same).

Each reducer will handle a (key, value) received. The key id the GENE-
ID-and-REFERENCE and value is a list of GENE-VALUE. The reduce()
function will get the y values from MapReduce/Hadoop Conﬁguration object
(in Hadoop this will be done by setup() method). Once we have x’s and
y’s, then we write them to a text ﬁle, which will be saved in HDFS (to
be consumed by the Phase-2 map() function). For example, reducers will
generate the following text ﬁles:

GENE-ID-1; V11, V12, ..., V1n; T11, T12,..., T1n
GENE-ID-2; V21, V22, ..., V2n; T21, T22,..., T2n
...
GENE-ID-m; Vm1, Vm2, ..., Vmn; Tm1, Tm2,..., T1mn

Note that the GENE-VALUE represents x’s and we will pass bioset IDs
and ”survival time” (represent’s y’s). Why do we need to pass bioset IDs (
through Job’s Conﬁguration object)? Because bioset id[i] corroponds with
survival time[i], we have to make sure that we are using proper x’s and y’s
for linear regression.

Let’s say that we have 200 mappers and 30 reducers for Phase-1. With
this conﬁguration, our MapReduce job for Phase-1 will create 30 output ﬁles
(in HDFS):

/<hdfs-output-directory>/part-00000
/<hdfs-output-directory>/part-00001
...
/<hdfs-output-directory>/part-00029

689

The input to map() function of Phase-2 will be theses HDFS ﬁles (gen-

erated by reducers of Phase-1 job).

Listing 27.4: map() for Linear Regression for Phase-1
/**
* @param key is generated by Hadoop (ignored here)
* @param value's format: <gene_id_and_ref><;><bioset_id><,><gene_value>
*/
map(key, value) {

String line = value.toString().trim();
if ((line == null) || (line.length() == 0)) {

return;

}

String[] tokens = StringUtils.split(line, ";");
String gene_id_and_ref = tokens[0];
String bioset_id_and_value = tokens[1];
if (tokens.length == 2) {

// prepare (key, value) for reducer

emit(gene_id_and_ref, bioset_id_and_value);

}

}

Listing 27.5: reduce() for Linear Regression for Phase-1

public class LinearModelReducer extends Reducer<Text, Text, NullWritable,

Text> {

// instance variables
private Configuration conf = null;
private String type = null;
// biosetIDs as Strings : NOTE oreder of biosets are VERY IMPORTANT
public List<String> biosets = null;
// NOTE: oreder of time items are VERY IMPORTANT
public List<Double> time = null;

// will be run only once
public void setup(Context context) {

this.conf = context.getConfiguration();

this.type = conf.get("type");

690

// get parameters from Hadoop's configuration
String biosetsAsString = conf.get("biosets");
this.biosets = DataStructuresUtil.splitOnToListOfString(

biosetsAsString, ",");

String timeAsCommaSeparatedString = conf.get("time");
this.time = DataStructuresUtil.toListOfDouble(

timeAsCommaSeparatedString);

}

// key = geneid_and_ref
// values = { biosetID,value }
public void reduce(Text key, Iterable<Text> values, Context context) {

//
// we will generate the following per key
// (( key=<geneID><r{1,2,3,4}> [example of key: 1234r2] ))
// <geneID><;><V1, V2, ..., Vn><;><T1,T2, ..., Tn>
// where V's are gene values and T's are time values
//
// T1 is for V1
// T2 is for V2
// ...
// Tn is for Vn
//
int numberOfValues = 0;
Iterator<Text> iter = values.iterator();
StringBuilder valuebuilder = new StringBuilder(); // generates

geneID; V1, V2, ..., Vn

StringBuilder timebuilder = new StringBuilder(); // generates T1, T2

, ..., Tn

valuebuilder.append(key.toString());
valuebuilder.append(";");

while (iter.hasNext()) {

Text pairAsText = iter.next();
if (pairAsText == null) {

continue;

}
String pairAsString = pairAsText.toString();
String[] tokens = StringUtils.split(pairAsString, ",");
// biosetID = tokens[0]
// value = tokens[1]
if (tokens.length != 2) {

691

// we are done here, all values must be present for linear

model

// no need to write anything to hadoop
continue;

}

int index = biosets.indexOf(tokens[0]);
if (index == -1) {

// biosetID not found
continue;

}

// biosetID found at index
// biosets.get(index) = biosetID;
double valueAsDouble = Double.parseDouble(tokens[1]);

// update value
valuebuilder.append(valueAsDouble);
valuebuilder.append(",");

// update time
timebuilder.append(time.get(index));
timebuilder.append(",");

numberOfValues++;

}

if (numberOfValues > 2) {

// prepare reducer for output
String geneAndValues = valuebuilder.toString();
// chop off the last ","
String geneAndValuesFinal = geneAndValues.substring(0,

geneAndValues.length()-1);

String timesAsString = timebuilder.toString();
// chop off the last ","
String timeFinal = timesAsString.substring(0, timesAsString.length

()-1);

// reducerValue = <geneID><;><V1, V2, ..., Vn><;><T1,T2, ..., Tn>
Text reducerValue = new Text(geneAndValuesFinal + ";" + timeFinal)

;

context.write(null, reducerValue);

}

}

692

}

27.9.2 MapReduce Solution using R’s Linear Model:

Phase 2

This phase has a mapper, but no reducers are reqquired. The map() func-
tion will read text ﬁles (output of Phase-1 reduce() function) and then call
R’s lm() (linear model function). The input for map() function will be the
following HDFS ﬁles generated by reducers of Phase-1 (if we had 30 reducers
in Phase-1, then we will have 30 input ﬁles for mappers of Phase-2):

/<hdfs-output-directory>/part-00000
/<hdfs-output-directory>/part-00001
...
/<hdfs-output-directory>/part-00029

The input to map() function of Phase-2 will be theses HDFS ﬁles (gener-
ated by reducers of Phase-1 job). The map() of Phase-2 will pass each ﬁle to
a shell script, which will call R’s lm() function. R processing becomes very
eﬃcient when we bundle lots of input in text ﬁles (this way we can launch
only one R process and call lm() once per record read from input ﬁles.

The foolowing R script (as a template , we use FreeMarker to generate

the actual Linux shell script) shows how linear model (lm()) is invoked:

$ cat linear_model.template.r

1 #!/usr/local/bin/Rscript
2 # input_file is part-nnnnn file in local file system
3 input_file = "${input_file}"
4 cat("input_file=", input_file, "\n")
5 output_file = "${output_file}"
6 cat("output_file=", output_file, "\n")

7

8 #
9 # each record for file will have the following format
10 # <geneID><;><V1, V2, ..., Vn><;><T1,T2, ..., Tn>
11 #

693

"1,2,3"

" 4,5,6"

12 # > a = "g1;1,2,3; 4,5,6"
13 # > items = unlist(strsplit(a, ";"))
14 # > items
15 # [1] "g1"
16 # > geneID = items[[1]]
17 # > geneID
18 # [1] "g1"
19 # > value = as.double(unlist(strsplit(items[[2]], ",")))
20 # >value
21 # [1] 1 2 3
22 # > time = as.double(unlist(strsplit(items[[3]], ",")))
23 # >time
24 # [1] 4 5 6
25 #

26
27 linear_model_fun <- function(line){

items = unlist(strsplit(line, ";"))
geneID = items[[1]]
#cat(geneID, "\n")
value = as.double(unlist(strsplit(items[[2]], ",")))
#cat(value, "\n")
time = as.double(unlist(strsplit(items[[3]], ",")))
#cat(time, "\n")
fit = lm(value ~ time)
intercept = fit$coef[1]
slope =
pvalue =
anova(fit)$’Pr(>F)’[1]
rsquare = summary(fit)$r.squared
cat(geneID, intercept, slope, pvalue, rsquare, "\n", file=output_file, append=TRUE)

fit$coef[2]

28

29

30

31

32

33

34

35

36

37

38

39

40

41 }

42

43 conn <- file(input_file, open="r")
44 while(length(line <- readLines(conn, 1)) > 0) {

45

try.output <- try( linear_model_fun(line) )

46 }
47 close.connection(conn)

694

27.9.3 Hadoop Implementation using using R’s Linear

Model

Our Hadoop Implementation is comprised of the following classes (note that
there are no reducers for phase 2):

Class Name
LinearRegressionClientPhase2.java
LinearRegressionDriverPhase2.java

Class Description
Client class to submit job
The driver class, deﬁnes input/output
and registers plug-in classes.
Deﬁnes the map() function

LinearRegressionMapperPhase2.java
LinearRegressionAnalyzerPhase2.java Deﬁnes how output data will

be read from HDFS

695

Chapter 28

MapReduce and Monoids

28.1

Introduction

This chapter is based on Jimmy Lin’s paper[13] titled ”Monoidify! Monoids
as a Design Principle for Eﬃcient MapReduce Algorithms.” Jimmy Lin clearly
deﬁnes and relates monoids as a design principle for eﬃcient MapReduce al-
gorithms. But what is a monoid, what properties deﬁnes it, and how does it
aid the MapReduce paradigm. Following abstract algebra, ”a monoid is an
algebraic structure with a single associative binary operation and an identity
element.” (source: Wikipedia1). Jimmy Lin shows that when your MapRe-
duce operations are not monoids, then it is very hard to use ”combiners”
eﬃciently. Next we will brieﬂy review MapReduce’s combiners and abstract
algebra’s monoids and see how they are related to each other.

Also, David Saile[21] states that ”recall that a monoid is an algebraic
structure with a single associative binary operation and an identity element.
For example, the natural numbers2 N form a monoid under addition with
identity element zero. In classic MapReduce, the mapper is not constrained,
but the reducer is required to be (the iterated application of) an associative
operation. Recent research argued that reduction is in fact monoidal in
known applications of MapReduce. That is, reduction is indeed the iterated
application of an associative operation ”•” with a unit u. In the case of the

1 http://en.wikipedia.org/wiki/Monoid
2The term ”natural numbers” refers either to the set of positive integers {1, 2, 3, ...}

or to the set of non-negative integers {0, 1, 2, 3, ...}

696

word-occurrence count example, reduction iterates addition ”+” with ”0” as
unit. The parallel execution schedule may be more exible if commutativity
is required in addition to associativity.”

A detailed analysis of common MapReduce computations on the basis of

monoids can be found in [4].

In MapReduce framework, the combiner (as an optional plug-in component)
is a ”local-reduce” process which operates only on data generated by one
server. Successful use of combiners reduces the amount of intermediate data
generated by the mappers on a given single server (that is why it is so-called
a local reducer). Combiners can be used as a MapReduce optimization to
reduce network traﬃc (by decreasing size of the transient data) between map-
pers and reducers. Typically, combiners have the same interface as reducers.
The combiner must have the following characteristics:

• Combiners receives as input all the data emitted by the mapper in-

stances on a given server (this is called a local aggregation)

• Combiners output is sent to the reducers — some programmers call

this as a local server reduction!

• The combiner must be side-eﬀect free; combiners may run an indeter-

minate number of times.

• The combiner must have the same input and output key types (see

example below)

• The combiner must have the same input and output value types (see

example below)

• The combiner runs in memory after the map phase

Therefore, a combiner skeleton should be deﬁned as:

Listing 28.1: Combiner Template

1 public class MyCombiner {
2

...
public void combine(KeyType key, Iterable<ValueType> values) {

3

4

5

6

...
KeyType key2 = ...;
ValueType value2 = ...;

697

...
emit(key2, value2);
...

7

8

9

}

10
11 }

This template indicates that (key, value) pairs generated by a combiner
has to match the (key, value) pairs received (as an input) by reducers. For
example, if mapper outputs (T1, T2) pairs (key is type of T1 and value is type
T2) then a combiner has to emit (T1, T2) pairs as well.

The MapReduce/Hadoop does not have a combine() function, we just use
reduce() in hadoop to implement combiners, but we use a plugin of Job.setCombinerClass()
to deﬁne a combiner class.

Furthermore, Jimmy Lin[13] concludes that ”one principle for designing ef-
ﬁcient MapReduce algorithms can be precisely articulated as follows: create
a monoid out of the intermediate value emitted by the mapper. Once we
monoidify the object, proper use of combiners and the in-mapper combin-
ing techniques becomes straightforward.”

The Haskell programming langauge has a direct support for monoids3. In
Haskell4, ”a monoid is a type with a rule for how two elements of that type
can be combined to make another element of the same type.”

28.2 Deﬁnition of Monoid

Monoid is a triplet (S, f, e), where S is a set (called underlying set of monoid)
and f : S × S → S is a mapping (called binary operation of monoid), and
e ∈ S is the identity element of monoid. A monoid with binary operation •
satisﬁes the following three axioms (note that f(a, b) = a • b):

(cid:88) Closure: for all a, b in S, the result of the operation a • b is also in S.

(cid:88) Associativity: for all a, b and c in S, the following equation holds:

(a • b) • c = a • (b • c)

3 http://www.haskell.org/haskellwiki/Monoid
4 http://blog.sigfpe.com/2009/01/haskell-monoids-and-their-uses.html

698

(cid:88) Identity element: there exists an element e in S, such that for all ele-

ments a in S, the following two equations hold:
e • a = a
a • e = a

And in mathematical notation we can write these as

(cid:88) Closure: ∀a, b ∈ S : a • b ∈ S

(cid:88) Associativity: ∀a, b, c ∈ S : (a • b) • c = a • (b • c)

(cid:88) Identity element: ∃e ∈ S : ∀a ∈ S : e • a = a • e = a

A monoid might have other properties: The monoid operator might (but
isn’t required to) obey other properties like:

(cid:88) idempotency: ∀a ∈ S : a • a = a

(cid:88) commutativity: ∀a, b, ∈ S : a • b = b • a

28.2.1 How to form a Monoid?

To form a monoid ﬁrst we need a type S, which can deﬁne a set of values
such as integers: {0, −1, +1, −2, +2, ...}. The second component is a binary
function

• : S × S → S

Then we need to make sure that for any two values x ∈ S and y ∈ S we get
a result object, the combination of x and y:

x • y : S

For example, If S is a set of integers, then the binary opearation • may be
addition (+), multiplication (×) or division (÷). Finally, as the third and
most important ingredient we need • to follow a set of laws. If it does, then
S together with • is called a monoid. We say: (S, •, e) is a monoid, where
e ∈ S is the identity element (such as 0 for addition and 1 for multiplication).
Also note that the binary division operator (÷) over a set of real numbers is
not a monoid:

((12 ÷ 4) ÷ 2) (cid:54)= (12 ÷ (4 ÷ 2))
((12 ÷ 4) ÷ 2) = (3 ÷ 2) = 1.5
(12 ÷ (4 ÷ 2)) = (12 ÷ 2) = 6.0

699

It seems that ”monoids capture the notion of combining arbitrarily many
things into a single thing together with a notion of an empty thing called
the identity. One example is addition on natural numbers. The addition
function + allows us to combine arbitrarily many natural numbers into a
single natural number, the sum. The identity is the empty sum, zero. Another
example is string concatenation. The concatenation operator allows us to
combine arbitrarily many strings into a single string. The identity is the
empty concatenation, the empty string.” (source monoids)

28.3 Monoidic and Non-Monoidic Examples

Several examples are listed below to understand the concept of monoid.

28.3.1 Subtraction over Set of Integers

The set S = {0, 1, 2, ...} is a commutative monoid for the MAX (maximum)
operation, whose identity element is 0

MAX(a, MAX(b, c)) = MAX(MAX(a, b), c)
MAX(a, 0) = MAX(0, a) = a
MAX(a, b) ∈ S

28.3.2 Subtraction over Set of Integers

Subtraction operator (−) over a set of integers does not deﬁne a monoid:
this operation is not associative:

(1 − 2) − 3 = −4
1 − (2 − 3) = 2

28.3.3 Addition over Set of Integers

Addition operator (+) over a set of integers deﬁnes a monoid: this operation
is commutative and associative and the identity element is 0:

(1 + 2) + 3 = 6
1 + (2 + 3) = 6
n + 0 = n
0 + n = n

700

we can formalize this monoid as (below e(+) deﬁnes an identity element):

S = {0, −1, +1, −2, +2, −3, +3, ...}
e(+) = 0identity element is 0
m(a, b) = m(b, a) = a + b

28.3.4 Multiplication over Set of Integers

The natural numbers, N = {0, 1, 2, 3, ...}, form a commutative monoid under
multiplication (identity element one).

28.3.5 Mean over Set of Integers

On the other hand, the natural numbers, N = {0, 1, 2, 3, ...}, does not form
a monoid under the mean (average) function (the following example shows
that the mean of means of arbitrary subsets of a set of values is not the same
as the mean of the set of values):

MEAN(1, 2, 3, 4, 5) (cid:54)= MEAN(MEAN(1, 2, 3), MEAN(4, 5))

MEAN(1, 2, 3, 4, 5) =

(1 + 2 + 3 + 4 + 5)
5

=

15
5

= 3

MEAN(MEAN(1, 2, 3), MEAN(4, 5)) = MEAN(2, 4.5) =

(2 + 4.5)
2

= 3.25

28.3.6 Non-Commutative Example

For a non-commutative example, consider the collection of all binary strings:
an element is a ﬁnite ordered sequence of 0’s and 1’s. The binary operation
is just concatenation: e.g. concat(1011, 001001) = 1011001001. The identity
element is the ”empty string”. Therefore concatenation of binary strings is
a monoid.

28.3.7 Median over Set of Integers

The natural numbers does not form a monoid under the MEDIAN function:

701

MEDIAN(1, 2, 3, 5, 6, 7, 8, 9) (cid:54)= MEDIAN(MEDIAN(1, 2, 3), MEDIAN(5, 6, 7, 8, 9))

MEDIAN(1, 2, 3, 5, 6, 7, 8, 9) =

(5 + 6)
2

= 5.5

MEDIAN(MEDIAN(1, 2, 3), MEDIAN(5, 6, 7, 8, 9)) = MEDIAN(2, 7) =

(2 + 7)
2

= 4.5

28.3.8 Concatenation over Lists

A good example is lists. Lists with concatenation (+) and the empty list (as
[]) are a monoid: for any list, we can write:

l + [] == l, [] + l = l

and concatenation is associative. Given two lists, say [1,2,3] and [7,8], you
can join them together using + to get [1,2,3,7,8]. There’s also the empty
list []. Using + to combine [] with any list gives you back the same list, for
example []+[1,2,3] = [1,2,3] and [1,2,3] + [] = [1,2,3].

28.3.9 Union/Intersection over Integers

Sets under union or intersection over a set of integers forms a monoid.

28.3.10 Functional Example

This example is from Mike Stay’s Monoids blog5. Functions from a set T to
itself under composition

S = { all functions of the form a : T → T}
e(•) = the identity function
m(a, b) = b ◦ a, where ◦ is composition of functions:
(b ◦ a)(x) = b(a(x))

For example, given the set T = {0, 1}, we have

(cid:88) S contains four possible functions from T back to itself: S = {k0, 1T , N OT, k1}
5 http://reperiendi.wordpress.com/2007/09/12/monoids/

702

(1) The constant function mapping everything to zero:

(2) The identity function:

k0 : T → T
k0(t) = 0

1T : T → T
1T(t) = t

(3) The function that toggles the input

NOT : T → T
NOT(t) = 1 − t

(4) The constant function mapping everything toone:

k1 : T → T
k1(t) = 1

(cid:88) e(•) = 1T (this is the identity function)
(cid:88) m(a, b) = b ◦ a

Not that the identity function is the unit for composition:

(a ◦ 1T)(t) = a(1T(t)) = a(t)
(1T ◦ a)(t) = 1T(a(t)) = a(t)

Exercise: verify that composition is associative.

28.3.11 Matrix Example

This matrix example is from John Perry[20]. Let N = {1, 2, 3, ...}. Let
m, n ∈ N . Then the set of m × n matrices with integer entries, written
Zm×n satises properties that make it a monoid under addition:

• closure is guaranteed by the deﬁnition;

• the associative property is guaranteed by the associative property of

its elements; and

• the additive identity is 0, the zero matrix

703

28.4 MapReduce Example: Not a Monoid

We follow the example provided by Jimmy Lin[13]. Given a large number of
key–value pairs where the keys are strings and the values are integers, the goal
is to ﬁnd the average of all the values by key. In SQL, this is accomplished
as (assuming that our mytable has key and value columns):

• Select All Data

SELECT key, value FROM mytable;
key
key1
key1
key1
key2
key2
key3
key3

value
10
20
30
40
60
20
30

• Select All Data and GROUP BY key

SELECT key, AVG(value) FROM mytable GROUP BY key;
key
key1
key2
key3

value
20
50
25

Here is the ﬁrst version of MapReduce algorithm, where the mapper is

not generating monoid outputs for the mean/average function.:

Listing 28.2: Mapper: not generating monoids

1 /**
2 * @param key a string object
3 * @param value an long associated with key
4 */
5 map(String key, Long value) {

emit(key, value);

6

7 }

704

Listing 28.3: Reducer: not receiving monoids

1 /**
2 * @param key a string object
3 * @param values as list of longs: [i1, i2, ...]
4 */
5 reduce(String key, List<Long> list) {

Long sum = 0;
Integer count = 0;
for (Long i : list) {
sum = sum + i;
count++;

}
double average = sum/count;
emit(key, average);

6

7

8

9

10

11

12

13
14 }

Two observations from the ﬁrst version of MapReduce algorithm:

• the algorithm is not very eﬃcient: since there will be too much work

by shuﬄe() and sort() functions of MapReduce framework

• We can not use the reducer as a combiner: since we know that the
mean of means of arbitrary subsets of a set of values is not the same
as the mean of the set of values.

Note that using combiners make MapReduce algorithms eﬃcient by reduc-
ing network traﬃc (you need to ensure that the combiner provides suﬃcient
aggregation) and reducing the load of shuﬄe() and sort() functions of MapRe-
duce framework. Now the question is how can we use our reducer to work as
a combiner? The answer is to make output of the mapper to be a monoid:
we change the output of a mapper. Once your mapper outputs monoids,
then combiners and reducers will behave correltly.

28.5 MapReduce Example: Monoid

We are revising the mapper to generate key-value pairs where key is the
string and value is a pair (sum, count), which has a monoid property.

705

Listing 28.4: Mapper: generating monoids

/**

* @param key a string object
* @param value a Pair(long : sum, int: count) associated with key
*/

map(String key, Long value) {
emit(key, Pair(value, 1));

}

1

2

3

4

5

6

7

As you can see, the key is the same as before, but the value is a pair of
(sum, count). Now, the output of mapper is a monoid where the identity
element is (0, 0). The element-wise sum operation can be performed as:

(a, b) ⊕ (c, d) = (a + c, b + d)

Now the mean function will be calculated correctly since mappers output

monoids:

MEAN(1, 2, 3, 4, 5) = MEAN(MEAN(1, 2, 3), MEAN(4, 5))

MEAN(1, 2, 3, 4, 5) =
MEAN(MEAN(1, 2, 3), MEAN(4, 5)) = MEAN(MEAN(6, 3), MEAN(9, 2)) = MEAN(15, 5) = 3

= 3

=

(1 + 2 + 3 + 4 + 5)
5

15
5

The revised algorithm, where mappers (deﬁned above) outputs are monoids

is presented below:

Listing 28.5: New Combiner: receiving monoid values

1 /**
2 * @param key a string object
3 * @param value is a list = [(v1, c1), (v2, c2), ...]
4 */
5 combine(String key, List<Pair<Long, Integer>> list) {

6

7

Long sum = 0;
Integer count = 0;

706

for (Pair<Long, Integer> pair : list) {

sum += pair.v;
count += pair.c

}
emit(key, new Pair(sum, count));

8

9

10

11

12
13 }

Listing 28.6: New Reducer: receiving monoid values

1 /**
2 * @param key a string object
3 * @param value is a list = [(v1, c1), (v2, c2), ...]
4 */
5 reduce(String key, List<Pair<Long, Integer>> list) {

Long sum = 0;
Integer count = 0;
for (Pair<Long, Integer> pair : list) {

sum += pair.v;
count += pair.c

}
double average = sum/count;
emit(key, average);

6

7

8

9

10

11

12

13
14 }

28.6 Hadoop Implementation of Monodized

MapReduce

The Java classes used in Monodized MapReduce solution are listed below. In
our solution, we utilized the PairOfLongInt6 class to represent a Hadoop’s
WritableComparable representing a pair consisting of a long and an int.

6 http://lintool.github.io/Cloud9/docs/api/edu/umd/cloud9/io/pair/PairOfLongInt.html

(Cloud9, developed by Jimmy Lin, is a collection of Hadoop tools that tries to make
working with big data a bit easier.)

707

Class name
MeanDriver.java
MeanMonodizedMapper.java
MeanMonodizedCombiner.java
MeanMonodizedReducer.java
SequenceFileWriterDemo.java
HadoopUtil.java
edu.umd.cloud9.io.pair.PairOfLongInt WritableComparable representing a
pair consisting of a long and an int.

Description
A driver program to submit Hadoop jobs
Deﬁnes map()
Deﬁnes combiner
Deﬁnes reduce()
Creates a sample SequenceFile
Deﬁnes some utility functions

28.7 Sample Run of Monodized Hadoop/MapRe-

duce

28.7.1 Create Input File (as a SequenceFile)

We used SequenceFileWriterDemo class to generate sample input as a SequenceFile7.
The advantage of SequenceFile(s) over text ﬁle(s) is that in
t map() function, we do not need to parse input to identify key and value
ﬁelds. SequenceFile(s) can also be compressed, either per record or per
block. To create a SequenceFile, we use SequenceFile.createWriter()
method which returns a SequenceFile.Writer instance. We then write key-
value pairs using the SequenceFile.Writer.append(key, value) method.
After we are done, we ﬁnally call the close() method.

$ java SequenceFileWriterDemo test.seq
key1 1
key1 2
key1 3
key1 4
key1 5
key2 2
key2 4
key2 6
key2 8

7http://wiki.apache.org/hadoop/SequenceFile

708

key2 10
key3 3
key3 6
key3 9
key3 12
key3 15
key4 4
key4 8
key4 12
key4 16
key4 20
key5 5
key5 10
key5 15
key5 20
key5 25

28.7.2 Create HDFS Input and Output Directories

$ hadoop fs -mkdir /monoid
$ hadoop fs -mkdir /monoid/input
$ hadoop fs -mkdir /monoid/output

28.7.3 Copy Input File to HDFS and Verify

$ hadoop fs -copyFromLoal test.seq /monoid/input/
$ hadoop fs -text /monoid/input/test.seq
key1 1
key1 2
key1 3
key1 4
key1 5
key2 2
key2 4
key2 6
key2 8
key2 10
key3 3

709

key3 6
key3 9
key3 12
key3 15
key4 4
key4 8
key4 12
key4 16
key4 20
key5 5
key5 10
key5 15
key5 20
key5 25

28.7.4 Prepare a shell script to run your MapReduce

job

$ cat run.sh
#/bin/bash

export HADOOP_HOME=/Users/mahmoud/zmp/zs/hadoop
export HADOOP_HOME_WARN_SUPPRESS=true

export JAVA_HOME=‘/usr/libexec/java_home‘
echo "JAVA_HOME=$JAVA_HOME"

PATH=.:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
export PATH=$PATH:$HADOOP_HOME/bin:$JAVA_HOME/bin

CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-ant-1.2.1.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-core-1.2.1.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-examples-1.2.1.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-test-1.2.1.jar
CLASSPATH=$CLASSPATH:$HADOOP_HOME/hadoop-tools-1.2.1.jar

710

LIB_DIR=/Users/mahmoud/zmp/map_reduce_book/hadooptests/lib
JAR_FILES=‘find $LIB_DIR -name ’*.jar’‘
for jarfile in $JAR_FILES ; do
CLASSPATH=$CLASSPATH:$jarfile
done

echo "CLASSPATH=$CLASSPATH"

export JAR=/Users/mahmoud/zmp/map_reduce_book/hadooptests/monoid/mean_as_monoid.jar
export CLASSPATH=$CLASSPATH:$JAR
export HADOOP_CLASSPATH=$CLASSPATH

javac *.java
jar cvf $JAR *.class
$HADOOP_HOME/bin/hadoop fs -rm /lib/mean_as_monoid.jar
$HADOOP_HOME/bin/hadoop fs -put $JAR /lib/
$HADOOP_HOME/bin/hadoop fs -rmr /monoid/output
$HADOOP_HOME/bin/hadoop jar $JAR MeanDriver /monoid/input /monoid/output

28.7.5 Run MapReduce Job

$ ./run.sh
JAVA_HOME=/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
...
added manifest
adding: HadoopUtil.class(in = 1797) (out= 840)(deflated 53%)
adding: MeanDriver.class(in = 2220) (out= 1109)(deflated 50%)
adding: MeanMonodizedCombiner.class(in = 1702) (out= 736)(deflated 56%)
adding: MeanMonodizedMapper.class(in = 1548) (out= 616)(deflated 60%)
adding: MeanMonodizedReducer.class(in = 1741) (out= 761)(deflated 56%)
adding: SequenceFileWriterDemo.class(in = 2148) (out= 1070)(deflated 50%)
Deleted hdfs://localhost:9000/lib/mean_as_monoid.jar
Deleted hdfs://localhost:9000/monoid/output
...
13/10/07 14:45:14 INFO mapred.JobClient: Running job: job_201310071402_0006
13/10/07 14:45:15 INFO mapred.JobClient: map 0% reduce 0%
13/10/07 14:45:19 INFO mapred.JobClient: map 100% reduce 0%

711

13/10/07 14:45:28 INFO mapred.JobClient: map 100% reduce 3%
...
13/10/07 14:46:05 INFO mapred.JobClient: map 100% reduce 100%
13/10/07 14:46:05 INFO mapred.JobClient: Job complete: job_201310071402_0006
...
13/10/07 14:46:05 INFO mapred.JobClient:
13/10/07 14:46:05 INFO mapred.JobClient:
13/10/07 14:46:05 INFO mapred.JobClient:
13/10/07 14:46:05 INFO mapred.JobClient:
13/10/07 14:46:05 INFO mapred.JobClient:

Reduce input records=5
Reduce input groups=5
Combine output records=5
Reduce output records=5
Map output records=25

28.7.6 View Hadoop Output

$ hadoop fs -text /monoid/output/part*
key2
key3
key4
key5
key1

6.0
9.0
12.0
15.0
3.0

28.8 Conclusion on Using Monoids

We observed that in MapReduce, if your mapper generates monoids then
you can utilize combiners for optimization and eﬃciency purposes (using
combiners reduces network traﬃc and make MapReduce’s sort() and shuﬄe()
functions more eﬃcient by processing less data). Also, we showed that how
to monodify MapReduce algorithms. The challenge to us is to monodify
our MapReduce algorithms.
In general, combiners can be used when the
function you want to apply is both commutative and associative (properties
of a monoid). For example, classic word count is a monoid over a set of
integers with the + operation (here you can use a combiner). But the mean
function (which is not associative as shown in the counter example above)
over a set of integers does not form a monoid. Therefore, if combiners used
properly, then it will signiﬁcantly cuts down the amount of data shuﬄed from
the maps to the reducers.

712

Monoids have other applications and usefullness in functional programming
as well. For example, MarkCC8 states that

”Why should we care if data structures like are monoids? Because
we can write very general code in terms of the algebraic construction,
and then use it over all of the diﬀerent operations. Monoids provide
the tools you need to build fold operations. Every kind of fold —
that is, operations that collapse a sequence of other operations into a
single value — can be deﬁned in terms of monoids. So you can write a
fold operation that works on lists, strings, numbers, optional values,
maps, and god-only-knows what else. Any data structure which is a
monoid is a data structure with a meaningful fold operation: monoids
encapsulate the requirements of foldability.”

28.9 Functors and Monoids

Now that we have seen the deﬁnition and use of monoids in MapReduce
framework, we can even apply higher-order functions (like ”functors”) to
monoids. A functor is an object that is a function (or we can say that
it is a function and object at the same time). The Java9 programming
language (JDK6 and JDK7) does not have direct concept of functors, because
functions are not ﬁrst-class objects in Java; it means that you can not pass
a function name as an argument to another function. There is a simple way
to simulate functors in Java by deﬁning an interface and a method (this is a
very simplistic simulation):

public interface FunctorSimulation<T1, T2> {

T2 apply(T1 input);

}

8

http://scientopia.org/blogs/goodmath/2012/05/13/introducing-algebraic-data-

structures-via-category-theory-monoids/

9 JDK8 has a direct support for functors and it is named lambdas (for details see

http://openjdk.java.net/projects/lambda/)

713

For details on implementation/simulation of functors in Java, you may
refer to Guava’s10 Function interface and Apache’s Commons11 Functor
interface. The Haskell12 programming language has a direct suppport for
monoids and functors. Bruno P. Kinoshita has a good example of using
Apache Commons Functor functional interfaces with Java 8 lambdas.

First, we present a ”functor” on a monoid by a simple example: Let
MONOID = (t, e, f) be a monoid, where t is a type (set of values), e is the
identity element, and f is the ”+” binary plus function:

MONOID = {

type t
val e : t
val plus : t x t -> t

}

Then we deﬁne a functor Prod as

functor Prod (M : MONOID) (N : MONOID) = {

type t = M.t * N.t
val e = (M.e, N.e)
fun plus((x1,y1), (x2,y2)) = (M.plus(x1,x2), N.plus(y1,y2))

}

Then we can deﬁne other functors such as Square as:

functor Square (M : MONOID) : MONOID = Prod M M

Also, a functor between two monoids can be deﬁned as: Let (M1, f1, e1)

and (M2, f2, e2) be monids. A functor

F : (M1, f1, e1) → (M2, f2, e2)
is speciﬁed by a an object map (monoids are categories with a single object)
and an arrow map: F : M1 → M2 and the following conditions will hold:
∀a, b ∈ M1, F(f1(a, b)) = f2(F(a), F(b))
F(e1) = e2
10 https://code.google.com/p/guava-libraries/
11 http://commons.apache.org/proper/commons-functor/
12 http://learnyouahaskell.com/functors-applicative-functors-and-monoids

714

A functor between two monoids is just a ”monoid homomorphism.” For ex-
ample, for String data type, function Length() that counts the number of
letters in a word is a monoid homomorphism.

• Length(””) = 0 (length of an empty string is 0)

• If Length(x) = m and Length(y) = n, then concatenation x + y of

strings has m+n letters, for example
Length(”String” + ”ology”) = Length(”Stringology”) = 11 = 6 + 5 =
Length(”String”) + Length(”ology”).

715

Chapter 29

The Small Files Problem

29.1

Introduction

This chapter provides an eﬃcient solution to the "small files" problem.
In general, Hadoop handles big ﬁles very well, but when the ﬁles are small,
it just passes each small ﬁle to a map() function, which is not very eﬃcient
because the number of mappers will be big. Having too many small ﬁles
can be problematic in Hadoop (a speciﬁc implementation of a MapReduce
paradigm). What does this mean? Hadoop’s distributed ﬁle system (HDFS)
default block size is 64MB (or 67,108,864 bytes). The block size is deﬁned
by a parameter called dfs.block.size. If you have an application which
deals with huge ﬁles (such as DNA-Sequencing), then you may even set this
to higher size like 128MB.

What is a small ﬁle in MapReduce/Hadoop environment? A ”small f ile” is
ﬁle which is signiﬁcantly smaller than the HDFS’s default block size. Typ-
ically, if youre using and storing small ﬁles, then you probably have lots of
them. For example, to represent a bioset for a gene-expression data type, a
ﬁle size can be from 2 to 3 MB. So, to process 1000 biosets, you need 1000
mappers (which will be very ineﬃcient – each ﬁle will be sent to a mapper).
To solve this problem, we should merge many of these small ﬁles into one and
then process them. In the case of biosets, we might merge every 20 to 25 ﬁles
into one ﬁle (where the size will be closer to 64MB). By merging these ﬁles,
we might need only 40 to 50 mappers. For details on ”small ﬁle” problem,
refer to The Small Files Problem. Also, note that Hadoop is mainly designed

716

for batch processing of large volume of data (rather than processing many
small ﬁles).

29.2 Solution to The Small Files Problem

Le’s assume that we have to process 20,000 small ﬁles (assuming that each
ﬁle size is much smaller than 64MB) and we want to process them eﬃciently
in MapReduce/Hadoop environment. If you just send these ﬁles as input by
FileInputFormat.addInputPath(Job, Path) as input, then each input ﬁle
will be sent to a mapper and you will end up with 20,000 mappers, which is
very ineﬃcient. Let dfs.block.size be 64MB. Further assume that the size
of these ﬁles are between 2 to 3 MB (so we assume that on average each small
ﬁle size is 2.5 MB). Further, assume that we have M (such as 100, 200, 300,
...) mappers available to us. The following multi-threaded algorithm (which
is a POJO and non-MapReduce) will solve the small ﬁles problem (since our
small ﬁles are in the range of 2 to 3 MB, we assume that on average they
occupy 2.5 MB — therefore we can put 25 [25 × 2.5 ≈ 64M B] small ﬁles as
a one HDFS block, which we call a bucket). Now that we can put 25 small
ﬁles into a single bucket (which its size will be less than 64MB — ideal size
for HDFS), therefore we just need 80 ( 2000 ÷ 25 = 80) mappers, which will
be very eﬃcient compared to 2000 mappers. Our algorithm puts N ﬁles (in
our example it is 25) into each bucket and then concurrently merges these
small ﬁles into one ﬁle, which the size is closer to the dfs.block.size.

Before submitting small ﬁles to MapReduce/Hadoop, we merge these small
ﬁles into big ones and then submit them into MapReduce driver program.
The following code fragment (taken from the driver program which submits
MapReduce/Hadoop jobs) shows how to merge small ﬁles into a ﬁle, where
the merged ﬁle size is closer to dfs.block.size.

Listing 29.1: Merging Small Files into a Large File

1

2

3

4

5

6

7

8

// prepare input
int NUMBER_OF_MAP_SLOTS_AVAILABLE = <M>;
Job job = <define-a-job>;
List<Path> smallFiles = <HDFS small input files: file1, file2, ...>;
int numberOfSmallFiles = smallFiles.size();
if ( NUMBER_OF_MAP_SLOTS_AVAILABLE >= numberOfSmallFiles ) {

// we have enough mappers and there is no need
// to merge or consolidate small files; each

717

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

// small file will be sent as a block to a mapper
for (Path path : smallFiles) {

FileInputFormat.addInputPath(job, path);

}

}
else {

// the number of mappers are less than the number of small files
// create and fill buckets with merged small files

// Step-1: create empty buckets (each bucket may hold a set of small files)
BucketThread[] buckets = SmallFilesConsolidator.createBuckets(

smallFiles,
NUMBER_OF_MAP_SLOTS_AVAILABLE);

// Step-2: filll buckets with small files
SmallFilesConsolidator.fillBuckets(buckets, smallFiles, job);

// Step-3: Merge small files per bucket.
// each bucket is a thread (implements Runnable interface )
// merging is done concurrently for each bucket
SmallFilesConsolidator.mergeEachBucket(buckets, job);

}

The SmallFilesConsolidator class accepts a set of small Hadoop ﬁles
and then merges these small ﬁles together into larger (size to be closer to
dfs.block.size) Hadoop ﬁles. The optimal solution is to create merged
ﬁles, when their size is less than or equal to HDFS block size. We generate
these large ﬁles (as a GUID) under the "/tmp/" directory in HDFS (of course
you can make "/tmp/" as a conﬁgurable HDFS directory):

// this directory is configurable
private static String MERGED_HDFS_ROOT_DIR = "/tmp/";
...
private static String getParentDir() {

String guid = UUID.randomUUID().toString();
return MERGED_HDFS_ROOT_DIR + guid + "/";

}

The BucketThread class enable us to concatenate small ﬁles into one big
ﬁle, which will be less than the HDFS block size. This way, we will sub-
mit less mappers with big input ﬁles. The BucketThread class implements
Runnable interface and provide the copyMerge() method, which merges

718

small ﬁles into a larger ﬁle. Since each BucketThread object implements
Runnable interface, therefore it will be able to run in its own thread. This
way all BucketThread objects can merge their small ﬁles concurrently. The
BucketThread.copyMerge() is the core method and merges all small ﬁles in
one bucket into another temporary HDFS ﬁle. For example, if a bucket holds
the following small ﬁles: {File1, File2, File3, File4}, then the merged
ﬁle will look like (note that the
t MergedFile is the concatenation of all four ﬁles):

MergedFile

File1
File2
File3
File4

Implementation of BucketThread.copyMerge() method is given below:

Listing 29.2: The copyMerge() Method

1 /**
2

3

4

5

6

7

8

9

be "/tmp/<guid>/"
be "/tmp/<guid>/id/"

parentDir will
targetDir will
targetFile will be "/tmp/<guid>/id/id"

* Copy all files in several directories to one output file (mergedFile).
*
*
*
*
*
*
*
*/

merge all paths in bucket and return a new directory
(targetDir), which holds merged paths

10
11 public void copyMerge() throws IOException {
12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

// if there is only one path/dir in the bucket,
// then there is no need to merge it
if ( size() < 2 ) {

return;

}

// here bucket.size() >= 2
Path hdfsTargetFile = new Path(targetFile);
OutputStream mergedFile = fs.create(hdfsTargetFile);
try {

for (int i = 0; i < bucket.size(); i++) {

FileStatus contents[] = fs.listStatus(bucket.get(i));
for (int k = 0; k < contents.length; k++) {

if (!contents[k].isDir()) {

InputStream smallFile = fs.open(contents[k].getPath());
try {

IOUtils.copyBytes(smallFile, mergedFile, conf, false);

}
finally {

719

32

33

34

35

36

37

38

39

HadoopUtil.close(smallFile);

}

}

} //for k

} // for i

}
finally {

HadoopUtil.close(mergedFile);

}

40
41 }

The SmallFilesConsolidator class provides 3 piece of functionality:

1. create required empty buckets: each bucket will hold a set of small ﬁles.
This will be done by SmallFilesConsolidator.createBuckets().

2. ﬁll buckets: we will place enough small ﬁles in a bucket so that the total
size of all small ﬁles will be about dfs.block.size. This behavior is
implemented by SmallFilesConsolidator.fillBuckets()

3. merge each bucket: here we will merge all small ﬁles in the bucket to
create a single large ﬁle, where its size will be about dfs.block.size.
This is accomplished by SmallFilesConsolidator.mergeEachBucket()

To demonstrate the small ﬁles problem, we will run the classic word count
with and without SmallFilesConsolidator class. For input, for each case
we will use 30 small ﬁles. As clearly we see that using SmallFilesConsolidator
outperforms the original solution. For example, using 30 small ﬁles, the ”So-
lution With SmallFilesConsolidator” ﬁnshed in 58,235 milliseconds while the
original word count with small ﬁles ﬁnished in 80,435 milliseconds.

29.2.1 Input Data

We used the following input data (30 small ﬁles) for both solutions.

# hadoop fs -ls /small_input_files/input/
Found 30 items
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--

1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff

51 2013-11-05 10:16 /small_input_files/input/Document-1
31 2013-11-05 10:16 /small_input_files/input/Document-10
31 2013-11-05 10:16 /small_input_files/input/Document-11
31 2013-11-05 10:16 /small_input_files/input/Document-12
31 2013-11-05 10:16 /small_input_files/input/Document-13
31 2013-11-05 10:16 /small_input_files/input/Document-14
51 2013-11-05 10:16 /small_input_files/input/Document-15
51 2013-11-05 10:16 /small_input_files/input/Document-16

720

-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--

1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff
1 mahmoud staff

51 2013-11-05 10:16 /small_input_files/input/Document-17
51 2013-11-05 10:16 /small_input_files/input/Document-18
51 2013-11-05 10:16 /small_input_files/input/Document-19
33 2013-11-05 10:16 /small_input_files/input/Document-2
51 2013-11-05 10:16 /small_input_files/input/Document-20
33 2013-11-05 10:16 /small_input_files/input/Document-21
33 2013-11-05 10:16 /small_input_files/input/Document-22
33 2013-11-05 10:16 /small_input_files/input/Document-23
33 2013-11-05 10:16 /small_input_files/input/Document-24
33 2013-11-05 10:16 /small_input_files/input/Document-25
33 2013-11-05 10:16 /small_input_files/input/Document-26
33 2013-11-05 10:16 /small_input_files/input/Document-27
33 2013-11-05 10:16 /small_input_files/input/Document-28
33 2013-11-05 10:16 /small_input_files/input/Document-29
31 2013-11-05 10:16 /small_input_files/input/Document-3
33 2013-11-05 10:16 /small_input_files/input/Document-30
31 2013-11-05 10:16 /small_input_files/input/Document-4
31 2013-11-05 10:16 /small_input_files/input/Document-5
31 2013-11-05 10:16 /small_input_files/input/Document-6
31 2013-11-05 10:16 /small_input_files/input/Document-7
31 2013-11-05 10:16 /small_input_files/input/Document-8
31 2013-11-05 10:16 /small_input_files/input/Document-9

29.3 Solution With SmallFilesConsolidator

In this solution we will use SmallFilesConsolidator class to merge the
small ﬁles into a larger ﬁle.

29.3.1 Java Source Files

Class name
BucketThread
HadoopUtil
SmallFilesConsolidator

Class Description
Used to merge small ﬁles to larger ﬁles
Deﬁnes some basic Hadoop utilities
Manages consolidation of small
ﬁles into a larger ﬁle

WordCountDriverWithConsolidator Wrod Count Driver with Consolidator
WordCountMapper
WordCountReducer

Deﬁnes map()
Deﬁnes reduce() and combine()

SmallFilesConsolidator Class

The SmallFilesConsolidator class is a driver class to consolidate the small
ones into ﬁles, where the size is closer to the HDFS’s block size. The main
methods are:

721

• getNumberOfBuckets(): determines the number of buckets needed for

merging all ﬁles into bigger ﬁles.

public static int getNumberOfBuckets(int totalFiles,

int numberOfMapSlotsAvailable,
int maxFilesPerBucket)

• createBuckets(): create required buckets

public static BucketThread[] createBuckets(

int totalFiles,
int numberOfMapSlotsAvailable,
int maxFilesPerBucket)

• fillBuckets(): this method ﬁlls each bucket with small ﬁles

public static void fillBuckets(
BucketThread[] buckets,
List<String> smallFiles, // list of small files
Job job,
int maxFilesPerBucket)

• mergeEachBucket(): this method merges small ﬁles to create a larger

ﬁle

public static void mergeEachBucket(BucketThread[] buckets,

Job job)

29.3.2 Sample Run

# ./run_with_consolidator.sh
JAVA_HOME=/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
added manifest
adding: BucketThread.class(in = 4068) (out= 1974)(deflated 51%)
adding: HadoopUtil.class(in = 2981) (out= 1317)(deflated 55%)
adding: SmallFilesConsolidator.class(in = 3091) (out= 1664)(deflated 46%)
adding: WordCountDriverWithConsolidator.class(in = 5277) (out= 2557)(deflated 51%)
adding: WordCountDriverWithoutConsolidator.class(in = 3280) (out= 1602)(deflated 51%)
adding: WordCountMapper.class(in = 2705) (out= 1114)(deflated 58%)
adding: WordCountReducer.class(in = 1598) (out= 665)(deflated 58%)
Deleted hdfs://localhost:9000/small_input_files/output
13/11/05 10:54:04 INFO WordCountDriverWithConsolidator: inputDir=/small_input_files/input
13/11/05 10:54:04 INFO WordCountDriverWithConsolidator: outputDir=/small_input_files/output
13/11/05 10:54:05 INFO SmallFilesConsolidator: added path: /tmp/906e6c30-c411-4a70-b68f-114ba7511e63/0
13/11/05 10:54:05 INFO SmallFilesConsolidator: added path: /tmp/906e6c30-c411-4a70-b68f-114ba7511e63/1
13/11/05 10:54:05 INFO SmallFilesConsolidator: added path: /tmp/906e6c30-c411-4a70-b68f-114ba7511e63/2
13/11/05 10:54:05 INFO SmallFilesConsolidator: added path: /tmp/906e6c30-c411-4a70-b68f-114ba7511e63/3
13/11/05 10:54:05 INFO SmallFilesConsolidator: added path: /tmp/906e6c30-c411-4a70-b68f-114ba7511e63/4

722

Launched reduce tasks=10
SLOTS_MILLIS_MAPS=34127
Total time spent by all reduces waiting after reserving slots (ms)=0
Total time spent by all maps waiting ter reserving slots (ms)=0
Launched map tasks=8
Data-local map tasks=8
SLOTS_MILLIS_REDUCES=96622

Job Counters

map 0% reduce 0%
map 25% reduce 0%

map 100% reduce 83%
map 100% reduce 100%

13/11/05 10:54:05 INFO SmallFilesConsolidator: added path: /tmp/906e6c30-c411-4a70-b68f-114ba7511e63/5
13/11/05 10:54:05 INFO SmallFilesConsolidator: added path: /tmp/906e6c30-c411-4a70-b68f-114ba7511e63/6
13/11/05 10:54:05 INFO SmallFilesConsolidator: added path: /tmp/906e6c30-c411-4a70-b68f-114ba7511e63/7
...
13/11/05 10:54:05 INFO input.FileInputFormat: Total input paths to process : 8
...
13/11/05 10:54:05 INFO mapred.JobClient: Running job: job_201311051023_0002
13/11/05 10:54:06 INFO mapred.JobClient:
13/11/05 10:54:12 INFO mapred.JobClient:
...
13/11/05 10:55:00 INFO mapred.JobClient:
13/11/05 10:55:01 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient: Job complete: job_201311051023_0002
13/11/05 10:55:02 INFO mapred.JobClient: Counters: 26
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO mapred.JobClient:
13/11/05 10:55:02 INFO WordCountDriverWithConsolidator: run(): status=true
13/11/05 10:55:02 INFO WordCountDriverWithConsolidator: submitJob(): status=0
13/11/05 10:55:02 INFO WordCountDriverWithConsolidator: returnStatus=0
13/11/05 10:55:02 INFO WordCountDriverWithConsolidator: Finished in milliseconds: 58235

Map output materialized bytes=999
Map input records=48
Reduce shuffle bytes=999
Spilled Records=96
Map output bytes=1704
Total committed heap usage (bytes)=2334351360
Combine input records=201
SPLIT_RAW_BYTES=1048
Reduce input records=48
Reduce input groups=7
Combine output records=48
Reduce output records=7
Map output records=201

FILE_BYTES_READ=579
HDFS_BYTES_READ=2140
FILE_BYTES_WRITTEN=1215442
HDFS_BYTES_WRITTEN=55
File Input Format Counters

Bytes Read=1092
Map-Reduce Framework

Bytes Written=55
FileSystemCounters

File Output Format Counters

As you can observe from the log of sample run, we have consolidated 30
HDFS small ﬁles into 8 large HDFS ﬁles:

13/11/05 10:54:05 INFO SmallFilesConsolidator: added path: /tmp/906e6c30-c411-4a70-b68f-114ba7511e63/0
13/11/05 10:54:05 INFO SmallFilesConsolidator: added path: /tmp/906e6c30-c411-4a70-b68f-114ba7511e63/1
13/11/05 10:54:05 INFO SmallFilesConsolidator: added path: /tmp/906e6c30-c411-4a70-b68f-114ba7511e63/2
13/11/05 10:54:05 INFO SmallFilesConsolidator: added path: /tmp/906e6c30-c411-4a70-b68f-114ba7511e63/3
13/11/05 10:54:05 INFO SmallFilesConsolidator: added path: /tmp/906e6c30-c411-4a70-b68f-114ba7511e63/4
13/11/05 10:54:05 INFO SmallFilesConsolidator: added path: /tmp/906e6c30-c411-4a70-b68f-114ba7511e63/5
13/11/05 10:54:05 INFO SmallFilesConsolidator: added path: /tmp/906e6c30-c411-4a70-b68f-114ba7511e63/6
13/11/05 10:54:05 INFO SmallFilesConsolidator: added path: /tmp/906e6c30-c411-4a70-b68f-114ba7511e63/7

723

29.4 Solution Without SmallFilesConsolida-

tor

This solution is just a basic word count without using the SmallFilesConsolidator
class. As we notice from the sample run (below), the total number of input
paths to process is 30, which is exactly the number of the small ﬁles we want
to process. This solution is not an optimal solution at all since every small
ﬁle will be sent to a mapper. The ideal case is to send input ﬁles, which
their size is greater than or equal to HDFS block size (Hadoop is desined for
handling large ﬁles).

...
13/11/05 10:29:13 INFO input.FileInputFormat: Total input paths to process : 30
...

29.4.1 Java Source Files

Class name
HadoopUtil
WordCountDriverWithoutConsolidator Wrod Count Driver without Consolidator
WordCountMapper
WordCountReducer

Class Description
Deﬁnes some basic Hadoop utilities

Deﬁnes map()
Deﬁnes reduce() and combine()

29.4.2 Sample Run

# ./run_without_consolidator.sh
JAVA_HOME=/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
added manifest
adding: BucketThread.class(in = 4068) (out= 1974)(deflated 51%)
adding: HadoopUtil.class(in = 2981) (out= 1317)(deflated 55%)
adding: SmallFilesConsolidator.class(in = 3091) (out= 1664)(deflated 46%)
adding: WordCountDriverWithConsolidator.class(in = 5277) (out= 2557)(deflated 51%)
adding: WordCountDriverWithoutConsolidator.class(in = 3280) (out= 1602)(deflated 51%)
adding: WordCountMapper.class(in = 2705) (out= 1114)(deflated 58%)
adding: WordCountReducer.class(in = 1598) (out= 665)(deflated 58%)
Deleted hdfs://localhost:9000/small_input_files/output
13/11/05 10:29:12 INFO WordCountDriverWithoutConsolidator: inputDir=/small_input_files/input
13/11/05 10:29:12 INFO WordCountDriverWithoutConsolidator: outputDir=/small_input_files/output
...
13/11/05 10:29:13 INFO input.FileInputFormat: Total input paths to process : 30
...
13/11/05 10:29:13 INFO mapred.JobClient: Running job: job_201311051023_0001
13/11/05 10:29:14 INFO mapred.JobClient:
13/11/05 10:29:22 INFO mapred.JobClient:
...
13/11/05 10:30:31 INFO mapred.JobClient:

map 0% reduce 0%
map 16% reduce 0%

map 100% reduce 93%

724

Launched reduce tasks=10
SLOTS_MILLIS_MAPS=144653
Total time spent by all reduces waiting after reserving slots (ms)=0
Total time spent by all maps waiting after reserving slots (ms)=0
Launched map tasks=30
Data-local map tasks=30
SLOTS_MILLIS_REDUCES=137261

Job Counters

map 100% reduce 100%

File Output Format Counters

Bytes Written=55
FileSystemCounters

13/11/05 10:30:32 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient: Job complete: job_201311051023_0001
13/11/05 10:30:33 INFO mapred.JobClient: Counters: 26
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO mapred.JobClient:
13/11/05 10:30:33 INFO WordCountDriverWithoutConsolidator: run(): status=true
13/11/05 10:30:33 INFO WordCountDriverWithoutConsolidator: returnStatus=0
13/11/05 10:30:33 INFO WordCountDriverWithoutConsolidator: Finished in milliseconds: 80435

Map output materialized bytes=3426
Map input records=48
Reduce shuffle bytes=3426
Spilled Records=306
Map output bytes=1704
Total committed heap usage (bytes)=6399668224
Combine input records=201
SPLIT_RAW_BYTES=3651
Reduce input records=153
Reduce input groups=7
Combine output records=153
Reduce output records=7
Map output records=201

FILE_BYTES_READ=1686
HDFS_BYTES_READ=4743
FILE_BYTES_WRITTEN=2687892
HDFS_BYTES_WRITTEN=55
File Input Format Counters

Bytes Read=1092
Map-Reduce Framework

725

Chapter 30

Huge Cache for MapReduce

30.1

Introduction

The purpose of this chapter is to show how to use and read a huge cache
(comprised of billios of (key, value) pairs, which can not ﬁt in commodity
server’s memory) in MapReduce algorithms. The algorithms presented in this
cahpter are generic enough and can be used in any MapReduce paradigms
(such as MapReduce/Hadoop and Spark/Hadoop).

There exist MapReduce algorithms, which might require access to some huge
(in billions of records) static reference relational tables. Typically, these ref-
erence relational tables do not change for a long period of time, but they are
needed either in map() or reduce() phase of MapReduce programs. One ex-
ample of such a table is a ”position feature” table, which is used for germline1
datatype ingestion and variant classiﬁction. The ”position feature” table
might have the following attributes (a composite key is (chromosome_id,
position)):

1Germline refers to the sequence of cells in the line of direct descent from zy-
gote to gametes, as opposed to somatic cells (all other body cells). Mutations in
germline cells are transmitted to oﬀspring; those in somatic cells are not.
source:
http://medical-dictionary.thefreedictionary.com/germline

726

Table: position feature

Characteristics
Column Name
PK-1
chromosome_id
PK-2
position
basic attribute
feature_id
basic attribute
mrna_feature_id
sequence_data_type_id basic attribute
basic attribute
mapping

In expressing your solution in MapReduce paradigm, either in map() or
reduce(), given a key=(chromosome_id, position), you want to return a
List<String> where each element of list is comprised of remaining attributes
{feature_id, mrna_feature_id, sequence_data_type_id, mapping}. For
a germline data type, a ”position feature” table can have up to 12 billion
records (which might take about one TB of disk space in MySQL or Oracle
database system). Now imagine that your mapper or reducer wants to access
the ”position feature” table for a given key=(chromosome_id, position).
Since you will be ﬁring many requests (several millions per second) of this
type, it will bring your database server down to its knees and will not scale
(this is a fact). One possible solution is to cache all static data into a hash
table and then use the hash table instead of using a relational table (as we
will see shortly in the next section, this is not a proper solution at all and it
will not scale – since the size of such a Hash Table will be about one TB and
will not ﬁt in memory).

30.2

Implementation Options

What are the optimal and pragmatic options for caching 12 billion records
in a MapReduce environment? In this section, I will present several options
and discuss the feasibility of their implementations.

• OPTION-1: Use a relational database (such as MySQL or Oracle).
This option is not a viable solution and will not scale at all. A mapper
or reducer will constantly hit the database and the database server will
not be able to handle thousands or millions of requests per second. If
even we use a set of replicated relational databases, still this option will

727

not scale out (since the number of database connections are limited for
a large set of Hadoop cluster).

• OPTION-2: Use a memcached server. Memcached2 is an in-memory
key-value store for small chunks of arbitrary data (strings, objects)
from results of database calls, API calls, or page rendering. If for every
few slave nodes you have a dedicated memcached cluster (which will
be very costly in a large cluster environment), then this is a viable
and proper option. This solution will not scale out due to high cost of
having so many expensive memcached servers.

• OPTION-3: Use a Redis server. Redis3 is an open source, BSD li-
censed, advanced key-value store.
It is often referred to as a data
structure server since keys can contain strings, hashes, lists, sets and
sorted sets. Again, if for every few slave nodes you have a dedicated
redis server (which will be very costly in a large cluster environment),
then this a viable and proper option. This solution will not scale out
due to high cost of having so many expensive redis servers (for one TB
of (key, value) pairs, Redis requires at least 6 TB of RAM).

• OPTION-4: Use a MapReduce join between your input and 12 bil-
lion static records. The idea is to ﬂatten 12 billion records and then
use a MapReduce join between this 12 billion records and your input.
Perform the join on the key=(chromosome_id, position). This is a
viable option if your input is huge too (I mean in billions rather than
in millions). For example, for a germline ingestion process, the VCF4
ﬁle will not have more than 6 million records. It is not proper to join
a table of 6 million records against 12 billion records (wast of lots of
time).

• OPTION-5: Partition 12 billion static records into small chunks (each
chuck will be 64MB – easily you can load into RAM and when not
needed you can evict it) and use Map-LRU (least recently used) Hash
Table. This simple elegant idea works very well: scales out and you

2http://memcached.org/
3http://redis.io/
4VCF – Variant Call Format – is a text ﬁle format. It contains meta-information lines,
a header line, and then data lines each containing information about a position in the
genome. For more detail, see http://samtools.github.io/hts-specs/VCFv4.2.pdf

728

do not need dedicated cache servers. This solution is detailed out in
the following sections. No matter what, in a distribted environment,
the mapper or reducer does not have an access to an unlimited amout
of memory/RAM. This solution will work out in any MapReduce envi-
ronment and does not need extra RAM for caching purposes.

30.3 Fromalizing the Cache Problem

In a nutshell, given a set of 12 billion records, the goal is to ﬁnd an associated
value for a given composite key key=(chromosome_id, position). Let’s say
that you are going to ingest a VCF ﬁle (this is our input ﬁle – it is a about 5
million records for a germline data type – your MapReduce input per job is
a VCF ﬁle) into your genome system: for every record of a given VCF, you
need to ﬁnd out:

• mutation class

• list of genes

• list of feature

• ...

To ﬁnd out detailed information per VCF record, you do need a set of static
tables such as a ”position feature” table (details were outlined in the intro-
duction section). As we discussed before, a ”position feature” table has at
least 12 billion records. The ﬁst step of a germline ingestion process is to ﬁnd
records from a ”position feature” table for a given key=(chromosome_id, position)
(every VCF record will have chromosome_id and position ﬁelds.

30.4 Elegant Scalable Solution

The solution presented here is a local cache solution. This means that every
worker/slave node of a MapReduce/Hadoop cluster will have its own local
cache (on hard disk – hard disk is cheap enough) and there will not be a
network traﬃc for accessing cache components and data. The local cache
will reside in a hard disk and brought to memory on a needed basis by using
LRU-Map cache technique. This is how it works: we assume that we have

729

a relational table called position_feature (as deﬁned in the Introduction
section of this chapter), which has over 12 billion records.

• First, we partition 12 billion records by chromosome_id (1, 2, 3, ...,
24, 25). This will give us 25 ﬁles (let’s name these ﬁles are labeled as
chr1.txt, chr2.txt, ..., chr25.txt), where each record (in these
text ﬁles per chromosome) will have the following format (note that
key=(chromosome_id, position) returns multiple records from the
relational table):

<position><;><Record1><:><Record2><:>...<:><RecordN>

and each record<i> is comprised of the following

<feature_id><,><mrna_feature_id><,><sequence_data_type_id><,><mapping>

Therefore, each raw cache data ﬁle (chr1.txt, chr2.txt, ..., chr25.txt)
corresponds to the following SQL query (you may repeat this script per
chromosome_id (the following query is for chromosome_id=1):

select position,

GROUP_CONCAT(feature_id, ’,’,

mrna_feature_id, ’,’,
seq_datatype_id, ’,’,
mapping SEPARATOR ’:’)

INTO OUTFILE ’/tmp/chr1.txt’
FIELDS TERMINATED BY ’;’
LINES TERMINATED BY ’\n’

from position_feature where chromosome_id = 1 group by position;

730

• Next we sort each of these ﬁles (chr1.txt, chr2.txt, ..., chr25.txt)
by position and generate chr1.txt.sorted, chr2.txt.sorted, ...,
chr25.txt.sorted.

• Since memory is limited (say 1 to 4 GB at most) per Mapper/Reducer
of a MapReduce job, then we partition each sorted ﬁle into chunks of
64MB (without breaking any lines). For example, to partition sorted
ﬁles into 64MB chunks we execute the following command:

#!/bin/bash
sorted=/data/positionfeature.sorted
output=/data/partitioned/
for i in {1..25} ; do

echo "i=$i"
mkdir -p $output/$i
cd $output/$i/
split -a 3 -d -C 64m $sorted/$i.txt.sorted $i.

done
exit

For example, for chromosome_id=1 we will have:

# ls -l /data/partitioned/1/
-rw-rw-r-- 1 hadoop hadoop 67108634 Feb
-rw-rw-r-- 1 hadoop hadoop 67108600 Feb
-rw-rw-r-- 1 hadoop hadoop 67108689 Feb
...
-rw-rw-r-- 1 hadoop hadoop 11645141 Feb

2 09:30 1.000
2 09:30 1.001
2 09:30 1.002

2 09:33 1.292

Note that each of these partitioned ﬁles have a range of position val-
ues. We will use these ranges in our cache implementation. Therefore,
given a chromosome_id=1 and a position, we exaclty know, which

731

partition holds the result of a query. Let’s look at the content of one
of these sorted partitioned ﬁles:

# head -2 /data/partitioned/1/1.000
6869;35304872,35275845,2,1
6870;35304872,35275845,2,1

# tail -2 /data/partitioned/1/1.000
790279;115457,21895578,12,2:115457,35079912,3,3:...
790280;115457,21895578,12,2:115457,35079912,3,3:...

You can see that all positions are sorted within each partition. To
support metadata for all partitions in using ”LRU Map”, we do need
an additional data structures to keep track of (begin, end) positions.
For each partitioned ﬁle we will keep (partition name, begin, end)
information. For example for chromosome id=1 and chromosome id=2
we will have:

# cat 1/begin_end_position.txt
1.000;6869;790280
1.001;790281;1209371
1.002;1209372;1461090
...
1.292;249146130;249236242

# cat 2/begin_end_position.txt
2.000;33814;1010683
2.001;1010684;1494487
2.002;1494488;2132388
...
2.279;242617420;243107469

The partition data structure is illustrated below.

732

Figure 30.1: Hige Cache Partition Data Structure

733

• Next, we will convert each partition (of 64MB) into a Hash Table,

implemented by MapDB5.

• Since memory is limited per Mapper/Reducer, we use LRUMap<K,V>(N)
to hold at most N MapDB data structures (each MapDB persistent Map
corresponds to one sorted partition (of 64MB). The idea of LRUMap<K,V>
is to hold at most N partitions shch that N × 64MB will be smaller than
the memory avaiable per mapper/reducer. When you want to insert
the N+1’st entry into LRUMap<K,V>(N), then the oldest entry will be
evicted (then you can properly close the MapDB object – releases all
memory and closes all ﬁle handles). For LRU Map implementation, we
use org.apache.commons.collections4.map.LRUMap<K,V>.

• The ﬁnal thing we do is to sort our input by key=(chromosome_id, position).
This sorting will minimize the eviction of MapDB entries from LRUMap<K,V>(N).
The sorting of of an input ﬁle is a huge design/implementation criteria
and it will have a big impact on the performance of our MapReduce job
(germline ingestion). Without sorting our input ﬁle, the eviction rate
might be very high. But sorting the input ﬁle will minimize the evic-
tion rate. Note that sorting input ﬁle is very fast and should not take
more than few seconds (this can be done by a Linux sort command or
you may use MapReduce/Hadoop to sort the input data).

30.5

Implementation of Elegant Scalable So-
lution

30.5.1 Use of LRU Map

For implementation of LRU (least recently used) Map, I selected the org.apache.commons.collections4.map.LRUMap<K,V>,
which is a Map implementation with a ﬁxed maximum size which removes
the least recently used entry if an entry is added when full. The least recently
used algorithm works on the get and put operations only. Iteration of any
kind, including setting the value by iteration, does not change the order (for

5MapDB is implemented by Jan Kotek and its source code is hosted at https:
//github.com/jankotek/MapDB. MapDB provides concurrent Maps, Sets and Queues
backed by disk storage or oﬀ-heap-memory. It is a fast and easy to use embedded Java
database engine (http://www.mapdb.org)

734

details, you may consult with Apache Commons Collections6. For our cache
implemetation, we extend the LRUMap class (the MapDBEntry class is a simple
class, which represents a sorted partition of 64MB as a Map data structure
implemented in MapDB.

Listing 30.1: Custom LRU Map

1 import org.apache.commons.collections4.map.LRUMap;
2
3 public class CustomLRUMap<K, V> extends LRUMap<K, V> {
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

private K key = null;
private V value = null;
private LinkEntry<K, V> entry = null;

public CustomLRUMap(final int size) {

super(size);

}

@Override
protected boolean removeLRU(final LinkEntry<K, V> entry) {
System.out.println("begin remove LRU entry ...");
this.entry = entry;
this.key = entry.getKey();
this.value = entry.getValue();

if (key instanceof String) {

String keyAsString = (String) key;
System.out.println("evicting key="+keyAsString);

}

if (value instanceof MapDBEntry) {

// release resources held by MapDBEntry
MapDBEntry mapdbEntry = (MapDBEntry) value;
mapdbEntry.close();

}

return true; // actually delete entry

}

32
33 }

30.5.2 Test LRU Map

The following test program shows how CustomLRUMap<K,V> (CustomLRUMap<K,V>
extends the LRUMap<K,V> class and redeﬁnes the eviction policy by the removeLRU()
method) works. In this example, we only keep 3 map entries at any time. No
matter how many etries you add to the LRUMap object, the LRUMap.size()

6http://commons.apache.org/proper/commons-collections/

735

can not exceed 3 (the maximum size is given at the time of creation of
CustomLRUMap<K,V> object).

Listing 30.2: Test Custom LRU Map

1 # cat CustomLRUMapTest.java
2
3 import org.apache.commons.collections4.map.LRUMap;
4
5 public class CustomLRUMapTest {
6

public static void main(String[] args) throws Exception {

7

8

9

10

11

12

13

14

15

16

17

18

19

CustomLRUMap<String, String> map = new CustomLRUMap<String, String>(3);
map.put("k1", "v1");
map.put("k2", "v2");
map.put("k3", "v3");
System.out.println("map="+map);
map.put("k4", "v4");
String v = map.get("k2");
System.out.println("v="+v);
System.out.println("map="+map);
map.put("k5", "v5");
System.out.println("map="+map);
map.put("k6", "v6");
System.out.println("map="+map);

}

20
21 }
22
23 # javac CustomLRUMapTest.java
24 # java CustomLRUMapTest
25 map={k1=v1, k2=v2, k3=v3}
26 begin removeLRU...
27 evicting key=k1
28 v=v2
29 map={k3=v3, k4=v4, k2=v2}
30 begin removeLRU...
31 evicting key=k3
32 map={k4=v4, k2=v2, k5=v5}
33 begin removeLRU...
34 evicting key=k4
35 map={k2=v2, k5=v5, k6=v6}

Listing 30.3: MapDBEntry Class

1 import java.io.File;
2 import java.util.Map;
3 import org.mapdb.DB;
4 import org.mapdb.DBMaker;
5
6 public class MapDBEntry {
7

8

9

10

private DB db = null;
private Map<String, String> map = null;

public MapDBEntry(DB db, Map<String, String> map) {

736

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

this.db = db;
this.map = map;

}

public String getValue(String key) {

if (map == null) {

return null;

}
return map.get(key);

}

// eviction policy
public void close() {

closeDB();
closeMap();

}

private void closeDB() {
if (db != null) {

db.close();

}

}

private void closeMap() {
if (map != null) {
map = null;

}

}

public static MapDBEntry create(String dbName) {

DB db = DBMaker.newFileDB(new File(dbName))
.closeOnJvmShutdown()
.readOnly()
.make();

Map<String, String> map = map = db.getTreeMap("collectionName");
MapDBEntry entry = new MapDBEntry(db, map);
return entry;

}

48
49 }

30.5.3 Use of MapDB

How do we create persistent Map<K,V> using MapDB? The following program
shows how to create a MapDB for a sorted partition ﬁle:

Listing 30.4: MapDBEntry Class

1 import org.mapdb.DB;
2 import org.mapdb.DBMaker;
3 import java.io.BufferedReader;
4 import java.io.FileReader;

737

5 import java.io.File;
6 import java.util.concurrent.ConcurrentNavigableMap;
7
8 public class GenerateMapDB {
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

public static void main(String[] args) throws Exception {

String inputFileName = args[0];
String mapdbName = args[1];
create(inputFileName, mapdbName);

}

public static void create(String inputFileName, String mapdbName)

throws Exception {
//Configure and open database using builder pattern.
//All options are available with code auto-completion.
DB db = DBMaker.newFileDB(new File(mapdbName))

.closeOnJvmShutdown()
.make();

//open an collection, TreeMap has better performance then HashMap
ConcurrentNavigableMap<String,String> map = db.getTreeMap("collectionName");

where <v> has the following format:
<feature_id><,><mrna_feature_id><,><sequence_data_type_id><,><mapping>

//
// line = <position><;><v><:><v>:...:<v>
//
//
//
String line = null;
BufferedReader reader = null;
try {

reader = new BufferedReader(new FileReader(inputFileName));
while ((line = reader.readLine()) != null) {

line = line.trim();
String[] tokens = line.split(";");
if (tokens.length == 2) {

map.put(tokens[0], tokens[1]);

}
else {

System.out.println("error line="+line);

}

}

}
finally {

reader.close(); // close input file
db.commit();
db.close();

// persist changes into disk
// close database resources

}

}

52
53 }

To query MapDB database, we can write a very simple class:

738

Listing 30.5: MapDBEntry Class

1 import java.io.File;
2 import java.util.Map;
3 import org.mapdb.DB;
4 import org.mapdb.DBMaker;
5 import org.apache.log4j.Logger;
6
7 /**
8

* This class defines basic query on MapDB.
*
*
* @author Mahmoud Parsian
*
*/
public class QueryMapDB {

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

public static void main(String[] args) throws Exception {

long beginTime = System.currentTimeMillis();
String mapdbName = args[0];
String position = args[1];
THE_LOGGER.info("mapdbName="+mapdbName);
THE_LOGGER.info("position="+position);
String value = query(mapdbName, position);
THE_LOGGER.info("value="+value);
long elapsedTime = System.currentTimeMillis() -beginTime;
THE_LOGGER.info("elapsedTime (in millis) ="+elapsedTime);
System.exit(0);

}

public static String query(String mapdbName, String key) throws Exception {
String value = null;

DB db = null;
try {
db = DBMaker.newFileDB(new File(mapdbName))
.closeOnJvmShutdown()
.readOnly()
.make();
Map<String, String> map = map = db.getTreeMap("collectionName");

value = map.get(key);

}
finally {

if (db != null) {

db.close();

}

}
return value;

}

47
48 }

739

30.5.4 Test of MapDB: put() and get()

30.5.4.1 Test of MapDB: put()

# javac GenerateMapDB.java
# javac QueryMapDB.java

# cat test.txt
19105201;35302633,35292056,2,1:20773813,35399339,2,1
19105202;35302633,35292056,2,1:20773813,35399339,2,1
19105203;35302633,35284930,2,1:35302633,35292056,2,1:20773813,35399339,2,1
19105204;35302633,35284930,2,1:35302633,35292056,2,1:20773813,35399339,2,1

# java GenerateMapDB test.txt mapdbtest
# ls -l mapdbtest*
-rw-r--r-- 1 mahmoud
-rw-r--r-- 1 mahmoud

staff 32984 Feb 11 16:40 mapdbtest
staff 13776 Feb 11 16:40 mapdbtest.p

As you can observe from the generated output, MapDB generates 2 ﬁles
(mapdbtest and mapdbtest.p) for each persistent hash table.

30.5.4.2 Test of MapDB: get()

# java QueryMapDB mapdbtest 19105201
Feb 11 2014 16:41:16 [main] [INFO ] [QueryMapDB] - mapdbName=mapdbtest
Feb 11 2014 16:41:16 [main] [INFO ] [QueryMapDB] - position=19105201
Feb 11 2014 16:41:16 [main] [INFO ] [QueryMapDB] - value=35302633,35292056,2,1:20773813,35399339,2,1
Feb 11 2014 16:41:16 [main] [INFO ] [QueryMapDB] - elapsedTime (in millis) = 2

# java QueryMapDB mapdbtest 19105202
Feb 11 2014 16:41:21 [main] [INFO ] [QueryMapDB] - mapdbName=mapdbtest
Feb 11 2014 16:41:21 [main] [INFO ] [QueryMapDB] - position=19105202
Feb 11 2014 16:41:21 [main] [INFO ] [QueryMapDB] - value=35302633,35292056,2,1:20773813,35399339,2,1
Feb 11 2014 16:41:21 [main] [INFO ] [QueryMapDB] - elapsedTime (in millis) = 2

# java QueryMapDB mapdbtest 191052023333

740

Feb 11 2014 16:41:55 [main] [INFO ] [QueryMapDB] - mapdbName=mapdbtest
Feb 11 2014 16:41:55 [main] [INFO ] [QueryMapDB] - position=191052023333
Feb 11 2014 16:41:55 [main] [INFO ] [QueryMapDB] - value=null
Feb 11 2014 16:41:55 [main] [INFO ] [QueryMapDB] - elapsedTime (in millis) = 1

30.6 MapReduce Using LRU-Map-Cache

Now that we have an eﬃcient LRU-Map-Cache, we may use it either in map()
or reduce() functions. To use LRU-Map-Cache in map() or reduce(), you
need to do the following (this can be applied in mapper or reducer class):

• FIRST: Initialize and set up LRU-Map-Cache. This step can be ac-

complished in the setup() method. This will done once.

• SECOND: Use the LRU-Map-Cache in map() or reduce(). This will

be done many times.

• FINALLY: Close the LRU-Map-Cache objects (to release all non-needed
resources). This step can be accomplished in the cleanup() method.
This will done once.

To make these steps easier, we deﬁne a service class called CacheManager,

which can be used as:

Listing 30.6: CacheManager Usage

try {

//
// initialize cache
//
CacheManager.init();

//
// use cache
//
String chrID = ...;
String position = ...;
List<String> valueAsList = CacheManager.get(chrID, position);

}
finally {
//
// close cache
//

741

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

}

CacheManager.close();

30.7 CacheManager Deﬁnition

CacheManager is a service class, which provides 3 basic services: initilization,
service, and closing cache. Since this is a service class, all methods are deﬁned
as static. The BeginEndPosition object implements the partition data
structures such that you can get the Db name (a 64MB hash table) for a
given key of (chrID, position).

Listing 30.7: CacheManager Deﬁnition

1 public class CacheManager {
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

private static final int DEFAULT_LRU_MAP_SIZE = 128;
private static int theLRUMapSize = DEFAULT_LRU_MAP_SIZE;

private static CustomLRUMap<String, MapDBEntry<String, String>> theCustomLRUMap = null;
private static BeginEndPosition beginend = null;
private static String mapdbRootDirName = "/data/mapdb/pf";
private static String mapdbBeginEndDirName =
private static boolean initialized = false;

"/data/mapdb/pf/begin_end_position";

public static void setLRUMapSize(int size) {

theLRUMapSize = size;

}

public static int getLRUMapSize() {

return theLRUMapSize;

}

// initialize the LRUMap
public static void init() throws Exception {...}

// initialize the LRUMap
public static void init(int size) throws Exception {...}

// close the cache database in the LRUMap
public static void close() throws Exception {...}

// get value from the cache database for a given (chrID, position).
public static String get(int chrID, int position) throws Exception {...}

// get value from the cache database for a given (chrID, position).
public static String get(String chrID, String position) throws Exception {...}

// close the cache database in the LRU-Map-Cache
public static void close() throws Exception {...}

742

37
38 }

30.7.1 CacheManager Initilization

Listing 30.8: CacheManager Initialization

public static void setLRUMapSize(int size) {

theLRUMapSize = size;

}

public static int getLRUMapSize() {

return theLRUMapSize;

}

// initialize the LRUMap
public static void init() throws Exception {

if (initialized) {

return;

}
theCustomLRUMap = new CustomLRUMap<String, MapDBEntry<String, String>>(theLRUMapSize);
beginend = new BeginEndPosition(mapdbBeginEndDirName);
beginend.build(mapdbRootDirName);
initialized = true;

}

// initialize the LRUMap
public static void init(int size) throws Exception {

if (initialized) {

return;

}
setLRUMapSize(size);
init();

}

30.7.2 CacheManager Closing

Listing 30.9: CacheManager Closing

// close the cache database in the LRUMap
public static void close() throws Exception {

if (theCustomLRUMap != null) {

for (Map.Entry<String, MapDBEntry<String, String>> entry : theCustomLRUMap.entrySet()) {

entry.getValue().close();

}

743

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

1

2

3

4

5

6

7

8

}

}

30.7.3 CacheManager Usage

Listing 30.10: CacheManager Usage

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

/**
* Get value from the LRU-Map-Cache for a given (chrID, position).
* @param chrID chrID
* @param position position
*/
public static String get(int chrID, int position) throws Exception {

return get(String.valueOf(chrID), String.valueOf(position));

}

/**
* Get value from the cache database (value is the snpID) for a given (chrID, position).
* @param chrID chrID
* @param position position
*/
public static String get(String chrID, String position) throws Exception {

String dbName = getDBName(chrID, position);
if (dbName == null) {
return null;

}
// now return the cache vale
MapDBEntry<String, String> entry = theCustomLRUMap.get(dbName);
if (entry == null) {

entry = MapDBEntryFactory.create(dbName);
theCustomLRUMap.put(dbName, entry);

}
return entry.getValue(position);

}

private static String getDBName(String chrID, String position){

// query parameters are: chrID and position
List<Interval> results = beginend.query(chrID, position);
if ((results == null) || (results.isEmpty()) || (results.size() == 0)) {

return null;

}
else {

return results.get(0).db();

}

}

38
39 }

744

Chapter 31

Bloom Filter

31.1

Introduction

The simple goal of this chapter is introduce the cocept of ”Bloom ﬁlter”
and use it in a ”reduce-side join” which engages a Bloom ﬁlter on the
map phase of a MapReduce job. What is a Bloom ﬁlter? How it can
be used in a MapReduce environment? How can it speed up a join op-
eration between two big relations/tables? According to Wikipedia: ”A
Bloom ﬁlter is a space-eﬃcient probabilistic data structure, conceived by
Burton Howard Bloom in 1970, that is used to test whether an element
is a member of a set. False positive matches are possible, but false nega-
tives are not; i.e. a query returns either possibly in set or definitely
not in set. Elements can be added to the set, but not removed (though
this can be addressed with a ”counting” ﬁlter). The more elements that
are added to the set, the larger the probability of false positives” (source:
http://en.wikipedia.org/wiki/Bloom_filter). The Bloom ﬁlter data
structure may return true for elements that are not actually members of the
set (this is called false-positives errors), but it will never return false for ele-
ments that are in the set; for each element in the set, the Bloom ﬁlter must
return true. There is a very nice tutorial on the Bloom ﬁlter by Bill Mill.
This is another good introduction to Bloom ﬁlter data structure by Jacob
Honorooﬀ.

Therefore, in a nutshell, we can summarize Bloom ﬁlter properties as:

• Given a big set S = {x1, x2, ..., xn}, Bloom ﬁlter is a probabilistic,

745

fast, and space eﬃcient cache builder for a big data set; this is basically
approximating set membership operation:

Is x ∈ S?

• It tries to answer lookup questions: does item "x" exist in a set

S?

• It allows false positive errors, as they only cost us an extra data
set access. This means that for some x, which is not in the set, Bloom
ﬁlter might indicate that x is in the set.

• It does not allow false negative errors, because they result in wrong
answers. This means that if x is not in the set, then for sure it will
indicate that x is not in the set. Thus, the Bloom ﬁlter does not allow
false negatives, but can allow false positives.

Let’s focus on a simple join example between two relations/tables: let’s say
that we want to join R(a, b) and S(a, c) on a common ﬁeld a. Further
assume that

size(R) = 1000, 000, 000(larger data set)

size(S) = 10, 000, 000(smaller data set)

To do basic join, we need to check 10,000,000,000,000,000 records, which
is very huge and time consuming process. One idea to reduce time and
complexity of join operation between R and S is to use a Bloom ﬁlter on
relation S (smaller data set) and then use the built Bloom ﬁlter data structure
on relation R. This can eliminate the non-needed records from R (it might
reduce it to 20,000,000) and hence the join becomes fast and eﬃcient.

Next we semi-formalize Bloom ﬁlter data structure: what is involved in
Bloom ﬁlter probabilistic data structures? How do we construct one? what
is the probability of false positive errors, and how we can decrease the
probability of false positive errors. This is how it works:

• Given a big set S = {x1, x2, ..., xn}

746

• Let B be an m ( m > 1 ) bit array, initialized with 0s. B’s elements are
B[0], B[1], B[2], ..., B[m-1]. The memory required for array B is only a
fraction of the one needed for storing the whole set S. By selecting the
bigger bit vector (array B), the probability of false positive rate will
decrease.

• Let {H1, H2, ..., Hk} be a set of k hash functions, If Hi(xj) = a then
set B[a] = 1. You may use SHA1, MD5, and Murmer as hash functions.
For example, you may use the following as hash functions:

– Hi(x) = M D5(x + i)
– Hi(x) = M D5(x||i)

• To check if x ∈ S, check B at Hi(x). All k values must be 1.
• It is possible to have a false positive; all k values are 1, but x is not in

S.

• What is the probability of false positives?

the probability of false
positives is (for details, see http://en.wikipedia.org/wiki/Bloom_
filter):

´

1 − r1 −

skn

1
m

¯

k

´
1 − e−kn/m

¯

k

≈

• What are the optimal hash functions? What is the optimal number
of hash functions? For a given m (number of bits selected for Bloom
ﬁlter) and n (size of big data set), the value of k (the number of hash
functions) that minimizes the probability of false positives is (ln stands
for ”natural logarithm”1)

k =

m
n

ln(2)

m = −

nln(p)
(ln(2))2

1Natural logarithm is the logarithm to the base e of a number, where e is the Euler’s

number: 2.71828183. Let x = ey, then ln(x) = loge(x) = y.

747

• Therefore, the probability that a speciﬁc bit has been ﬂipped to 1 is:

1 − p1 −

qkn ≈ 1 − e−kn
m

1
m

• Following Wikipedia: ”unlike a standard hash table, a Bloom ﬁlter
of a ﬁxed size can represent a set with an arbitrary large number of
elements; adding an element never fails due to the data structure ”ﬁlling
up.” However, the false positive rate increases steadily as elements are
added until all bits in the ﬁlter are set to 1, at which point all queries
yield a positive result.”

31.2 A Simple Bloom Filter Example

In this example, we show how to insert and query on a bloom ﬁlter of size 10
(m = 10) with three hash functions H = {H1, H2, H3} and let H(x) denote
the result of the three hash functions (H(x) = {H1(x), H2(x), H3(x)}). We
start with a 10-bit long array B initilized to 0:

Array B:

initialized:

index 0 1 2 3
value 0 0 0 0

4 5 6 7 8 9
0 0 0 0 0 0

insert element a, H(a) = (2, 5, 6)

index 0 1 2 3
value 0 0 1 0

4 5 6 7 8 9
0 1 1 0 0 0

insert element b, H(b) = (1, 5, 8)

index 0 1 2 3
value 0 1 1 0

4 5 6 7 8 9
0 1 1 0 1 0

query element c
H(c) = (5, 8, 9) => c is not a member (since B[9]=0)

query element d
H(d) = (2, 5, 8) => d is a member (False Positive)

748

query element e
H(e) = (1, 2, 6) => e is a member (False Positive)

query element f
H(f) = (2, 5, 6) => f is a member (Positive)

31.3 Bloom Filter in Guava Library

The Guava2 library provides an implementation of a Bloom ﬁlter. This
is how it works: you deﬁne your basic type (Person, which will be used
in the Bloom ﬁlter (this example is from the http://code.google.com/p/
guava-libraries/wiki/HashingExplained):

class Person {

final int id;
final String firstName;
final String lastName;
final int birthYear;
Person(int id, String firstName, String lastName, int birthYear){

this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.birthYear = birthYear;

}

}

Then you deﬁne a Funnel of the basic type, which you want to use Bloom
ﬁlter: a Funnel describes how to decompose a particular object type into
primitive ﬁeld values. our Funnel might look like

Funnel<Person> personFunnel = new Funnel<Person>() {

2http://code.google.com/p/guava-libraries/

749

@Override
public void funnel(Person person, PrimitiveSink into) {

into

.putInt(person.id)
.putString(person.firstName, Charsets.UTF_8)
.putString(person.lastName, Charsets.UTF_8)
.putInt(birthYear);

}

};

Once Funnel<T> is deﬁned, then we can deﬁne and use a Bloom ﬁlter:

List<Person> friendsList = {Person1, Person2, ...};
BloomFilter<Person> friends = BloomFilter.create(personFunnel, 500, 0.01);
for(Person friend : friendsList) {

friends.put(friend);

}

// much later, use the Bloom filter
Person dude = new Person(100, "Alex", "Smith", 1967);
if (friends.mightContain(dude)) {

// the probability that dude reached this place
// if he isn’t a friend is 1% (0.01), we might,
// for example, start asynchronously loading things
// for dude while we do a more expensive exact check

}

The Guava library provide the following hash functions for building a Bloom
ﬁlter data structure:

• md5()

• murmur3_128()

• murmur3_32()

• sha1()

750

• sha256()

• sha512()

• goodFastHash(int bits)

31.4 Using Bloom Filter in MapReduce

Bloom ﬁlter is a small, compact, and fast data structure for set membership.
It can be used in the join of two relations/tables such as R(a, b) and S(a,
c) where one of the relations has huge number of records (for example, R
to have 1000,000,000 records) and the other relation has small number of
records (for example, S to have 10,000,000 records). To do a join on ﬁeld ”a”
between R and S, it will take a long time and it is ineﬃcient. We can use
Bloom ﬁlter data structure in the following way: build a Bloom ﬁlter out of
relation S(a, c), and then want to test values R(a, b) for membership using
the built Bloom ﬁlter. Note that, for reduce-side join optimization, we use of
a Bloom ﬁlter on the map tasks, which will force an I/O cost reduction for
the MapReduce job. How do we use the Bloom ﬁlter concept? The following
is one way to have an optimized reduce-side join with the use of a Bloom
ﬁlter: we implement it in two steps:

• STEP-1: construction of the bloom ﬁlter; this a Mapreduce job which
uses the smaller of the two relations/tables for constructing the bloom
ﬁlter data structure. For this step only mappers are needed to construct
the Bloom ﬁlter data structure (more than one Bloom ﬁlters will be
built — one per mapper).

• STEP-2. use of the the Bloom ﬁlter data structure (built in STEP-1)

in the reduce-side join

Listing 31.1: Join R and S
joinResult = {};
for all tuples r in R {

for all tuples s in S {

if (joinConditionSatisfied(r, s)) {

// join condition can be like r.a == s.b

751

add (r;s) to the joinResult;

}

}

}

752

Appendices

753

Appendix A

Bioset

A.1

Introduction

Biosets (also called ”gene signatures”1 ) and ”assays”2) encompass data in
the form of experimental sample comparisons (for transcriptomic, epigenetic,
and copy number variation data), as well as genotype signatures (for GWAS
and mutational data).

A bioset has an associated data type (a data type can be ”gene-expression”,
”protein-expression”, ”methylation”, ”copy-number-variation”, ”miRNA”,
or ”somatic mutation”). Also, each bioset entry/record has an associated
reference type (a reference type can be r1=normal, r2=disease, r3=paired,
or r4=unknown). Note that a reference type does not apply to ”somatic
mutation” data type.

The number of entries/records per bioset does depend on the data type

of a bioset (see the following table):

1A gene signature is the group of genes in a type of cell whose combined expression
pattern is uniquely characteristic of a medical or other condition. Ideally, the gene signa-
ture can be used to select a group of patients at a speciﬁc state of a disease with accuracy
that facilitates selection of treatments. (source: http://en.wikipedia.org/wiki/Gene_
signature)

2An assay is an investigative (analytic) procedure in laboratory medicine, pharmacol-
ogy, environmental biology, and molecular biology for qualitatively assessing or quantita-
tively measuring the presence or amount or the functional activity of a target entity (the
analyte), which can be a drug or biochemical substance or a cell in an organism or organic
sample. (source: http://en.wikipedia.org/wiki/Assay)

754

Bioset Data Type
Somatic Mutation
Methylation
Gene Expression
Copy Number Variation
Germline
Protein Expression
miRNA

Number of Entries/Records
3,000
30,000
50,000
40,000
4,300,000
30,000
30,000

755

Appendix B

Spark RDDs

B.1

Introduction

Sparks main abstraction is a distributed collection of items (such as collection
of log records, FASTQ sequences, employee records) called a Resilient Dis-
tributed Dataset (RDD). RDDs can be created from Hadoop InputFormats
(such as HDFS ﬁles) or by transforming other RDDs. The purpose of this
appendix chapter is to introduce Spark RDDs by simple Java examples. The
purpose is not to dive into architectural[33] details of RDDs, but merely how
to use and utilize them in MapReduce programs. Usage of RDDs are pre-
sented by simple data examples. As a user, you can consider an RDD as a
handle for a collection of items of type T, which are the result of some compu-
tation (type T can be any standard Java data types – such as String, Integer,
Map, List, ... – or any custom objects such as Employee, Mutation, ...). RDD
has actions (such as reduce(), collect(), count(), saveAsTextFile(), ...)
and transformations (such as map(), filter(), union(), groupByKey(), ...)
can be used for more complex computations. All the examples provided here
are based on Spark 1.1.0. Also in Spark, there is a heavy use of tuples
(such as scala.Tuple2 (tuple of 2 elements) and scala.Tuple3 (tuple of 3
elements)).

756

B.2 What is a TupleN?

scala.Tuple<N> represents a composite data type of N elements. Spark API
use scala.Tuple2 and scala.Tuple3 for for composite data types and are
described below:

• scala.Tuple2: represents a tuple of 2 elements; some examples are

provided below:

Listing B.1: Example of Tuple2

1 import scala.Tuple2;
2 import java.util.List;
3 import java.util.Arrays;
4 ...
5 Tuple2<String,Integer> t21 = new Tuple2<String,Integer>("abc", 234);
6 String str21 = t21._1; // str21 holds "abc"
7 Integer int21 = t21._2; // int21 holds 234
8
9 List<Integer> listofint = Arrays.asList(1, 2, 3);
10 Tuple2<String,List<Integer>> t22 =
11
12 String str22 = t22._1;
13 List<Integer> list22 = t22._2; // int21 points to List(1, 2, 3)

new Tuple2<String,List<Integer>>("z1z2", listofint);

// str22 holds "z1z2"

• scala.Tuple3: represents a tuple of 3 elements; a simple example is

provided below:

Listing B.2: Example of Tuple3

1 import scala.Tuple3;
2 import java.util.List;
3 import java.util.Arrays;
4 ...
5 List<String> listofstrings = Arrays.asList("a1", "a2", "a3");
6 Tuple3<String,Integer, List<String>> t3 =
7
8 String str3 = t3._1;
9 Integer int3 = t3._2;
10 List<String> list3 = t3._3; // list3 points to List("a1", "a2", "a3")

// str3 holds "a1a2"
// int3 holds 567

new Tuple3<String,Integer, List<String>>("a1a2", 567, listofstrings);

• Note that scala.Tuple4 through scala.Tuple22 are deﬁned as part

of Java Spark API.

757

B.3 What is an RDD

An RDD stands for a Resilient Distributed Dataset, which is the basic data
abstraction in Spark. As class and interface are the fundamental units
of abstractions in Java, JavaRDD and JavaPairRDD are fundamental units
of data abstractions in Spark. It means that to perform map(), reduce()
, or groupByKey() operations, you use an RDD as input and output. By
deﬁnition, an RDD represents an immutable1, partitioned collection of el-
ements that can be operated on in parallel. This means that if I have
JavaRDD<String>, which has 100M elements, then it can be partitioned into
10, 100, or 1000 segments and each segments can be operated independently
(this partitioning is important and does depend on your cluster size, num-
ber of cores available per server, and the total amount of RAM available
in your cluster – there is no silver bullet for ﬁnding the proper number of
partition; but this can be properly set by some trial and experience). For
details of RDD properties, read http://www.cs.berkeley.edu/~pwendell/
strataconf/api/core/spark/RDD.html.

JavaRDD and JavaPairRDD are members of the org.apache.spark.api.java
package and deﬁned as:

Listing B.3: JavaRDD and JavaPairRDD

public class JavaRDD<T> ...
// represents elements of type T
// Examples of JavaRDD<T> are:
//
//
//
//
//

JavaRDD<String>
JavaRDD<Integer>
JavaRDD<Map<String, Long>>
JavaRDD<Employee>
...

public class JavaPairRDD<K,V> ...
// represents pairs of (key,value) of type K and V
// Examples of JavaPairRDD<K,V> are:
//
//
//
//

JavaPairRDD<String,Integer>
JavaPairRDD<String, Tuple2<Integer,Integer>>
JavaPairRDD<Integer, Map<String, Long>>
...

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

1RDDs are read-only and can not be modiﬁed or updated.

758

B.4 How to Create RDDs

For most of the MapReduce applications, RDDs are created by JavaContextObject,
JavaRDD and JavaPairRDD. Initial/ﬁrst RDDs are created by JavaContextObject
and subsequent RDDs are created by many other classes including JavaRDD
and JavaPairRDD. For most of the applications, this is the order to create
and manipulate RDDs:

• First, create a JavaContextObject: this can be accomplished in many
ways: you may create this object by using ”Spark master URL” or by
using ”YARN’s resource manager host name”. You may use SparkUtil2
class to create JavaContextObject. Also, you may create JavaContextObject
by the following code:

1 import org.apache.spark.SparkConf;
2 import org.apache.spark.api.java.JavaSparkContext;
3 ...
4 // create JavaSparkContext
5 SparkConf sparkConf = new SparkConf().setAppName("myapp");
6 JavaSparkContext ctx = new JavaSparkContext(sparkConf);

• Second, once you have an instance of JavaContextObject, then you
may create RDDs. RDDs can be created from many diﬀerent sourcees:
from Java collections objects, from text ﬁles, from HDFS ﬁles (text or
binary).

• Third, once you have an instance of JavaRDD or JavaPairRDD, then cre-

ation of new RDDs are accomplished easily by using map(), reduceByKey(),
filter(), groupByKey(), ... methods. You may create RDDs: by us-
ing Java collection objects or by reading ﬁles (text ﬁles or text/binary
HDFS ﬁles).

B.5 Create RDDs by Collection Objects

You may create RDDs by Java collection objects. Te following simple exam-
ple, create an RDD (called rdd1) from a java.utl.List object:

2https://github.com/mahmoudparsian/data-algorithms-book/blob/master/

src/main/java/org/dataalgorithms/util/SparkUtil.java

759

Listing B.4: JavaRDD Creation

1 import java.util.List;
2 import com.google.common.collect.Lists;
3 import org.apache.spark.SparkConf;
4 import org.apache.spark.api.java.JavaSparkContext;
5 ...
6 // create JavaSparkContext
7 SparkConf sparkConf = new SparkConf().setAppName("myapp");
8 JavaSparkContext ctx = new JavaSparkContext(sparkConf);
9
10 // create your desired collection object
11 final List<String> list1 = Lists.newArrayList(
12

13

14

15

16

17

"url1,2",
"url1,3",
"url2,7",
"url2,6",
"url3,4",
"url3,5",
"url3,6"

18
19 );
20
21 // create an RDD from Java collection object
22 JavaRDD<String> rdd1 = ctx.parallelize(list1);

Now rdd1 is a JavaRDD<String> with 7 elements (each element has
the format of <url><,><count>) in it. Once RDD is created, you may
start applying functions and transformations (such as map(), collect(),
reduceByKey(), and many others).

B.6 Collect Elements of an RDD

The generated rdd1 can be collected as List<String>:

1 // create an RDD from Java collection object
2 JavaRDD<String> rdd1 = ctx.parallelize(list1);
3
4 // collect RDD's elements:
5 // java.util.List<T> collect()
6 // Return an array that contains all of the elements in this RDD.
7 java.util.List<String> collected = rdd1.collect();

760

B.7 Transform RDD into New RDD

Let’s take rdd1 and transform it into (K,V) pairs (as JavaPairRDD object):
for transformation, we use JavaRDD.mapToPair() method.

Listing B.5: JavaPairRDD Creation

1 // create an RDD from Java collection object
2 JavaRDD<String> rdd1 = ctx.parallelize(list1);
3
4 // create (K,V) pairs where K is a URL and V is a count
5 JavaPairRDD<String, Integer> kv1 = rdd1.mapToPair(
6

new PairFunction<String,

// T as input

7

8

9

10

11

12

13

14

15

String, // K as output
Integer // V as output

>() {

@Override
public Tuple2<String, Integer> call(String element) {

String[] tokens = element.split(",");
// tokens[0] = URL
// tokens[1] = count
return new Tuple2<String, Integer>(tokens[0], new Integer(tokens[1]));

}

16
17 });

B.8 Create RDDs by Reading Files

For most of the MapReduce applications, you will read data from HDFS and
then create RDDs, and possibly save the results as in HDFS. Let’s assume
that we have two HDFS ﬁles:

Listing B.6: Listing HDFS Files

/myinput/logs/

1 $ hadoop fs -ls
2 ... /myinput/logs/file1.txt
3 ... /myinput/logs/file2.txt
4
5 $ hadoop fs -cat
6 url5,2
7 url5,3
8 url6,7
9 url6,8
10 $ hadoop fs -cat
11 url7,1
12 url7,2
13 url8,5
14 url8,6

/myinput/logs/file1.txt

/myinput/logs/file2.txt

761

15 url9,7
16 url9,8
17 url5,9
18 $

Next, we create an RDD from these two ﬁles

1 // create JavaSparkContext
2 SparkConf sparkConf = new SparkConf().setAppName("myapp");
3 JavaSparkContext ctx = new JavaSparkContext(sparkConf);
4
5 // read input file from HDFS
6 // input record format: <string-key><,><integer-value>
7 String hdfsPath = "/myinput/logs";
8 // public JavaRDD<String> textFile(String path)
9 // Read a text file from HDFS, a local file system
10 // (available on all nodes), or any Hadoop-supported
11 // file system URI, and return it as an RDD of Strings.
12 JavaRDD<String> rdd2 = ctx.textFile(hdfsPath);

At this point, rdd2 has 11 String elements (4 from file1.txt and 7
from file2.txt). Now, you may use the same techniqure (presented in the
preceding sections) to create JavaPairRDD<String,Integer> where key is a
URL and value is the URL’s associated count.

B.9 Grouping By Key

Here we will group elements by key for rdd2:

Listing B.7: JavaPairRDD Creation

1 // rdd2 is already created (see previous section)
2 // create (K,V) pairs where K is a URL and V is a count
3 JavaPairRDD<String, Integer> kv2 = rdd2.mapToPair(
4

new PairFunction<String,

// T as input

5

6

7

8

9

10

11

12

13

String, // K as output
Integer // V as output

>() {

@Override
public Tuple2<String, Integer> call(String element) {

String[] tokens = element.split(",");
// tokens[0] = URL
// tokens[1] = count
return new Tuple2<String, Integer>(tokens[0], new Integer(tokens[1]));

762

}

14
15 });
16
17 // next group RDD’s elements by key
18 JavaPairRDD<String, Iterable<Integer>> gouped2 = kv2.groupByKey();

The resulting RDD (group2) will have the following content:

(K,V) Generated by groupByKey() Method
Key
url5
url6
url7
url8
url9

Value
[2, 3, 9]
[7, 8]
[1, 2]
[5, 6]
[7, 8]

B.10 Map Values

If you have a JavaPairRDD, which you want to alter values and create new set
of values (without changing the keys), then you may use JavaPairRDD.mapValues()
method. For example, we will take grouped2 created in the preceding section
and retuen the maximum of URL counts.

Listing B.8: JavaPairRDD.mapValues()

1 // public <U> JavaPairRDD<K,U> mapValues(Function<V,U> f)
2 // Pass each value in the key-value pair RDD through a map
3 // function without changing the keys; this also retains
4 // the original RDD’s partitioning.
5 JavaPairRDD<String,Integer> mapped2 = gouped2.mapValues(
6

new Function<Iterable<Integer>,

// input
// output

Integer

>() {

7

8

9

10

11

12

13

14

15

16

17

18

19

public Integer call(Iterable<Integer> list) {

Integer max = null;
for (Integer element : list) {

if (max == null) {

max = element;

}
else {

if (element > max) {
max = element;

}

}

763

}
return max;

20

21

}

22
23 });

The resulting RDD (mapped2) will have the following content:

(K,V) Generated by mapValues() Method
Key
url5
url6
url7
url8
url9

Value
9
8
2
6
8

B.11 Reducing By Key

Here we will reduce elements by key for rdd2: the goal is to add the counts for
the same URL (create a ﬁnal count per URL). We use JavaPairRDD.reduceByKey()
method.

Listing B.9: JavaPairRDD.mapToPair()

1 // rdd2 is already created (see previous section)
2 // create (K,V) pairs where K is a URL and V is a count
3 JavaPairRDD<String, Integer> kv2 = rdd2.mapToPair(
4

new PairFunction<String,

// T as input

5

6

7

8

9

10

11

12

13

String, // K as output
Integer // V as output

>() {

@Override
public Tuple2<String, Integer> call(String element) {

String[] tokens = element.split(",");
// tokens[0] = URL
// tokens[1] = count
return new Tuple2<String, Integer>(tokens[0], new Integer(tokens[1]));

}

14
15 });
16
17 // next reduce JavaPairRDD’s elements by key
18 // public JavaPairRDD<K,V> reduceByKey(Function2<V,V,V> func)
19 // Merge the values for each key using an associative reduce
20 // function. This will also perform the merging locally on each
21 // mapper before sending results to a reducer, similarly to a
22 // "combiner" in MapReduce. Output will be hash-partitioned with

764

23 // the existing partitioner/ parallelism level.
24 JavaPairRDD<String, Integer> counts = kv2.reduceByKey(
25

new Function2<

26

27

28

29

30

31

32

Integer, // input T1
Integer, // input T2
// output T
Integer

>() {

@Override
public Integer call(Integer count1, Integer count2) {

return count1 + count2;

}

33
34 });

The resulting RDD (counts) will have the following content:

(K,V) Generated by reduceByKey() Method
Key
url5
url6
url7
url8
url9

Value
14
15
3
11
15

B.12 Filtering an RDD

Spark provides a very simple and powerful API for ﬁltering RDDs. To ﬁlter
RDD elements, we just need to implement a ﬁlter() function: return true
for the elements you want to keep and return false for the elements you
want to toss out. Consider the following RDD labeled as logRDD. We write a
ﬁlter() function, which keeps the elements, which has the "normal" keyword
and tosses out the remaining elements.

Listing B.10: Sample JavaRDD

1 import java.util.List;
2 import com.google.common.collect.Lists;
3 import org.apache.spark.SparkConf;
4 import org.apache.spark.api.java.JavaSparkContext;
5 ...
6 // create JavaSparkContext
7 SparkConf sparkConf = new SparkConf().setAppName("logs");
8 JavaSparkContext ctx = new JavaSparkContext(sparkConf);
9

765

10 // create your desired collection object
11 final List<String> logRecords = Lists.newArrayList(
12

13

14

15

"record 1: normal",
"record 2: error",
"record 3: normal",
"record 4: error",
"record 5: normal"

16
17 );
18
19 // create an RDD from Java collection object
20 JavaRDD<String> logRDD = ctx.parallelize(logRecords);
21
22 // To filter elements, we need to implement a filter function:
23 // JavaRDD<T> filter(Function<T,Boolean> f)
24 // Return a new RDD containing only the elements that satisfy a predicate.
25 JavaRDD<String> filteredRDD = logRDD.filter(new Function<String,Boolean>() {
26

public Boolean call(String record) {

27

28

29

30

31

32

if (record.contains("normal"))

{

return true; // do return these records

}
else {

return false; // do not retrun these records

}

}

33
34 });
35
36 // At this point, filteredRDD will have the following 3 elements:
37 //
38 //
39 //

"record 1: normal"
"record 3: normal"
"record 5: normal"

B.13 Saving RDD as HDFS Text File

You may save your RDDs as Hadoop ﬁles (text or sequence ﬁle). Let counts
be an RDD create in the preceding section, then you may save it in HDFS
as a text ﬁle(s):

1 // save RDD as an HDFS text file
2 // void saveAsTextFile(String path)
3 // Save this RDD as a text file, using string representations of elements.
4 // Make sure that your output path -- "/my/output" -- does not exist
5 counts.saveAsTextFile("/my/output");

After it is saved, you may view the saved data as:

$ hadoop fs -cat /my/output/part*

766

B.14 Saving RDD as HDFS Sequence File

You may save your RDDs as Hadoop ﬁles (text or sequence ﬁle). Let
counts be an RDD created in the preceding section, then you may save
it in HDFS as a sequence ﬁle (sequence ﬁles are binary ﬁles in the form
of (K, V) pairs). To save an RDD as a sequence ﬁle, you have to con-
vert its elements into Hadoop’s Writable objects. Since counts is an RDD
of type JavaPairRDD<String, Integer>, we can not directly write it to
HDFS as a sequence ﬁle; ﬁrst we need create a new RDD which has a type
of JavaPairRDD<Text, IntWritable>, where we convert String into Text
and Integer into IntWritable. This is how we write counts into HDFS as
a sequence ﬁle:

Listing B.11: Creating a SequenceFile

1 import scala.Tuple2;
2 import org.apache.hadoop.io.Text;
3 import org.apache.hadoop.io.IntWritable;
4 import org.apache.hadoop.mapred.SequenceFileOutputFormat;
5 ...
6
7 // First create a Writable RDD:
8 JavaPairRDD<Text, IntWritable> countsWritable =
9

counts.mapToPair(new PairFunction<

10

11

12

13

14

15

16

17

18

19

Tuple2<String,Integer>, // T
// K
Text,
// V
IntWritable

>() {
@Override
public Tuple2<Text, IntWritable> call(Tuple2<String,Integer> t) {

return new Tuple2<Text, IntWritable>(

new Text(t._1),
new IntWritable(t._2)

);

}

20
21 });
22
23 // Next, write it as a sequence file
24 // make sure that your output path -- "/my/output2" -- does not exist
25 countsWritable.saveAsHadoopFile(
"/my/output2",
26
Text.class,
IntWritable.class,
SequenceFileOutputFormat.class // output format class

// name of path
// key class
// value class

28

27

29
30 );

After it is saved, you may view the saved data as

$ hadoop fs -text /my/output2/part*

767

B.15 Reading RDD from HDFS Sequence File

You may create a new RDDs from reading Hadoop’s sequence ﬁle. The
sequence ﬁle we created in the preceding section will be read and a new
RDD will be created:

Listing B.12: Reading a SequenceFile

JavaPairRDD<K,V> hadoopFile(String path,

1 import scala.Tuple2;
2 import org.apache.hadoop.io.Text;
3 import org.apache.hadoop.io.IntWritable;
4 import org.apache.hadoop.mapred.SequenceFileInputFormat;
5 ...
6
7 //
8 //
9 //
10 //
11 // Get an RDD for a Hadoop file with an arbitrary InputFormat
12 // ’’’Note:’’’ Because Hadoop’s RecordReader class re-uses the
13 // same Writable object for each record, directly caching the
14 // returned RDD will create many references to the same object.
15 // If you plan to directly cache Hadoop writable objects, you
16 // should first copy them using a map function.
17 JavaPairRDD<Text, IntWritable> seqRDD = ctx.hadoopFile(
18

Class<F> inputFormatClass,
Class<K> keyClass,
Class<V> valueClass)

"/my/output2",
SequenceFileInputFormat.class,
Text.class,
IntWritable.class

// HDFS path
// input format class
// key class
// value class

19

20

21
22 );

B.16 Counting RDD

The count() method returns the number of items stored in an RDD.

Listing B.13: Counting RDDs

1 // count JavaPairRDD
2 JavaPairRDD<Text, IntWritable> pairRDD = ...;
3 int count1 = pairRDD.count();
4
5 // count JavaRDD
6 JavaRDD<String> strRDD = ...;
7 int count2 = strRDD.count();

768

B.17 Spark RDD Examples in Scala

If you are interested in usage of RDD in Scala, then you may refer to http://
homepage.cs.latrobe.edu.au/zhe/ZhenHeSparkRDDAPIExamples.html.

769

glossary

770

Bibliography

[1] Satnam Alag. Collective Intelligence in Action. Manning Publications

Co., 2009.

[2] Carolyn J. Anderson. Exact tests for 2way tables. 2013.

[3] Sarah Boslaugh. Statistics in a Nutshell, Second Edition. O’Reilly Me-

dia, Inc., 2013.

[4] A. Brandt. Algebraic analysis of mapreduce samples. 2010.

[5] Eirinaios Michelakis Ioannis Koutis Christos Faloutsos Charalampos
E. Tsourakakis, Petros Drineas. Spectral counting of triangles in power-
law networks via element-wise sparsication.

[6] Edwin

Chen.

recommendations-and-more-via-mapreduce-and-scalding/.
Chen, 2012.

http://blog.echen.me/2012/02/09/movie-
Edwin

[7] Anderson

de Rezende Rocha.

classiﬁer.
http://www.ic.unicamp.br/ rocha/teaching/2011s2/mc906/aulas/naive-
bayes-classiﬁer.pdf.

Naive

bayes

[8] Jeﬀrey Dean and Sanjay Ghemawat. MapReduce: Simplied Data Pro-
cessing on Large Clusters. Proc of the 6th Symposium on Operating
Systems Design and Implementation, Reading, MA, 2004.

[9] Alexander Felfernig Dietmar Jannach, Markus Zanker and Gerhard
Friedrich. Recommender Systems, An Introduction. Cambridge Uni-
versity Press, 2011.

771

[10] G. David Garson. Cox Regression. Asheboro, NC: Statistical Associates

Publishers, 2012.

[11] Peter Harrington. Machine Learning in Action. Manning Publications

Co., 2012.

[12] Jimmy Lin. Mapreduce algorithm design. 2013.

[13] Jimmy Lin. Monoidify! monoids as a design principle for eﬃcient mapre-

duce algorithms. 29 April 2013.

[14] Jimmy Lin and Chris Dyer. Data-Intensive Text Processing with MapRe-

duce. University of Maryland, College Park, MD, 2010.

[15] Jimmy Lin and Chris Dyer. Data-Intensive Text Processing with MapRe-

duce. Morgan & Claypool Publishers, January 27, 2013.

[16] Donald Miner and Adam Shook. MapReduce Design Patterns. O’Reilly

Media, Inc., 2013.

[17] Tom M. Mitchell. Machine Learning. McGraw-Hill, 1997.

[18] Netﬂix. http://www.netﬂixprize.com/. Netﬂix, 2009.

[19] Bo Pang and Lillian Lee. A sentimental education: Sentiment analysis

using subjectivity summarization based on minimum cuts.

[20] John Perry.

Foundations of Nonlinear Algebra.

John Perry:

http://www.math.usm.edu/perry/mat423fa13/main.pdf, 2012.

[21] David Saile. Mapreduce with deltas. August 2011.

[22] Dedy Hartama Ramliana S Elvi Wani Sajadin Sembiring, M. Zarlis.
Prediction of student academic performance by an application of data
mining techniques. 2011 International Conference on Management and
Artiﬁcial Intelligence IPEDR vol.6, 2011.

[23] Manish Sarkar and Tze-Yun Leong. Application of k-nearest neighbors
algorithm on breast cancer diagnosis problem. Medical Computing Lab-
oratory, Department of Computer Science, School of Computing, The
National University of Singapore, Lower Kent Ridge Road, Singapore:
119260, 2000.

772

[24] Thomas Schank and Dorothea Wagner. Finding, counting and listing all
triangles in large graphs, an experimental study. http://i11www.iti.uni-
karlsruhe.de/extra/publications/sw-fclt-05 t.pdf.

[25] Thomas Schank and Dorothea Wagner. Approximating clustering co-

ecient and transitivity. 2005.

[26] Toby Segaran. Programming Collective Intelligence: Building Smart

Web 2.0 Applications. O’Reilly Media, Inc., 2007.

[27] Michael

G.

Walker.

Survival

analysis.

http://walkerbioscience.com/pdfs/Survival%20analysis.pdf.

[28] Tom White. Hadoop: The Deﬁnitive Guide, Third Edition. O’Reilly

Media, Inc., 2012.

[29] wikipedia.

http://en.wikipedia.org/wiki/Correlation and dependence.

wikipedia.org, 2012.

[30] Jongwook Woo and Yuhang Xu. Market Basket Analysis Algorithm
with Map/Reduce of Cloud Computing. Computer Information Systems
Department California State University, Los Angeles, CA.

[31] Therese Sorlie Bjorn Naume Anita Langerod Arnoldo Frigessi
Vessela N. Kristensen Anne-Lise Borresen-Dale Ole Chris-
Combining
tian Lingjaerde Xi Zhao, Einar Andreas Rodland.
survival.
improves prediction of breast
gene
http://www.plosone.org/article/info:doi/10.1371/journal.pone.0017845.

signatures

cancer

[32] Changyu Yang. Triangle counting in large networks, master’s thesis.

2012.

[33] Matei Zaharia. An architecture for fast and general data processing on

large clusters. 2014.

773

