Articles · 2014

Twitter analysis for Strata+Hadoop World (BCN, 2014) with Apache Spark and D3

Using the official hashtag #StrataHadoop, I've made a basic analysis of Twitter activity during the Strata+Hadoop World conference that was held on 19-21 November 2014 in Barcelona, Spain.

Archived article, first published in 2014. Kept as it was written; some tools and versions have moved on since.

Dataset of tweets

We use python library TwitterSearch to obtain the dataset with all tweets that contain hashtag #StrataHadoop (case insensitive) and were created in the interval from 15.10.2014 to 24.11.2014

import json

from TwitterSearch import TwitterSearch, TwitterSearchOrder

client = TwitterSearch(
    consumer_key=TWITTER_CONSUMER_KEY,
    consumer_secret=TWITTER_CONSUMER_SECRET,
    access_token=TWITTER_ACCESS_TOKEN,
    access_token_secret=TWITTER_ACCESS_TOKEN_SECRET,
)

search = TwitterSearchOrder()
search.set_keywords(['#StrataHadoop since:2014-11-15 until:2014-11-24'])
search.set_include_entities(True)

with open("stratahadoop.json", "w+") as f:
    for tweet in client.search_tweets_iterable(search):
        f.write(json.dumps(tweet))
        f.write("\n")

As the result, we have stratahadoop.json (the dataset is no longer published).

Analysis using Apache Spark and D3.js

Apache Spark™ is a fast and general engine for large-scale data processing. It's up to 100x faster than Hadoop MapReduce in memory, or 10x faster on disk. Apache Spark supports Java, Scala and Python out of the box. We will use Spark Python API (PySpark) for data mining from the dataset of tweets we have collected before.

D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation.

Basic dataset characteristics

Let's load the dataset into SparkContext and check number of tweets:

import json

from pyspark import SparkContext

sc = SparkContext()

rdd = sc.textFile("stratahadoop.json").map(lambda tweet: json.loads(tweet))
rdd.count()
> 8485

So, we have 8485 tweets in our dataset. It's interesting to separate such tweets that were created during the conference dates (created_during_event), because they are expected to be different and more related to the conference talks and discussions.

import pytz
from datetime import datetime, timedelta

cet = pytz.timezone("CET")
utc = pytz.timezone("UTC")

EVENT_START = datetime(2014, 11, 19, 9, 0, 0, tzinfo=cet).astimezone(utc)
EVENT_END = datetime(2014, 11, 21, 19, 0, 0, tzinfo=cet).astimezone(utc)

def created_during_event(tweet):
    """
    Return True if tweet has been created exactly during the current event.

    """
    created_at = datetime.strptime(tweet["created_at"], "%a %b %d %H:%M:%S +0000 %Y")
    return EVENT_START <= utc.localize(created_at) <= EVENT_END

Let's calculate number of such tweets:

rdd.filter(created_during_event).count()
> 5686

As the result, there are 5686 tweets (67%) that were created during the conference dates. We will investigate the distribution of tweets by hour in the another section below.

To better imaging the percentage, we can do simple visualization with D3:

// the PieChart code has been adapted from
// http://bl.ocks.org/dbuezas/9306799

function buildPieChart(data, containerId, containerWidth, containerHeight) {
    var container = d3.select(containerId);
    if(container[0][0] === null) {
        return;
    }

    var margin = {top: 20, right: 20, bottom: 30, left: 50},
        width = containerWidth - margin.left - margin.right,
        height = containerHeight - margin.top - margin.bottom,
        radius = Math.min(width, height) / 2;

    var fill = d3.scale.category10();

    data.forEach(function(d) {
        d.value = +d.value;
    });

    var svg = container
        .append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
        .append("g")
            .attr(
                "transform",
                "translate(" + width / 2 + "," + height / 2 + ")"
            );

    svg.append("g")
        .attr("class", "slices");
    svg.append("g")
        .attr("class", "labels");
    svg.append("g")
        .attr("class", "lines");

    var pie = d3.layout.pie()
        .sort(null)
        .value(function(d) {
            return d.value;
        });

    var arc = d3.svg.arc()
        .outerRadius(radius * 0.8)
        .innerRadius(radius * 0.4);

    var outerArc = d3.svg.arc()
        .innerRadius(radius * 0.9)
        .outerRadius(radius * 0.9);

    var title = function(d) {
        return d.data.title;
    };

    //  PIE SLICES
    var slice = svg.select(".slices").selectAll("path.slice")
        .data(pie(data), title);

    slice.enter()
        .insert("path")
            .style("fill", function(d, i) { return fill(i); })
            .attr("class", "slice");

    slice.transition()
        .attrTween("d", function(d) {
            this._current = this._current || d;
            var interpolate = d3.interpolate(this._current, d);
            this._current = interpolate(0);
            return function(t) {
                return arc(interpolate(t));
            };
        });

    slice.exit().remove();

    //  TEXT LABELS
    var text = svg.select(".labels").selectAll("text")
        .data(pie(data));

    text.enter()
        .append("text")
            .attr("dy", ".35em")
            .text(function(d) {
                return d.data.title;
            });

    function midAngle(d) {
        return d.startAngle + (d.endAngle - d.startAngle) / 2;
    }

    text.transition()
        .attrTween("transform", function(d) {
            this._current = this._current || d;
            var interpolate = d3.interpolate(this._current, d);
            this._current = interpolate(0);
            return function(t) {
                var d2 = interpolate(t);
                var pos = outerArc.centroid(d2);
                pos[0] = radius * (midAngle(d2) < Math.PI ? 1 : -1);
                return "translate("+ pos +")";
            };
        })
        .styleTween("text-anchor", function(d){
            this._current = this._current || d;
            var interpolate = d3.interpolate(this._current, d);
            this._current = interpolate(0);
            return function(t) {
                var d2 = interpolate(t);
                return midAngle(d2) < Math.PI ? "start":"end";
            };
        });

    text.exit().remove();

    //  SLICE TO TEXT POLYLINES
    var polyline = svg.select(".lines").selectAll("polyline")
        .data(pie(data));

    polyline.enter().append("polyline");

    polyline.transition()
        .attrTween("points", function(d){
            this._current = this._current || d;
            var interpolate = d3.interpolate(this._current, d);
            this._current = interpolate(0);
            return function(t) {
                var d2 = interpolate(t);
                var pos = outerArc.centroid(d2);
                pos[0] = radius * 0.95 * (midAngle(d2) < Math.PI ? 1 : -1);
                return [arc.centroid(d2), outerArc.centroid(d2), pos];
            };
        });

    polyline.exit().remove();
}

We can go even more deep and try to filter tweets, that were created inside or near to the conference's venue. Unfortunately, Twitter Search API doesn't support query and geocode search at the same time, so we can do simple filtering with Spark (close_to_venue) using approximate geobox (http://boundingbox.klokantech.com/)

GEOBOX = (41.4083817701,2.2177593708, 41.4106115707, 2.220836401)

def has_geo(tweet):
    """
    Return True if tweet has geo information.

    """
    if not tweet["coordinates"]:
        return False
    return True

def close_to_venue(tweet):
    """
    Return True if tweet has been created inside the geobox around venue.

    """
    lon, lat = tweet["coordinates"]["coordinates"]
    top_lat, top_lon, bottom_lat, bottom_lon = GEOBOX
    if lat < top_lat or lat > bottom_lat:
        return False
    if lon < top_lon or lon > bottom_lon:
        return False
    return True

rdd.filter(has_geo).count()
> 277
rdd.filter(created_during_event).filter(has_geo).count()
> 271
rdd.filter(created_during_event).filter(has_geo).filter(close_to_venue).count()
> 173

Well, not so many people embed geo information into their tweets - about 3.26% for the whole period and, slightly better, about 4.76% during the conference. But, as you can see, from such people with enabled geo data 173 (63.8%) were actually participants of the event.

From now we will work mostly with the tweets, that were created during the event, so it make sense to cache such RDD at this point. Of course, it almost have no sense to do that for such small dataset, but it helps a lot if you deal with huge datasets.

rdd_during_event = rdd.filter(created_during_event).cache()

Hashtags and authors

The analogue of the well-known "Hello world" example, but for the bigdata frameworks, is the task to calculate number of words in text. We will adapt that example and calculate most valuable hashtags and tweets authors for our dataset.

Let's start with hashtags and calculate TOP 25 of popular hashtags in tweets during the event:

from operator import add

hashtags_during_event = rdd_during_event\
    .flatMap(lambda tweet: [h['text'].lower() for h in tweet['entities']['hashtags']])\
    .map(lambda hashtag: (hashtag, 1))\
    .reduceByKey(add)\
    .map(lambda (hashtag, cnt): (cnt, hashtag))\
    .sortByKey()
hashtags_during_event.top(25)
> [(5689, u'stratahadoop'), (500, u'bigdata'), (187, u'spark'), (170, u'hadoop'), (112, u'elasticsearch'), (103, u'datascience'), (82, u'iot'), (81, u'strataconf'), (76, u'ignite'), (71, u'ioth'), (70, u'eudatalandscape'), (66, u'barcelona'), (57, u'sparkcamp'), (47, u'data'), (36, u'analytics'), (30, u'nosql'), (25, u'velocityconf'), (23, u'stratabarcelona'), (23, u'dataviz'), (22, u'privacy'), (22, u'opendata'), (21, u'livestream'), (20, u'ibm'), (20, u'changetheratio'), (20, u'bluemix')]

As expected, the most popular hashtag is #stratahadoop that was used to build our dataset ;) We also can see, that it appears 5689 times, so somebody was so exiting that used the hashcode a few times in the same tweet (for example, with different letters case). Other popular hastags are bigdata, spark and hadoop which are clearly highlight the main topic of the conference.

With D3 and d3-cloud it's fairly easy to visualise such attributes with respect to the dependent attribute count:

// the wordCloud code has been adapted from
// http://ywng-d3apps.rhcloud.com/MktInsight/

// NOTE: You need to include d3.layout.cloud.js
// https://raw.githubusercontent.com/jasondavies/d3-cloud/master/d3.layout.cloud.js

function buildWordCloud(data, fontScaleFunction, containerId, containerWidth, containerHeight) {
    var container = d3.select(containerId);
    if(container[0][0] === null) {
        return;
    }

    var width = containerWidth,
        height = containerHeight;

    data.forEach(function(d) {
        d.count = +d.count;
    });

    var fill = d3.scale.category20();
    var maxCount = data[0].count;
    var fontScale = d3.scale[fontScaleFunction]().domain([1, maxCount]).range([10, 50]);
    var rotationScale = d3.scale.sqrt().domain([0, 9]).range([-45, 45]);

    var svg = container
        .append("svg")
            .attr("width", width)
            .attr("height", height)
        .append("g")
            .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

    d3.layout.cloud().size([width, height])
        .words(data)
        .padding(5)
        .rotate(function() { return rotationScale(~~(Math.random() * 10)); })
        .font("Impact")
        .fontSize(function(d) { return fontScale(d.count); })
        .on("end", function(d, bounds) {
            svg.selectAll("text")
                .data(data).enter()
                .append("text")
                    .style("font-size", function(d) { return fontScale(d.count) * 1.1 + "px"; })
                    .style("font-family", "Impact")
                    .style("fill", function(d, i) { return fill(i); })
                    .attr("text-anchor", "middle")
                    .attr("transform", function(d) {
                        return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
                    })
                    .text(function(d) { return d.text; });
        })
        .start();
}

Now, let's do the same analysis for authors:

authors_during_event = rdd_during_event\
    .map(lambda tweet: (tweet['user']['screen_name'], 1))\
    .reduceByKey(add)\
    .map(lambda (name, cnt): (cnt, name))\
    .sortByKey()
authors_during_event.top(25)
> [(609, u'strataconf'), (87, u'jbaquerot'), (80, u'stevenbeeckman'), (77, u'trieloff'), (65, u'eudatalandscape'), (62, u'duncan3ross'), (59, u'kate_ting'), (57, u'cgogus'), (56, u'andreademarco'), (52, u'juantomas'), (51, u'kestelyn'), (51, u'ClouderaEvents'), (50, u'jbenno'), (48, u'peeterskris'), (44, u'indizen_insight'), (43, u'pacoid'), (42, u'DaanDebie'), (41, u'ch_doig'), (40, u'NoSQLDigest'), (39, u'DatenAssistance'), (38, u'ManfredBo'), (36, u'mounialalmas'), (35, u'adrianafreitas'), (34, u'AureliePols'), (33, u'mmaibaum')]

The official account on the conference @strataconf tweeted a lot, but probably it was mostly retweets? Let's check that too:

def is_not_retweet(tweet):
    if tweet['text'].startswith('RT '):
        return False
    return not tweet.get('retweeted_status')

real_authors_during_event = rdd_during_event.filter(is_not_retweet)\
    .map(lambda tweet: (tweet['user']['screen_name'], 1))\
    .reduceByKey(add)\
    .map(lambda (name, cnt): (cnt, name))\
    .sortByKey()
real_authors_during_event.top(25)
> [(153, u'strataconf'), (57, u'trieloff'), (48, u'kestelyn'), (48, u'eudatalandscape'), (47, u'kate_ting'), (47, u'jbenno'), (47, u'duncan3ross'), (44, u'indizen_insight'), (42, u'jbaquerot'), (38, u'stevenbeeckman'), (38, u'peeterskris'), (31, u'DaanDebie'), (25, u'ClouderaEvents'), (21, u'mmaibaum'), (21, u'miguelmalvarez'), (21, u'adrianafreitas'), (21, u'BMCControlM'), (19, u'BartAelterman'), (17, u'zahedab'), (17, u'padolphs'), (17, u'CapdevilaPujol'), (16, u'natalinobusa'), (16, u'kimknilsson'), (16, u'boudicca'), (16, u'PeterSpeyer')]

Actually, we were right. Official Twitter account of the Strata+Hadoop @strataconf was retweeted a lot, but it also created the most amount of tweets during the event according to our dataset

Tweets distribution by hour

Finally, let's look how tweets were distributed in time during the conference and calculate the histogram. As a bucket we will use the 1 hour interval:

def get_bucket(date):
    """
    Generate bucket name based on the date.
    """
    created_at = datetime.strptime(date, "%a %b %d %H:%M:%S +0000 %Y")
    return utc.localize(created_at).astimezone(cet).strftime("%Y%m%d%H00")

rdd.filter(created_during_event)\
    .map(lambda tweet: (get_bucket(tweet["created_at"]), 1))\
    .reduceByKey(add)\
    .sortByKey(ascending=True)\
    .collect()
> [('2014111909', 89), ('2014111910', 73), ('2014111911', 82), ('2014111912', 106), ('2014111913', 39), ('2014111914', 78), ('2014111915', 79), ('2014111916', 80), ('2014111917', 92), ('2014111918', 136), ('2014111919', 28), ('2014111920', 21), ('2014111921', 29), ('2014111922', 16), ('2014111923', 21), ('2014112000', 8), ('2014112001', 14), ('2014112002', 5), ('2014112003', 1), ('2014112004', 4), ('2014112006', 8), ('2014112007', 11), ('2014112008', 52), ('2014112009', 274), ('2014112010', 594), ('2014112011', 309), ('2014112012', 259), ('2014112013', 136), ('2014112014', 283), ('2014112015', 140), ('2014112016', 195), ('2014112017', 215), ('2014112018', 114), ('2014112019', 67), ('2014112020', 45), ('2014112021', 39), ('2014112022', 49), ('2014112023', 29), ('2014112100', 34), ('2014112101', 12), ('2014112102', 13), ('2014112103', 8), ('2014112104', 4), ('2014112105', 19), ('2014112106', 11), ('2014112107', 9), ('2014112108', 54), ('2014112109', 204), ('2014112110', 432), ('2014112111', 252), ('2014112112', 91), ('2014112113', 96), ('2014112114', 142), ('2014112115', 112), ('2014112116', 147), ('2014112117', 150), ('2014112118', 76)]

With D3 it's easy now to visualize such histogram with bar plot:

// the wordCloud code has been adapted from
// http://bost.ocks.org/mike/bar/3/

function buildBarPlot(data, containerId, containerWidth, containerHeight) {
    var container = d3.select(containerId);
    if(container[0][0] === null) {
        return;
    }

    var margin = {top: 20, right: 20, bottom: 80, left: 60},
        width = containerWidth - margin.left - margin.right,
        height = containerHeight - margin.top - margin.bottom,
        barWidth = width / data.length;

    var parseDate = d3.time.format("%Y%m%d%H").parse;

    data.forEach(function(d) {
        d.count = +d.count;
        d.key = parseDate(d.key);
    });

    var x = d3.time.scale()
        .domain([d3.min(data, function(d) { return d.key; }), d3.max(data, function(d) { return d.key; })])
        .range([0, width]);

    var y = d3.scale.linear()
        .domain([0, d3.max(data, function(d) { return d.count; })])
        .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
        .ticks(d3.time.hour, 1)
        .tickFormat(d3.time.format('%d.%m %H:00'));

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left")
        .ticks(10);

    var svg = container
        .append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
        .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis).selectAll("text")
            .style("text-anchor", "end")
            .attr("font-size", "0.6em")
            .attr("dx", "-0.4em")
            .attr("dy", "0.2em")
            .attr("transform", function(d) {
                return "rotate(-65)";
            });

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)
        .append("text")
            .attr("transform", "rotate(-90)")
            .attr("y", 6)
            .attr("dy", "-5em")
            .attr("font-size", "0.6em")
            .style("text-anchor", "end")
            .text("Number of Tweets (incl. RT)");

    svg.selectAll(".bar")
        .data(data).enter()
        .append("g")
            .attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; })
        .append("rect")
            .attr("y", function(d) { return y(d.count); })
            .attr("height", function(d) { return height - y(d.count); })
            .attr("width", barWidth - 1)
            .style("fill", "#6baed6");
}

From the diagrams we could clearly see 3 clusters that correspond to days of the conference. First day on Strata+Hadoop World Barcelona was a training day, this is the explanation why the activity in Twitter more homogeneous and not so high. Other days have strong outliers around 9am-10am which correspond to the keynote presentations according to the conference schedule made by the well-known speakers.

Author profiles

At the end, let's display profile images of authors who posted or retweeted about the conference with the hashtag #StrataHadoop. Since the amount of such users is big, we will consider only authors who tweeted/retweeted at least 10 times and then randomly display 10 of them:

rdd.map(lambda tweet: (tweet['user']['screen_name'], tweet['user']['profile_image_url']))\
    .map(lambda user: (user, 1))\
    .reduceByKey(add)\
    .filter(lambda (user, count): count > 10)\
    .map(lambda (user, count): user)\
    .takeSample(False, 10)
> [(u'natalinobusa', u'http://pbs.twimg.com/profile_images/536575658684846080/YbbgsApP_normal.jpeg'), (u'DaniScherer', u'http://pbs.twimg.com/profile_images/520402903295467521/8yCjgSU7_normal.jpeg'), (u'miguelmalvarez', u'http://pbs.twimg.com/profile_images/434666133526814720/tMXEUK75_normal.jpeg'), (u'DaanDebie', u'http://pbs.twimg.com/profile_images/1207807311/5311704645_2025136ce3_b_normal.jpg'), (u'JordiTorresBCN', u'http://pbs.twimg.com/profile_images/513397716307550208/FOLQqNAT_normal.jpeg'), (u'eudatalandscape', u'http://pbs.twimg.com/profile_images/470923513356771328/BoPMjCFL_normal.jpeg'), (u'awadallah', u'http://pbs.twimg.com/profile_images/1536319816/amr_2011_twitter_normal.jpg'), (u'thethis', u'http://pbs.twimg.com/profile_images/1121571086/DSC_0468_normal.jpg'), (u'Ellen_Friedman', u'http://pbs.twimg.com/profile_images/432943566906597376/0DbhL3TA_normal.jpeg'), (u'mmfcordeiro', u'http://pbs.twimg.com/profile_images/508683750/images_normal.jpg')]

Conclusion

Apache Spark and D3 give us very comfortable way for first look on the data. They also have very nice features we don't show in this article, that makes them a really good solution for data analysis. Of course, there is no universal solution and every researcher should consider other tools and technologies. For instance, because our data is could be easy represented as time-series and not so big, we can also use Elasticsearch and Kibana that provide easy way to query and visualize such data (I will show how to use them in the next article).

IPython Notebook StrataHadoop.ipynb with PySpark examples could be downloaded from our GitHub repository.

References

  1. TwitterSearch is a library to easily iterate tweets found by the Twitter API
  2. Apache Spark is a fast and general engine for large-scale data processing.
  3. D3.js is a JavaScript library for manipulating documents based on data
  4. d3-cloud is a word cloud layout written in JavaScript
  5. Elasticsearch is a powerful open source search and analytics engine that makes data easy to explore
  6. Kibana is an interactive tool to visualize logs and time-stamped data