Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
probberechts committed Jun 16, 2020
0 parents commit 9dabc11
Show file tree
Hide file tree
Showing 36 changed files with 14,525 additions and 0 deletions.
15 changes: 15 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module",
"ecmaVersion": 8
},
"env": {
"es6": true,
"node": true,
"browser": true
},
"rules": {
"no-cond-assign": 0
}
}
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dist/
node_modules
67 changes: 67 additions & 0 deletions .stylelintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
{
"rules": {
"at-rule-empty-line-before": ["always", {
"except": ["blockless-after-same-name-blockless", "first-nested"],
"ignore": ["after-comment"]
}],
"at-rule-name-case": ["lower"],
"at-rule-name-space-after": "always-single-line",
"at-rule-semicolon-newline-after": ["always"],
"block-closing-brace-newline-after": ["always"],
"block-closing-brace-newline-before": ["always"],
"block-no-empty": [true],
"block-opening-brace-newline-after": ["always"],
"block-opening-brace-space-before": ["always"],
"color-hex-length": ["short"],
"color-no-invalid-hex": [true],
"comment-whitespace-inside": "always",
"declaration-bang-space-before": ["always"],
"declaration-block-no-duplicate-properties": [true],
"declaration-block-no-shorthand-property-overrides": [true],
"declaration-block-semicolon-space-before": ["never"],
"declaration-block-single-line-max-declarations": [1],
"declaration-block-trailing-semicolon": ["always"],
"declaration-colon-space-after": ["always"],
"declaration-colon-space-before": ["never"],
"function-calc-no-unspaced-operator": [true],
"function-comma-space-after": "always",
"function-linear-gradient-no-nonstandard-direction": true,
"function-max-empty-lines": 0,
"function-name-case": ["lower"],
"function-whitespace-after": ["always"],
"keyframe-declaration-no-important": [true],
"max-empty-lines": 1,
"max-nesting-depth": [2],
"media-feature-colon-space-after": "always",
"media-feature-colon-space-before": "never",
"media-feature-range-operator-space-after": "always",
"media-feature-range-operator-space-before": "always",
"media-query-list-comma-newline-after": "always-multi-line",
"media-query-list-comma-space-after": "always-single-line",
"media-query-list-comma-space-before": "never",
"no-eol-whitespace": [true],
"no-extra-semicolons": [true],
"no-duplicate-selectors": true,
"number-leading-zero": ["never"],
"number-no-trailing-zeros": [true],
"property-case": ["lower"],
"selector-attribute-brackets-space-inside": "never",
"selector-attribute-operator-space-after": "never",
"selector-attribute-operator-space-before": "never",
"selector-combinator-space-after": ["always"],
"selector-combinator-space-before": ["always"],
"selector-list-comma-newline-after": "always",
"selector-list-comma-space-before": "never",
"selector-max-empty-lines": 0,
"selector-pseudo-class-no-unknown": true,
"selector-pseudo-class-parentheses-space-inside": "never",
"selector-pseudo-element-colon-notation": ["single"],
"selector-pseudo-element-no-unknown": true,
"selector-type-no-unknown": true,
"shorthand-property-no-redundant-values": true,
"string-no-newline": true,
"unit-case": "lower",
"unit-no-unknown": true
}

}
27 changes: 27 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
Copyright 2020 Pieter Robberechts
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the name of the author nor the names of contributors may be used to
endorse or promote products derived from this software without specific prior
written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# d3-soccer

A D3 plugin for visualizing event stream soccer data.

<div align="center">
<img src="img/header-readme.png">
</div>

## Installing

If you use NPM, `npm install d3-soccer`. Otherwise, download the [latest release](https://github.com/probberechts/d3-soccer/releases/latest). AMD, CommonJS, and vanilla environments are supported. In vanilla, a d3 global is exported:

```html
<script src="https://d3js.org/d3.v5.min.js"></script>
<script type="text/javascript" src="./dist/d3-soccer.js"></script>
<script type="text/javascript">
var h = 500;
var pitch = d3.pitch().height(h);
var svg = d3.select("#chart")
.append("svg")
.attr("width", "100%")
.attr("height", h);
.append("svg:g")
.call(pitch);
</script>
```

## Usage

See the examples directory.


78 changes: 78 additions & 0 deletions example/actions.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<!DOCTYPE html>
<html>
<head>
<title>D3 soccer</title>
<style type="text/css">
#chart>svg {
margin: 50px;
}
.vizrow {
display: flex;
flex-direction: row;
flex-wrap: wrap;
width: 100%;
align-items: center;
justify-content: center;
align-content: center;
align-items: center;
}

.vizcolumn {
display: flex;
flex-direction: column;
flex-basis: 100%;
flex: 1;
flex-grow: 0;
}
</style>
</head>
<body>

<div class="vizrow">
<div id="chart" class="vizcolumn"></div>
<div id="table" class="vizcolumn"></div>
</div>

<script src="https://d3js.org/d3.v5.min.js"></script>
<script type="text/javascript" src="./dist/d3-soccer.js"></script>
<script type="text/javascript">
var height = 400;

d3.json("data/bel_bra.json").then(data => {
var pitch = d3.pitch().height(height - 20);
var tooltip = d3.actionTooltip();
d3.select("#chart")
.call(tooltip);

var actions = d3.actions(pitch)
.showTooltip(tooltip)
.scale(2)
.teamColors({782:"#EF3340", 781:"#FDB913"});
var actionsTable = d3.actionsTable();
var scoreline = d3.scoreline().teams([
{"label": "BEL", "color": "#EF3340"},
{"label": "BRA", "color": "#FDB913"} ])
.score([2,0])
.clock(30);

var svg = d3.select("#chart").append("svg")
.attr("width", pitch.width())
.attr("height", height)
.attr("class", "light-theme")

akksvg.append("g")
.datum(data.slice(657,663))
.attr("transform", "translate(0,20)")
.call(actions);

svg.append("g")
.attr("transform", "translate(26, 10)")
.call(scoreline)

d3.select("#table")
.datum(data.slice(657,663))
.call(actionsTable)
})
</script>
</body>
</html>
1 change: 1 addition & 0 deletions example/data/bel_bra.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions example/data/debruyne_actions.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions example/data/debruyne_actions_heatmap.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[[0.0, 1.0, 1.0, 2.0, 2.0], [0.0, 1.0, 3.0, 6.0, 5.0], [2.0, 15.0, 11.0, 14.0, 9.0], [3.0, 16.0, 23.0, 22.0, 6.0], [5.0, 27.0, 25.0, 26.0, 10.0], [17.0, 24.0, 26.0, 17.0, 20.0], [21.0, 33.0, 21.0, 45.0, 31.0], [23.0, 24.0, 26.0, 21.0, 19.0], [15.0, 17.0, 12.0, 25.0, 17.0], [8.0, 7.0, 0.0, 1.0, 11.0]]
112 changes: 112 additions & 0 deletions example/data/load_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import json

import numpy as np
import pandas as pd
import socceraction.spadl as spadl
import socceraction.spadl.config as spadlcfg
import socceraction.spadl.statsbomb as statsbomb
import tqdm


def enhance_actions(actions, players, teams):
# data
actiontypes = pd.DataFrame(
list(enumerate(spadlcfg.actiontypes)), columns=["type_id", "type_name"]
)

bodyparts = pd.DataFrame(
list(enumerate(spadlcfg.bodyparts)), columns=["bodypart_id", "bodypart_name"]
)

results = pd.DataFrame(
list(enumerate(spadlcfg.results)), columns=["result_id", "result_name"]
)

return (
actions.merge(actiontypes, how="left")
.merge(results, how="left")
.merge(bodyparts, how="left")
.merge(players[["player_id", "player_name"]], how="left")
.merge(teams[["team_id", "team_name"]], how="left")
)


def count(x, y, n=50, m=50):
xmin = 0
ymin = 0
xdiff = spadlcfg.field_length
ydiff = spadlcfg.field_width

xi = (x - xmin) / xdiff * n
yj = (y - ymin) / ydiff * m
xi = xi.astype(int).clip(0, n - 1)
yj = yj.astype(int).clip(0, m - 1)

flat_indexes = n * (m - 1 - yj) + xi
vc = flat_indexes.value_counts(sort=False)
vector = np.zeros(m * n)
vector[vc.index] = vc
return vector.reshape((m, n))


def always_ltr(actions):
away_idx = ~actions.left_to_right
actions.loc[away_idx, "start_x"] = spadlcfg.field_length - actions[away_idx].start_x.values
actions.loc[away_idx, "start_y"] = spadlcfg.field_width - actions[away_idx].start_y.values
actions.loc[away_idx, "end_x"] = spadlcfg.field_length - actions[away_idx].end_x.values
actions.loc[away_idx, "end_y"] = spadlcfg.field_width - actions[away_idx].end_y.values
return actions


if __name__ == "__main__":

# Set up the statsbombloader
free_open_data_remote = "https://raw.githubusercontent.com/statsbomb/open-data/master/data/"
SBL = statsbomb.StatsBombLoader(root=free_open_data_remote,getter="remote")

# Select competitions to load and convert
competitions = SBL.competitions()
selected_competitions = competitions[competitions.competition_name=="FIFA World Cup"]

# Get matches from all selected competitions
matches = list(
SBL.matches(row.competition_id, row.season_id)
for row in selected_competitions.itertuples()
)
matches = pd.concat(matches, sort=True).reset_index(drop=True)
matches[["home_team_name","away_team_name","match_date","home_score","away_score"]]

# Load and convert match data
matches_verbose = tqdm.tqdm(list(matches.itertuples()),desc="Loading match data")
teams,players,player_games = [],[],[]
actions = {}
for match in matches_verbose:
# load data
teams.append(SBL.teams(match.match_id))
players.append(SBL.players(match.match_id))
events = SBL.events(match.match_id)

# convert data
player_games.append(statsbomb.extract_player_games(events))
actions[match.match_id] = statsbomb.convert_to_actions(events,match.home_team_id)
actions[match.match_id]["left_to_right"] = actions[match.match_id]["team_id"] == match.home_team_id


games = matches.rename(columns={"match_id":"game_id"})
teams = pd.concat(teams).drop_duplicates("team_id").reset_index(drop=True)
players = pd.concat(players).drop_duplicates("player_id").reset_index(drop=True)
player_games = pd.concat(player_games).reset_index(drop=True)

# get all actions from Belgium - Brazil
enhance_actions(actions[8650], players, teams).to_json('./bel_bra.json', orient='records')

# get all actions by De Bruyne
debruyne_actions = []
for match_id, match_actions in actions.items():
debruyne_actions.append(match_actions[(match_actions.player_id == 3089)])
debruyne_actions = always_ltr(enhance_actions(pd.concat(debruyne_actions), players, teams))
debruyne_actions.to_json('./debruyne_actions.json', orient='records')
heatmap = count(debruyne_actions.start_x, debruyne_actions.start_y, 10, 5).T
with open('debruyne_actions_heatmap.json', 'w') as outfile:
json.dump(heatmap.tolist(), outfile)

Loading

0 comments on commit 9dabc11

Please sign in to comment.