Going deeper into IBM’s Quantum Experience!


Introduction

In this post I delve deeper into IBM’s Quantum Experience. As mentioned in my earlier post “Venturing into IBM’s Quantum Experience”, IBM, has opened up its Quantum computing environment, to the general public, as the Quantum Experience. The access to Quantum Experience is through IBM’s Platform as a Service (PaaS) offering, Bluemix™. Clearly this is a great engineering feat, which integrates the highly precise environment of Quantum Computing, where the qubits are maintained at 5 milliKelvin, and the IBM Bluemix PaaS environment on Softlayer. The Quantum Experience, is in fact Quantum Computing as a Service (QCaaS).  In my opinion, the Quantum Experience, provides a glimpse of tomorrow, today,

Disclaimer: This article represents the author’s viewpoint only and doesn’t necessarily represent IBM’s positions, strategies or opinions

Note: Also by the way, feel free to holler if you find anything incorrect or off the mark in my post. I am just getting started on quantum computing so there may be slip ups.

A) Bloch sphere

6In my earlier post the operations of the X, Y, Z, H, S, and S1 were measured using the standard or diagonal basis and the results were in probabilities of the qubit(s). However, the probabilities alone, in the standard basis, are not enough to specify a quantum state because it does not capture the phase of the superposition. A convenient representation for a qubit is the Bloch sphere.

The general state of a quantum two-level system can be written in the form

|ψ⟩=α|0⟩+β|1⟩,

Where α and β are complex numbers with |α|2+|β|2=1. This leads to the “canonical” parameterized form

|ψ⟩= cos Θ/2 |0> + e sin Θ/2 |1>                        (A)

in terms of only two real numbers θ and φ, with natural ranges 0 ≤ θ ≤ π and 0 ≤ φ ≤ 2π. These are the same as the polar angles in 3-dimensional spherical coordinates, and this leads to the representation of the state (1) as a point on a unit sphere called the Bloch sphere.

In the notation of (A), the state |0> is represented by the North pole, and the state |1> by the South pole. Note:  The states |0> and |1> , n the Bloch sphere are not orthogonal to each other. The states on the equator of the Bloch sphere, correspond to superpositions of |0> and |1> with equal weights (θ = π∕2), and different phases, parameterized by the azimuthal angle φ (the “longitude”)

In the picture below  Bloch  measurements  are performed on the operations on the qubits

1

The results of the Bloch measurements for the combination of  quantum gates are shown below

i) Quantum gate operations and Bloch measurements

4

ii) Quantum gate operations as Superposition operations

5

B) Classical vs Quantum computing
A classical computer that has N-bits has 2^{N}possible configurations. However, at any
one point in time, it can be in one, and only one of  2N  configurations. Interestingly, the quantum computer also takes in a n -bit number and outputs a n -bit number; but because of the superposition principle and the possibility of entanglement, the intermediate state is very different.

A system which had N different mutually exclusive states can be represented as |1>, |2>. . . |N> using the Dirac’s bra-ket notation

A pure quantum state is a superposition of all these states
Φ = α1 1> + α2 2> + …. + αN N>
To describe it requires complex numbers, giving a lot more room for maneuvering.

C) The CNOT gate
The CNOT gate or the Controlled-Not gate is an example of a two-qubit quantum gate. The CNOT gate’s action is to flip (apply a NOT or X gate to) the target qubit if the control qubit is 1; otherwise it does nothing. The CNOT plays the role of the classical XOR gate, but unlike the XOR, The CNOT gate is a two-output gate and is reversible It is represented by the matrix by the following 4 x 4 matrix

\begin{pmatrix}1 & 0 & 0 &0 \\ 0 & 1 & 0 &0 \\  0& 0 &  0&1 \\ 0 & 0 & 1 & 0\end{pmatrix}

The CNOT gate flips the target bit if the control bit is 1, otherwise it does nothing if it’s 0:

More specifically
CNOT|0>|b> = |0>|b>
CNOT|1>|b>= |1>|1 – b>

The operation of the CNOT gate can be elaborated as below
The 2-qubit basis states can be represented as four-dimensional vectors
|00> = \begin{pmatrix} 1& 0 & 0 & 0 \end{pmatrix}^{T}
|01> = \begin{pmatrix} 0& 1 & 0 & 0 \end{pmatrix}^{T}
|10> = \begin{pmatrix} 0& 0 & 1 & 0 \end{pmatrix}^{T}
|11> = \begin{pmatrix} 0& 0 & 0 & 1 \end{pmatrix}^{T}

For example, a quantum state may be expanded as a linear combination of this basis:
|ψ⟩=a|00⟩+b|01⟩+c|10⟩+d|11⟩

The CNOT matrix can  be applied as below
CNOT*|ψ⟩=CNOT*(a|00⟩+b|01⟩+c|10⟩+d|11⟩)
= a*CNOT*|00⟩+…+d*CNOT*|11⟩

where you perform standard matrix multiplication on the basis vectors to get:
CNOT*|ψ⟩=a|00⟩+b|01⟩+c|11⟩+d|10⟩

In other words, the CNOT gate has transformed
|10⟩↦|11⟩ and |11⟩↦|10⟩

i) CNOT operations in R code

# CNOT gate
cnot= matrix(c(1,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0),nrow=4,ncol=4)
cnot
##      [,1] [,2] [,3] [,4]
## [1,]    1    0    0    0
## [2,]    0    1    0    0
## [3,]    0    0    0    1
## [4,]    0    0    1    0
#a. Qubit |00> 
q00=matrix(c(1,0,0,0),nrow=4,ncol=1)
q00
##      [,1]
## [1,]    1
## [2,]    0
## [3,]    0
## [4,]    0
# CNOT *q00 ==> q00
a <- cnot %*% q00
a
##      [,1]
## [1,]    1
## [2,]    0
## [3,]    0
## [4,]    0
#b.Qubit |01>
q01=matrix(c(0,1,0,0),nrow=4,ncol=1)
q01
##      [,1]
## [1,]    0
## [2,]    1
## [3,]    0
## [4,]    0
# CNOT *q01 ==> q01
a <- cnot %*% q01
a
##      [,1]
## [1,]    0
## [2,]    1
## [3,]    0
## [4,]    0
#c. Qubit |10>
q10=matrix(c(0,0,1,0),nrow=4,ncol=1)
q10
##      [,1]
## [1,]    0
## [2,]    0
## [3,]    1
## [4,]    0
# CNOT *q10 ==> q11
a <- cnot %*% q10
a
##      [,1]
## [1,]    0
## [2,]    0
## [3,]    0
## [4,]    1
#d. Qubit |11>
q11=matrix(c(0,0,0,1),nrow=4,ncol=1)
q11
##      [,1]
## [1,]    0
## [2,]    0
## [3,]    0
## [4,]    1
# CNOT *q11 ==> q10
a <- cnot %*% q11
a
##      [,1]
## [1,]    0
## [2,]    0
## [3,]    1
## [4,]    0

D) Non Clifford gates
The quantum gates discussed in my earlier post (Pauli X, Y, Z, H, S and S1) and the CNOT are members of a special group of gates known as the ‘Clifford group’. These gates can be simulated efficiently on a classical computer. Therefore, the Clifford group is not universal.  A finite set of gates that can approximate any arbitrary unitary matrix is known as a universal gate set. This is similar,  to how certain sets of classical logic gates, such as {AND, NOT}, are functionally complete and can be used to build any Boolean function ( I remember this axiom/fact from my Digital Electronics -101 class about 3  decades back!).

Adding almost any non-Clifford gate to single-qubit Clifford gates and CNOT gates makes the group universal which I presume can simulate any arbitrary unitary matrix.  The non-Clifford gates, discussed are the T and  Tǂ gates

These are given by

T = \begin{pmatrix}1 & 0\\ 0 & e^{^{i\prod /4}}\end{pmatrix}

Tǂ =\begin{pmatrix}1 & 0\\ 0 & e^{^{-i\prod /4}}\end{pmatrix}

i) T gate operations
The T gate makes it possible to reach  different points of the Bloch sphere.  By increasing the number of T-gates in the quantum circuit ( we start to cover the Bloch sphere more densely with states that can be reached

ii)  T Gates of depth 2 – Computational Measurement
9

Simulating in Composer
10

iii) Simulating in R Code
Measurement only gives the real part and does not provide info on phase

# T Gate 
T=matrix(c(1,0,0,exp(1i*pi/4)),nrow=2,ncol=2)
# Simulating T Gate depth-2 - Computational  measurement
a=S%*%T%*%H%*%T%*%H%*%q0
a
##                      [,1]
## [1,] 0.8535534+0.3535534i
## [2,] 0.1464466+0.3535534i

iv) 2 T Gates – Bloch  Measurement
7

Bloch measurement

8

v) Simulating T gate in R code
This gives the phase values as shown in the Bloch sphere

# Simulating T Gate depth-2 - Bloch measurement (use a diagonal basis H gate in front)
a=H%*%S%*%T%*%H%*%T%*%H%*%q0
a
##                [,1]
## [1,] 0.7071068+0.5i
## [2,] 0.5000000+0.0i

 

E) Quantum Entanglement – The case of ‘The Spooky action at a distance’
One of the infamous counter-intuitive ideas of quantum mechanics is that two systems that appear too far apart to influence each other can nevertheless behave in ways that, though individually random, are too strongly correlated to be described by any classical local theory.  For e.g. when the 1st qubit of a pair of “quantum  entangled” qubits are measured, this automatically determines the 2nd qubit, though the individual qubits may be separated by extremely large distances. It appears that the measurement of the first qubit cannot affect the 2nd qubit which is too far apart to be be influenced and also given the fact  that nothing can travel faster than the speed of light.  More specifically

“Suppose Alice has the first qubit of the pair, and Bob has the second. If Alice measures her qubit in the computational basis and gets outcome b ∈ {0, 1},  then the state collapses to |bb> . In other words the measurements and outcome of the 1st qubit determines the outcome of the  2nd qubit . How weird is that?

Similarly, if Alice measures her qubit in some other basis, this will collapse the joint state (including Bob’s qubit) to some state that depends on her measurement basis as well as its outcome. Somehow Alice’s action seems to have an instantaneous effect on Bob’s side—even if the two qubits are light-years apart!”

How weird is that!

Einstein, whose theory of relativity posits that information and causation cannot travel faster than the speed of light, was greatly troubled by this, . Einstein called such effects of entanglement “spooky action at a distance”.

In the 1960s, John Bell devised entanglement-based experiments whose behavior cannot be reproduced by any “local realist” theory where the implication of local and realist is given below

Locality: No information can travel faster than the speed of light. There is a hidden variable that defines all the correlations.

Realism:  All observables have a definite value independent of the measurement

i) Bell state measurements
The mathematical proof for the Bell tests  are quite abstract  and mostly escaped my grasp. I  hope to get my arms around this beast, in the weeks and months to come. However, I understood how to run the tests and perform the calculations which are included below.  I have executed the Bell Tests on

a) Ideal Quantum Processor (Simulator with ideal conditions)
b) Realistic Quantum Processor (Simulator with realistic conditions)
c) Real Quantum Processor. For this I used 8192 ‘shots’ repeats of the experiment

I finally calculate |C| for all 3 tests

The steps involved in calculating |C|
1.  Execute ZW, ZV, XW, XV
2. Calculate <AB> = P(00) + P(11) – P(01) – P(10)
3.  Finally |C| = ZW + ZV + XW – XV

Preparation of Qubit |00>
The qubits are in state |00> The H gate  takes the first qubit to the equal superposition

1/√2(|00> + |10>)  and the CNOT gate flips the second qubit if the first is excited, making the state  1/√2(|00> + |11>). This is the entangled state (commonly called a Bell state)

11

Simulating in Composer
This prepares the entangled state 1/√2(|00> + |11>)

12

It can be seen that the the qubits |00> and  |11> are created

1) Simulations on Ideal Quantum processor

a) Bell state ZW (Ideal) 
13
Simulation
24
P(00) = 0.427
P(01) = 0.073
P(10) =0.073
P(11) = 0.427

b) Bell state ZV (Ideal) 
14

Simulation

25
P(00) = 0.427
P(01) = 0.073
P(10) =0.073
P(11) = 0.427

c) Bell state XW (Ideal)
26

Measurement
27
P(00) = 0.427
P(01) = 0.073
P(10) =0.073
P(11) = 0.427

d) Bell state XV (Ideal)
28

Simulating Bell State XV in Composer
16
P(00) = 0.073
P(01) = 0.473
P(10) = 0.473
P(11) =0.73

Bell test measurement in Ideal Quantum Processor are given below
Untitled

For the Ideal Quantum Processor
|C) = 2.832

2) Simulations on the Realistic  Quantum Processor
The Bell tests above were simulated on Realistic Quantum Processor. The results are included below

Untitled

For the Realistic Quantum Processor
|C) = 2.523

3) Real IBM Quantum  Processor (8192 shots)
Finally the Bell Tests were executed in IBM’s Real Quantum Processor for 8192 shots, each requiring 5 standard units. The tests were queued, executed and the results sent by mail. The results are included below
a) Bell State ZW measurement (Real)
29

b) Bell state ZV measurement  (Real)
30
c) Bell State XW measurement (Real)
31
d) Bell state XV measurement (Real)

32

;

The results were tabulated and |C| computed. Bell test measurement in Real Quantum Processor are given below

Untitled

The Bell measurements on the Reak Quantum Processor is
|C) = 2.509

Conclusion
This post included details on the CNOT and the non-Clifford gates. The Bell tests were performed on all 3 processors Ideal, Realistic and Real Quantum Processors and in each case the |C| > 2. While I have been to execute the tests I will definitely have to spend more time understanding the nuances.

I hope to continue this journey into quantum computing the months to come. Watch this space!

Disclaimer: This article represents the author’s viewpoint only and doesn’t necessarily represent IBM’s positions, strategies or opinions

References
1.IBM Quantum Experience – User Guide
2.Quantum Computing lecture notes – Ronald De Wolf
3.Bloch sphere
4.Basic concepts in quantum computation
5.Physics Stack Exchange

You may also like
1.Revisiting crimes against women in India
2.Natural language processing: What would Shakespeare say?
3.Beaten by sheer pace – Cricket analytics with yorkr
4.A method for optimal bandwidth usage by auctioning available bandwidth using the OpenFlow protocol
5.TWS-4: Gossip protocol: Epidemics and rumors to the rescue
6.Bend it like Bluemix, MongoDB using Auto-scale – Part 1!
7.Fun simulation of a Chain in Android
8.Cricket analytics with cricketr in paperback and Kindle versions

Venturing into IBM’s Quantum Experience


UntitledIntroduction: IBM opened the doors of its Quantum Computing Environment, termed “Quantum Experience” to the general public about 10 days back. The access to IBM’s Quantum Experience is through Bluemix service , IBM’s  PaaS (Platform as a Service). So I  signed up for IBM’s quantum experience with great excitement. So here I am, an engineer trying to enter into and understand the weird,weird world of the quantum physicist!

Disclaimer: This article represents the author’s viewpoint only and doesn’t necessarily represent IBM’s positions, strategies or opinions

The idea of Quantum computing was initially mooted by Nobel Laureate Richard Feynman, Yuri Manning and Paul Benioff in the 1980s. While there was some interest in the field for the next several years, work in Quantum computing received a shot in the arm after Peter Shor’s discovery of an efficient quantum algorithm for integer factorization and discrete logarithms.

Problems that are considered to be computationally hard to solve with classical computers can be solved through quantum computing with an exponential improvement in efficiency.  Some areas that are supposed to be key candidates for quantum computing, are quantum money and cryptography.

Quantum computing will become predominant in our futures owing to 2 main reasons. The 1st reason, as already mentioned, is extraordinary performance improvements. The 2nd is due to the process of miniaturization. Ever since the advent of the transistor and the integrated circuit, the advancement in computing has led the relentless pursuit of miniaturization.,  In recent times the number of transistors has increased to such an extent, that quantum effects become apparent,  at such micro levels,  while  making the chips extremely powerful and cheap. The 18 core Xeon Haswell  Inel processoir packs 5.5 billion transistor in 661 mm2

 In classical computers the computation is based on the ‘binary digit’ or ‘bit’ which can be in either state 0 or 1. In quantum computing the unit of computation is the ‘quantum bit’ or the qubit. The quantum bit  can be in the states of 0, 1 and both simultaneously by the principle of superposition.

A qubit is a quantum system consisting of two levels, labeled |0⟩ and |1⟩ (using Dirac’s bracket notation) and is represented by a two-dimensional vector space.

|0>=\begin{pmatrix}1\\ 0\end{pmatrix}

|1>=\begin{pmatrix}0\\ 1\end{pmatrix}

Consider some physical system that can be in N different, mutually exclusive classical states. Then in the classical computing the system can be in one of the 2^{N} states. For e.g. if we had 3 bits the classical computer could be in one of {000,001,010,011,100,101,110,111} states.

A quantum computer takes advantage of a special kind of superposition that allows for exponentially many logical states at once, all the states from |00…0⟩ to |11…1⟩

Hence, the qubit need not be |0> or |1> but can be in any state |Ψ> which can be any superposition |ψ⟩=α|0⟩+β|1⟩, where α and β are the amplitudes. The superposition quantities α and β are complex numbers and obey |α|2+|β|2=1

Let us consider  a system which had N different mutually exclusive states. Using Dirac’s notation these states can be represented as |1>, |2>. . . |N>.

A pure quantum state is a superposition of all these states

Φ = α1 |1> + α2 |2> + …. + αN |N>

Where αi is the amplitude of qubit ‘I’ |i> in Φ. Hence, a system in quantum state |φi is in all classical states at the same time. It is state |1> with an amplitude of α1, in state |2> with an amplitude α2 etc.

A quantum system which is in all states at once can be either measured or allowed to evolve unitarily without measuring

Measurement

The interesting fact is that when we measure the quantum state Φ, the measured state will not be the quantum state Φ, but one  classical state |j> , where |j> is one of the states |1>,|2,.. |N>. The likelihood for the measured state to be |j> is dependent on the probability |αj |2, which is the squared norm of the corresponding amplitude αj. Hence observing the quantum state Φ results in the collapse of the quantum superposition state Φ top a classical state |j> and all the information in the amplitudes αj I

Φ = α1 |1> + α2 |2> + … + αN |N>

Unitary evolution

The other alternative is instead of measuring the quantum state Φ, is to apply a series of unitary operations and allow the quantum system to evolve.

In this post I use IBM’s Quantum Experience. The IBM’s Quantum Experience uses a type of qubit made from superconducting materials such as niobium and aluminum, patterned on a silicon substrate.

For this superconducting qubit to behave as the abstract notion of the qubit, the device is cooled down considerably. In fact, in the IBM Quantum Lab, the temperature is maintained at 5 milliKelvin, in a dilution refrigerator

The Quantum Composer a Graphical User Interface (GUI) for programming the quantum processor. With the quantum composer we can construct quantum circuits using a library of well-defined gates and measurements.

The IBM’s Quantum Composer is designed like a musical staff with 5 horizontal lines for the 5 qubits. Quantum gates can be dragged and dropped on these horizontal lines to operate on the qubits

Quantum gates are represented as unitary matrices, and operations on qubits are matrix operations, and as such require knowledge of linear algebra. It is claimed, that while the math behind quantum computing may not be too hard, the challenge is that certain aspects of quantum computing are counter-intuitive. This should be challenge. I hope that over the next few months I will be able to develop at least some basic understanding for the reason behind the efficiency of quantum algorithms

Pauli gates

The operation of a quantum gate can be represented as a matrix.  A gate that acts on one qubit is represented by a 2×2 unitary matrix. A unitary matrix is one, in which the conjugate transpose of the matrix is also its inverse. Since quantum operations need to be reversible, and preserve probability amplitudes, the matrices must be unitary.

To understand the operations of the gates on the qubits, I have used R language to represent matrices, and to perform the matrix operations. Personally , this made things a lot clearer to me!

Performing measurement

The following picture shows how the qubit state is measured in the Quantum composer

1

Simulation in the Quantum Composer

When the above measurement is simulated in the composer by clicking the ‘Simulate’ button the result is as below

2

This indicates that the measurement will display qubit |0> with a 100% probability or the qubit is in the ‘idle’ state.

A) Pauli operators

A common group of gates are the Pauli operators

a) The Pauli X

|0> ==>  X|0> ==> |1>

The Pauli X gate which is represented as below  does a bit flip

\begin{pmatrix}0&1\\1&0\end{pmatrix}

This can be composed in the Quantum composer as

3

When this simulated the Pauli X gate does a bit flip and the result is

4

which is qubit |1> which comes up as 1 (100% probability)

Pauli operator X using R code

# Qubit '0'
q0=matrix(c(1,0),nrow=2,ncol=1)
q0
##      [,1]
## [1,]    1
## [2,]    0
# Qubit '1'
q1=matrix(c(0,1),nrow=2,ncol=1)
q1
##      [,1]
## [1,]    0
## [2,]    1
# Pauli operator X
X= matrix(c(0,1,1,0),nrow=2,ncol=2)
X
##      [,1] [,2]
## [1,]    0    1
## [2,]    1    0
# Performing a X operation on q0 flips a q0 to q1
a=X%*%q0
a
##      [,1]
## [1,]    0
## [2,]    1

b) Pauli operator Z

The Z operator does a phase flip and is represented by the matrix

\begin{pmatrix}1&0\\0&-1\end{pmatrix}

Simulation in the Quantum composer
8

Pauli operator Z using R code

# Pauli operator Z
Z=matrix(c(1,0,0,-1),nrow=2,ncol=2)
Z
##      [,1] [,2]
## [1,]    1    0
## [2,]    0   -1
# Performing a Z operation changes the phase and leaves the bit 
a=Z%*%q0
a
##      [,1]
## [1,]    1
## [2,]    0

c) Pauli operator Y

The Pauli operator Y  does both  a bit and a phase flip. The Y operator is represented as

\begin{pmatrix}0&-i\\i&0\end{pmatrix}

Simulating in the composer gives the following

11

Pauli operator Y in  R code

# Pauli operator Y
Y=matrix(c(0,-1i,1i,0),nrow=2,ncol=2)
Y
##      [,1] [,2]
## [1,] 0+0i 0+1i
## [2,] 0-1i 0+0i
# Performing a Y operation does a bit flip and changes the phase 
a=Y%*%q0
a
##      [,1]
## [1,] 0+0i
## [2,] 0-1i

B) Superposition
Superposition is the concept that adding quantum states together results in a new quantum state. There are 3 gates that perform superposition of qubits the H, S and S’ gate.
a) H gate (Hadamard gate)
The H gate, also known as the Hadamard Gate when applied |0> state results in the qubit being half the time in  |0> and the other half in |1>
The H gate can be represented as

1/√2 \begin{pmatrix}1 & 1\\ 1 & -1\end{pmatrix}

# Superposition gates
# H, S & S1
H=1/sqrt(2) * matrix(c(1,1,1,-1),nrow=2,ncol=2)
H
##           [,1]       [,2]
## [1,] 0.7071068  0.7071068
## [2,] 0.7071068 -0.7071068

b) S gate
The S gate can be represented as
\begin{pmatrix}1 & 0\\ 0 & i\end{pmatrix}

S=matrix(c(1,0,0,1i),nrow=2,ncol=2)
S
##      [,1] [,2]
## [1,] 1+0i 0+0i
## [2,] 0+0i 0+1i

c) S’ gate
And the S’ gate is
\begin{pmatrix}1 & 0\\ 0 & -i\end{pmatrix}

S1=matrix(c(1,0,0,-1i),nrow=2,ncol=2)
S1
##      [,1] [,2]
## [1,] 1+0i 0+0i
## [2,] 0+0i 0-1i

d) Superposition (+)
Applying the Hadamard gate H to |0> causes it to become |+>. This is the standard superposition state
Where |+> = 1/√2 (|0> + |1>)

|0> ==> H|0>  ==>  |+>
Where the qubit is one half of the time in |0> and the other half of the time in |1>
Simulating in the Composer
14

Superposition(+) in R code
Superposition of qubit |0> results in |+> as shown below

|0> ==> H|0>  ==>  |+>

# H|0>
a <- H%*%q0
a
##           [,1]
## [1,] 0.7071068
## [2,] 0.7071068
# This is equal to 1/sqrt(2) (|0> + |1>)
b <- 1/sqrt(2) * (q0+q1)
b
##           [,1]
## [1,] 0.7071068
## [2,] 0.7071068

e) Superposition (-)

A new qubit state |-> is obtained by applying the H gates to |0> and then applying the Z gate which is known as the  diagonal basis. The H makes the above superposition and then the Z flips the phase (|1⟩ to −|1⟩)

Where |-> = 1/√2 (|0> – |1>)
|0> ==>  Z*H*|0> ==>  |->

Simulating in the Composer
15

Superposition(-) in R code

# The diagonal basis
# It can be seen that a <==>b
a <- Z%*%H%*%q0
a
##            [,1]
## [1,]  0.7071068
## [2,] -0.7071068
b <- 1/sqrt(2) * (q0-q1)
b
##            [,1]
## [1,]  0.7071068
## [2,] -0.7071068

C) Measuring superposition

But when we measure the superposition states the result is always a 0 or 1. In order to distinguish between the |+> and the |-> states we need to measure in the diagonal basis. This is done by using the H gate before the measurement

a) Superposition (+) measurement

19

Superposition(+) in R code

# Superposition (+) measurement
a <- H%*%H%*%q0
# The result is |0>
a
##      [,1]
## [1,]    1
## [2,]    0

b) Superposition (-) measurement

Simulating in composer

22

Simulating Superposition(-) in R code

# Superposition (-) measurement
a <- H%*%Z%*%H%*%q0
#The resultis |1>
a
##      [,1]
## [1,]    0
## [2,]    1

D) Y basis
A third basis us the circular or Y basis

|ac*> = 1/√2(|0> + i|1>)
ac* – the symbol is an anti-clockwise arrow

And

|c*> = 1/√2(|0> – i|1>)
c* – the symbol for clockwise arrow

a) Superposition (+i)Y

Simulating in Composer
29

Superposition (+i)Y in R code

#Superposition(+i) Y
a <- S%*%H%*%q0
a
##                      [,1]
## [1,] 0.7071068+0.0000000i
## [2,] 0.0000000+0.7071068i
b <- 1/sqrt(2)*(q0 +1i*q1)
b
##                      [,1]
## [1,] 0.7071068+0.0000000i
## [2,] 0.0000000+0.7071068i

b) Superposition(-i)Y 

Simulating Superposition (-i)Y in Quantum Composer
30

Superposition (-i)Y in R 

#Superposition(-i) Y
a <- S1%*%H%*%q0
a
##                      [,1]
## [1,] 0.7071068+0.0000000i
## [2,] 0.0000000-0.7071068i
b <- 1/sqrt(2)*(q0 -1i*q1)
b
##                      [,1]
## [1,] 0.7071068+0.0000000i
## [2,] 0.0000000-0.7071068i

To measure the circular basis we need to add a S1 and H gate

c) Superposition (+i) Y measurement

Simulation in Quantum composer

25

Superposition (+i) Y in R 

#Superposition(+i) Y measurement
a <- H%*%S1%*%S%*%H%*%q0
a
##      [,1]
## [1,] 1+0i
## [2,] 0+0i

d) Superposition (-Y) simulation

28

Superposition (-i) Y in R

#Superposition(+i) Y measurement
a <- H%*%S1%*%S%*%H%*%q0
a
##      [,1]
## [1,] 1+0i
## [2,] 0+0i

I hope to make more headway and develop the intuition for quantum algorithms in the weeks and months to come.

Watch this space. I’ll be back!

Disclaimer: This article represents the author’s viewpoint only and doesn’t necessarily represent IBM’s positions, strategies or opinions

References
1.IBM’s  Quantum Experience User Guide
2. Quantum computing lecture notes

Also see
1. Natural language processing: What would Shakespeare say?
2. Literacy in India – A deepR dive
3. Re-introducing cricketr! : An R package to analyze performances of cricketers
4. Design Principles of Scalable, Distributed Systems
5. A closer look at “Robot Horse on a Trot” in Android
6. What’s up Watson? Using IBM Watson’s QAAPI with Bluemix, NodeExpress – Part 1
7. Introducing cricket package yorkr: Part 1- Beaten by sheer pace!
8. Experiments with deblurring using OpenCV
9. Architecting a cloud based IP Multimedia System (IMS)

Re-introducing cricketr! : An R package to analyze performances of cricketers


In this post I re-introduce R package cricketr. I have added 8 new functions to my R package cricketr, available from version cricketr_0.0.13 namely

  1. batsmanCumulativeAverageRuns
  2. batsmanCumulativeStrikeRate
  3. bowlerCumulativeAvgEconRate
  4. bowlerCumulativeAvgWicketRate
  5. relativeBatsmanCumulativeAvgRuns
  6. relativeBatsmanCumulativeStrikeRate
  7. relativeBowlerCumulativeAvgWickets
  8. relativeBowlerCumulativeAvgEconRate

This post updates my earlier post Introducing cricketr:An R package for analyzing performances of cricketrs

Yet all experience is an arch wherethro’
Gleams that untravell’d world whose margin fades
For ever and forever when I move.
How dull it is to pause, to make an end,
To rust unburnish’d, not to shine in use!

Ulysses by Alfred Tennyson

 Introduction

This is an initial post in which I introduce a cricketing package ‘cricketr’ which I have created. This package was a natural culmination to my earlier posts on cricket and my finishing 10 modules of Data Science Specialization, from John Hopkins University at Coursera. The thought of creating this package struck me some time back, and I have finally been able to bring this to fruition.

So here it is. My R package ‘cricketr!!!’

This package uses the statistics info available in ESPN Cricinfo Statsguru. The current version of this package can handle all formats of the game including Test, ODI and Twenty20 cricket.

You should be able to install the package from GitHub and use  many of the functions available in the package. Please be mindful of  ESPN Cricinfo Terms of Use

Note: This page is also hosted as a GitHub page at cricketr

This post is also hosted on Rpubs at Reintroducing cricketr. You can also down the pdf version of this post at reintroducing_cricketr.pdf

(Take a look at my short video tutorial on my R package cricketr on Youtube – R package cricketr – A short tutorial)

Do check out my interactive Shiny app implementation using the cricketr package – Sixer – R package cricketr’s new Shiny avatar

Take a look at my book with all my articles related to cricket –  Cricket analytics with cricketr!!!. The book is also available in paperback and kindle versions at Amazon  which has, by the way,  better formatting!

Also see my 2nd book “Beaten by sheer pace”  based on my R package yorkr which is now available in paperback and kindle versions at Amazon

 The cricketr package

The cricketr package has several functions that perform several different analyses on both batsman and bowlers. The package has functions that plot percentage frequency runs or wickets, runs likelihood for a batsman, relative run/strike rates of batsman and relative performance/economy rate for bowlers are available.

Other interesting functions include batting performance moving average, forecast and a function to check whether the batsman/bowler is in in-form or out-of-form.

The data for a particular player can be obtained with the getPlayerData() function from the package. To do this you will need to go to ESPN CricInfo Player and type in the name of the player for e.g Ricky Ponting, Sachin Tendulkar etc. This will bring up a page which have the profile number for the player e.g. for Sachin Tendulkar this would be http://www.espncricinfo.com/india/content/player/35320.html. Hence, Sachin’s profile is 35320. This can be used to get the data for Tendulkar as shown below

The cricketr package is now available from  CRAN!!!.  You should be able to install directly with

if (!require("cricketr")){ 
    install.packages("cricketr",lib = "c:/test") 
} 
library(cricketr)

The cricketr package includes some pre-packaged sample (.csv) files. You can use these sample to test functions  as shown below

# Retrieve the file path of a data file installed with cricketr
pathToFile <- system.file("data", "tendulkar.csv", package = "cricketr")
batsman4s(pathToFile, "Sachin Tendulkar")

# The general format is pkg-function(pathToFile,par1,...)
batsman4s(<path-To-File>,"Sachin Tendulkar")

unnamed-chunk-2-1

Alternatively, the cricketr package can be installed from GitHub with

if (!require("cricketr")){ 
    library(devtools) 
    install_github("tvganesh/cricketr") 
}
library(cricketr)

The pre-packaged files can be accessed as shown above.
To get the data of any player use the function getPlayerData()

tendulkar <- getPlayerData(35320,dir="..",file="tendulkar.csv",type="batting",homeOrAway=c(1,2),
                           result=c(1,2,4))

Important Note This needs to be done only once for a player. This function stores the player’s data in a CSV file (for e.g. tendulkar.csv as above) which can then be reused for all other functions. Once we have the data for the players many analyses can be done. This post will use the stored CSV file obtained with a prior getPlayerData for all subsequent analyses

Sachin Tendulkar’s performance – Basic Analyses

The 3 plots below provide the following for Tendulkar

  1. Frequency percentage of runs in each run range over the whole career
  2. Mean Strike Rate for runs scored in the given range
  3. A histogram of runs frequency percentages in runs ranges
par(mfrow=c(1,3))
par(mar=c(4,4,2,2))
batsmanRunsFreqPerf("./tendulkar.csv","Sachin Tendulkar")
batsmanMeanStrikeRate("./tendulkar.csv","Sachin Tendulkar")
batsmanRunsRanges("./tendulkar.csv","Sachin Tendulkar")

tendulkar-batting-1

dev.off()
## null device 
##           1

More analyses

par(mfrow=c(1,3))
par(mar=c(4,4,2,2))
batsman4s("./tendulkar.csv","Tendulkar")
batsman6s("./tendulkar.csv","Tendulkar")
batsmanDismissals("./tendulkar.csv","Tendulkar")

tendulkar-4s6sout-1

 

3D scatter plot and prediction plane

The plots below show the 3D scatter plot of Sachin’s Runs versus Balls Faced and Minutes at crease. A linear regression model is then fitted between Runs and Balls Faced + Minutes at crease

battingPerf3d("./tendulkar.csv","Sachin Tendulkar")

tendulkar-3d-1

Average runs at different venues

The plot below gives the average runs scored by Tendulkar at different grounds. The plot also displays the number of innings at each ground as a label at x-axis. It can be seen Tendulkar did great in Colombo (SSC), Melbourne ifor matches overseas and Mumbai, Mohali and Bangalore at home

batsmanAvgRunsGround("./tendulkar.csv","Sachin Tendulkar")
tendulkar-avggrd-1

Average runs against different opposing teams

This plot computes the average runs scored by Tendulkar against different countries. The x-axis also gives the number of innings against each team

batsmanAvgRunsOpposition("./tendulkar.csv","Tendulkar")
tendulkar-avgopn-1

Highest Runs Likelihood

The plot below shows the Runs Likelihood for a batsman. For this the performance of Sachin is plotted as a 3D scatter plot with Runs versus Balls Faced + Minutes at crease using. K-Means. The centroids of 3 clusters are computed and plotted. In this plot. Sachin Tendulkar’s highest tendencies are computed and plotted using K-Means

batsmanRunsLikelihood("./tendulkar.csv","Sachin Tendulkar")

tendulkar-kmeans-1

## Summary of  Sachin Tendulkar 's runs scoring likelihood
## **************************************************
## 
## There is a 16.51 % likelihood that Sachin Tendulkar  will make  139 Runs in  251 balls over 353  Minutes 
## There is a 58.41 % likelihood that Sachin Tendulkar  will make  16 Runs in  31 balls over  44  Minutes 
## There is a 25.08 % likelihood that Sachin Tendulkar  will make  66 Runs in  122 balls over 167  Minutes

A look at the Top 4 batsman – Tendulkar, Kallis, Ponting and Sangakkara

The batsmen with the most hundreds in test cricket are

  1. Sachin Tendulkar :Average:53.78,100’s – 51, 50’s – 68
  2. Jacques Kallis : Average: 55.47, 100’s – 45, 50’s – 58
  3. Ricky Ponting : Average: 51.85, 100’s – 41 , 50’s – 62
  4. Kumara Sangakarra: Average: 58.04 ,100’s – 38 , 50’s – 52

in that order.

The following plots take a closer at their performances. The box plots show the mean (red line) and median (blue line). The two ends of the boxplot display the 25th and 75th percentile.

Box Histogram Plot

This plot shows a combined boxplot of the Runs ranges and a histogram of the Runs Frequency. The calculated Mean differ from the stated means possibly because of data cleaning. Also not sure how the means were arrived at ESPN Cricinfo for e.g. when considering not out..

batsmanPerfBoxHist("./tendulkar.csv","Sachin Tendulkar")

tkps-boxhist-1

batsmanPerfBoxHist("./kallis.csv","Jacques Kallis")

tkps-boxhist-2

batsmanPerfBoxHist("./ponting.csv","Ricky Ponting")

tkps-boxhist-3

batsmanPerfBoxHist("./sangakkara.csv","K Sangakkara")

tkps-boxhist-4

Contribution to won and lost matches

The plot below shows the contribution of Tendulkar, Kallis, Ponting and Sangakarra in matches won and lost. The plots show the range of runs scored as a boxplot (25th & 75th percentile) and the mean scored. The total matches won and lost are also printed in the plot.

All the players have scored more in the matches they won than the matches they lost. Ricky Ponting is the only batsman who seems to have more matches won to his credit than others. This could also be because he was a member of strong Australian team

For the next 2 functions below you will have to use the getPlayerDataSp() function. I
have commented this as I already have these files

tendulkarsp <- getPlayerDataSp(35320,tdir=".",tfile="tendulkarsp.csv",ttype="batting")
kallissp <- getPlayerDataSp(45789,tdir=".",tfile="kallissp.csv",ttype="batting")
pontingsp <- getPlayerDataSp(7133,tdir=".",tfile="pontingsp.csv",ttype="batting")
sangakkarasp <- getPlayerDataSp(50710,tdir=".",tfile="sangakkarasp.csv",ttype="batting")

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))
batsmanContributionWonLost("tendulkarsp.csv","Tendulkar")
batsmanContributionWonLost("kallissp.csv","Kallis")
batsmanContributionWonLost("pontingsp.csv","Ponting")
batsmanContributionWonLost("sangakkarasp.csv","Sangakarra")

tkps-wonlost-1

dev.off()
## null device 
##           1

Performance at home and overseas

From the plot below it can be seen
Tendulkar has more matches overseas than at home and his performance is consistent in all venues at home or abroad. Ponting has lesser innings than Tendulkar and has an equally good performance at home and overseas.Kallis and Sangakkara’s performance abroad is lower than the performance at home.

This function also requires the use of getPlayerDataSp() as shown above

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))
batsmanPerfHomeAway("tendulkarsp.csv","Tendulkar")
batsmanPerfHomeAway("kallissp.csv","Kallis")
batsmanPerfHomeAway("pontingsp.csv","Ponting")
batsmanPerfHomeAway("sangakkarasp.csv","Sangakarra")
dev.off()
tkps-homeaway-1
dev.off()
## null device 
##           1
 

Moving Average of runs in career

Take a look at the Moving Average across the career of the Top 4. Clearly . Kallis and Sangakkara have a few more years of great batting ahead. They seem to average on 50. . Tendulkar and Ponting definitely show a slump in the later years

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))
batsmanMovingAverage("./tendulkar.csv","Sachin Tendulkar")
batsmanMovingAverage("./kallis.csv","Jacques Kallis")
batsmanMovingAverage("./ponting.csv","Ricky Ponting")
batsmanMovingAverage("./sangakkara.csv","K Sangakkara")

tkps-ma-1

dev.off()
## null device 
##           1

Cumulative Average runs of batsman in career

This function provides the cumulative average runs of the batsman over the career. Tendulkar averages around 50, while Sangakkarra touches 55 towards the end of his career

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))
batsmanCumulativeAverageRuns("./tendulkar.csv","Tendulkar")

tkps-car-1

batsmanCumulativeAverageRuns("./kallis.csv","Kallis")

tkps-car-2

batsmanCumulativeAverageRuns("./ponting.csv","Ponting")

tkps-car-3

batsmanCumulativeAverageRuns("./sangakkara.csv","Sangakkara")

tkps-car-4

dev.off()
## null device 
##           1

Cumulative Average strike rate of batsman in career

This function gives the cumulative strike rate of the batsman over the career

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))
batsmanCumulativeStrikeRate("./tendulkar.csv","Tendulkar")

tkps-casr-1

batsmanCumulativeStrikeRate("./kallis.csv","Kallis")

tkps-casr-2

batsmanCumulativeStrikeRate("./ponting.csv","Ponting")

tkps-casr-3

batsmanCumulativeStrikeRate("./sangakkara.csv","Sangakkara")

tkps-casr-4

dev.off()
## null device 
##           1

Future Runs forecast

Here are plots that forecast how the batsman will perform in future. In this case 90% of the career runs trend is uses as the training set. the remaining 10% is the test set.

A Holt-Winters forecating model is used to forecast future performance based on the 90% training set. The forecated runs trend is plotted. The test set is also plotted to see how close the forecast and the actual matches

Take a look at the runs forecasted for the batsman below.

  • Tendulkar’s forecasted performance seems to tally with his actual performance with an average of 50
  • Kallis the forecasted runs are higher than the actual runs he scored
  • Ponting seems to have a good run in the future
  • Sangakkara has a decent run in the future averaging 50 runs
par(mfrow=c(2,2))
par(mar=c(4,4,2,2))
batsmanPerfForecast("./tendulkar.csv","Sachin Tendulkar")
batsmanPerfForecast("./kallis.csv","Jacques Kallis")
batsmanPerfForecast("./ponting.csv","Ricky Ponting")
batsmanPerfForecast("./sangakkara.csv","K Sangakkara")

tkps-perffcst-1

dev.off()
## null device 
##           1

Relative Mean Strike Rate plot

The plot below compares the Mean Strike Rate of the batsman for each of the runs ranges of 10 and plots them. The plot indicate the following Range 0 – 50 Runs – Ponting leads followed by Tendulkar Range 50 -100 Runs – Ponting followed by Sangakkara Range 100 – 150 – Ponting and then Tendulkar

frames <- list("./tendulkar.csv","./kallis.csv","ponting.csv","sangakkara.csv")
names <- list("Tendulkar","Kallis","Ponting","Sangakkara")
relativeBatsmanSR(frames,names)

tkps-relSR-1

Relative Runs Frequency plot

The plot below gives the relative Runs Frequency Percetages for each 10 run bucket. The plot below show

Sangakkara leads followed by Ponting

frames <- list("./tendulkar.csv","./kallis.csv","ponting.csv","sangakkara.csv")
names <- list("Tendulkar","Kallis","Ponting","Sangakkara")
relativeRunsFreqPerf(frames,names)

tkps-relRunFreq-1

Relative cumulative average runs in career

The plot below compares the relative cumulative runs of the batsmen over the career. While Tendulkar seems to lead over the others with a cumulative average of 50, we can see that Sangakkara goes over everybody else between 180-220th inning. It is likely that Sangakkarra may have overtaken Tendulkar if he had played more

frames <- list("./tendulkar.csv","./kallis.csv","ponting.csv","sangakkara.csv")
names <- list("Tendulkar","Kallis","Ponting","Sangakkara")
relativeBatsmanCumulativeAvgRuns(frames,names)

tkps-relcar-11

Relative cumulative average strike rate in career

As seen in earlier charts Ponting has the best overall strike rate, followed by Sangakkara and then Tendulkar

frames <- list("./tendulkar.csv","./kallis.csv","ponting.csv","sangakkara.csv")
names <- list("Tendulkar","Kallis","Ponting","Sangakkara")
relativeBatsmanCumulativeStrikeRate(frames,names)

tkps-relcsr-1

Check Batsman In-Form or Out-of-Form

The below computation uses Null Hypothesis testing and p-value to determine if the batsman is in-form or out-of-form. For this 90% of the career runs is chosen as the population and the mean computed. The last 10% is chosen to be the sample set and the sample Mean and the sample Standard Deviation are caculated.

The Null Hypothesis (H0) assumes that the batsman continues to stay in-form where the sample mean is within 95% confidence interval of population mean The Alternative (Ha) assumes that the batsman is out of form the sample mean is beyond the 95% confidence interval of the population mean.

A significance value of 0.05 is chosen and p-value us computed If p-value >= .05 – Batsman In-Form If p-value < 0.05 – Batsman Out-of-Form

Note Ideally the p-value should be done for a population that follows the Normal Distribution. But the runs population is usually left skewed. So some correction may be needed. I will revisit this later

This is done for the Top 4 batsman

checkBatsmanInForm("./tendulkar.csv","Sachin Tendulkar")
## *******************************************************************************************
## 
## Population size: 294  Mean of population: 50.48 
## Sample size: 33  Mean of sample: 32.42 SD of sample: 29.8 
## 
## Null hypothesis H0 : Sachin Tendulkar 's sample average is within 95% confidence interval 
##         of population average
## Alternative hypothesis Ha : Sachin Tendulkar 's sample average is below the 95% confidence
##         interval of population average
## 
## [1] "Sachin Tendulkar 's Form Status: Out-of-Form because the p value: 0.000713  is less than alpha=  0.05"
## *******************************************************************************************
checkBatsmanInForm("./kallis.csv","Jacques Kallis")
## *******************************************************************************************
## 
## Population size: 240  Mean of population: 47.5 
## Sample size: 27  Mean of sample: 47.11 SD of sample: 59.19 
## 
## Null hypothesis H0 : Jacques Kallis 's sample average is within 95% confidence interval 
##         of population average
## Alternative hypothesis Ha : Jacques Kallis 's sample average is below the 95% confidence
##         interval of population average
## 
## [1] "Jacques Kallis 's Form Status: In-Form because the p value: 0.48647  is greater than alpha=  0.05"
## *******************************************************************************************
checkBatsmanInForm("./ponting.csv","Ricky Ponting")
## *******************************************************************************************
## 
## Population size: 251  Mean of population: 47.5 
## Sample size: 28  Mean of sample: 36.25 SD of sample: 48.11 
## 
## Null hypothesis H0 : Ricky Ponting 's sample average is within 95% confidence interval 
##         of population average
## Alternative hypothesis Ha : Ricky Ponting 's sample average is below the 95% confidence
##         interval of population average
## 
## [1] "Ricky Ponting 's Form Status: In-Form because the p value: 0.113115  is greater than alpha=  0.05"
## *******************************************************************************************
checkBatsmanInForm("./sangakkara.csv","K Sangakkara")
## *******************************************************************************************
## 
## Population size: 193  Mean of population: 51.92 
## Sample size: 22  Mean of sample: 71.73 SD of sample: 82.87 
## 
## Null hypothesis H0 : K Sangakkara 's sample average is within 95% confidence interval 
##         of population average
## Alternative hypothesis Ha : K Sangakkara 's sample average is below the 95% confidence
##         interval of population average
## 
## [1] "K Sangakkara 's Form Status: In-Form because the p value: 0.862862  is greater than alpha=  0.05"
## *******************************************************************************************

3D plot of Runs vs Balls Faced and Minutes at Crease

The plot is a scatter plot of Runs vs Balls faced and Minutes at Crease. A prediction plane is fitted

par(mfrow=c(1,2))
par(mar=c(4,4,2,2))
battingPerf3d("./tendulkar.csv","Tendulkar")
battingPerf3d("./kallis.csv","Kallis")
plot-3-1par(mfrow=c(1,2))
par(mar=c(4,4,2,2))
battingPerf3d("./ponting.csv","Ponting")
battingPerf3d("./sangakkara.csv","Sangakkara")
plot-4-1dev.off()
## null device 
##           1

Predicting Runs given Balls Faced and Minutes at Crease

A multi-variate regression plane is fitted between Runs and Balls faced +Minutes at crease. A sample sequence of Balls Faced(BF) and Minutes at crease (Mins) is setup as shown below. The fitted model is used to predict the runs for these values

BF <- seq( 10, 400,length=15)
Mins <- seq(30,600,length=15)
newDF <- data.frame(BF,Mins)
tendulkar <- batsmanRunsPredict("./tendulkar.csv","Tendulkar",newdataframe=newDF)
kallis <- batsmanRunsPredict("./kallis.csv","Kallis",newdataframe=newDF)
ponting <- batsmanRunsPredict("./ponting.csv","Ponting",newdataframe=newDF)
sangakkara <- batsmanRunsPredict("./sangakkara.csv","Sangakkara",newdataframe=newDF)

The fitted model is then used to predict the runs that the batsmen will score for a given Balls faced and Minutes at crease. It can be seen Ponting has the will score the highest for a given Balls Faced and Minutes at crease.

Ponting is followed by Tendulkar who has Sangakkara close on his heels and finally we have Kallis. This is intuitive as we have already seen that Ponting has a highest strike rate.

batsmen <-cbind(round(tendulkar$Runs),round(kallis$Runs),round(ponting$Runs),round(sangakkara$Runs))
colnames(batsmen) <- c("Tendulkar","Kallis","Ponting","Sangakkara")
newDF <- data.frame(round(newDF$BF),round(newDF$Mins))
colnames(newDF) <- c("BallsFaced","MinsAtCrease")
predictedRuns <- cbind(newDF,batsmen)
predictedRuns
##    BallsFaced MinsAtCrease Tendulkar Kallis Ponting Sangakkara
## 1          10           30         7      6       9          2
## 2          38           71        23     20      25         18
## 3          66          111        39     34      42         34
## 4          94          152        54     48      59         50
## 5         121          193        70     62      76         66
## 6         149          234        86     76      93         82
## 7         177          274       102     90     110         98
## 8         205          315       118    104     127        114
## 9         233          356       134    118     144        130
## 10        261          396       150    132     161        146
## 11        289          437       165    146     178        162
## 12        316          478       181    159     194        178
## 13        344          519       197    173     211        194
## 14        372          559       213    187     228        210
## 15        400          600       229    201     245        226

Analysis of Top 3 wicket takers

The top 3 wicket takes in test history are
1. M Muralitharan:Wickets: 800, Average = 22.72, Economy Rate – 2.47
2. Shane Warne: Wickets: 708, Average = 25.41, Economy Rate – 2.65
3. Anil Kumble: Wickets: 619, Average = 29.65, Economy Rate – 2.69

How do Anil Kumble, Shane Warne and M Muralitharan compare with one another with respect to wickets taken and the Economy Rate. The next set of plots compute and plot precisely these analyses.

Wicket Frequency Plot

This plot below computes the percentage frequency of number of wickets taken for e.g 1 wicket x%, 2 wickets y% etc and plots them as a continuous line

par(mfrow=c(1,3))
par(mar=c(4,4,2,2))
bowlerWktsFreqPercent("./kumble.csv","Anil Kumble")
bowlerWktsFreqPercent("./warne.csv","Shane Warne")
bowlerWktsFreqPercent("./murali.csv","M Muralitharan")

relBowlFP-1

dev.off()
## null device 
##           1

Wickets Runs plot

par(mfrow=c(1,3))
par(mar=c(4,4,2,2))
bowlerWktsRunsPlot("./kumble.csv","Kumble")
bowlerWktsRunsPlot("./warne.csv","Warne")
bowlerWktsRunsPlot("./murali.csv","Muralitharan")
wktsrun-1
dev.off()
## null device 
##           1

Average wickets at different venues

The plot gives the average wickets taken by Muralitharan at different venues. Muralitharan has taken an average of 8 and 6 wickets at Oval & Wellington respectively in 2 different innings. His best performances are at Kandy and Colombo (SSC)

bowlerAvgWktsGround("./murali.csv","Muralitharan")
avgWktshrg-1

Average wickets against different opposition

The plot gives the average wickets taken by Muralitharan against different countries. The x-axis also includes the number of innings against each team

bowlerAvgWktsOpposition("./murali.csv","Muralitharan")
avgWktoppn-1

 

Wickets taken moving average

From th eplot below it can be see 1. Shane Warne’s performance at the time of his retirement was still at a peak of 3 wickets 2. M Muralitharan seems to have become ineffective over time with his peak years being 2004-2006 3. Anil Kumble also seems to slump down and become less effective.

par(mfrow=c(1,3))
par(mar=c(4,4,2,2))
bowlerMovingAverage("./kumble.csv","Anil Kumble")
bowlerMovingAverage("./warne.csv","Shane Warne")
bowlerMovingAverage("./murali.csv","M Muralitharan")

tkps-bowlma-1

dev.off()
## null device 
##           1

Cumulative average wickets taken

The plots below give the cumulative average wickets taken by the bowlers

par(mfrow=c(1,3))
par(mar=c(4,4,2,2))
bowlerCumulativeAvgWickets("./kumble.csv","Kumble")

kwm-bowlcaw-1

bowlerCumulativeAvgWickets("./warne.csv","Warne")

kwm-bowlcaw-2

bowlerCumulativeAvgWickets("./murali.csv","Muralitharan")

kwm-bowlcaw-3

dev.off()
## null device 
##           1

Cumulative average economy rate

The plots below give the cumulative average economy rate of the bowlers

par(mfrow=c(1,3))
par(mar=c(4,4,2,2))
bowlerCumulativeAvgEconRate("./kumble.csv","Kumble")

kwm-bowlcer-1

bowlerCumulativeAvgEconRate("./warne.csv","Warne")

kwm-bowlcer-2

bowlerCumulativeAvgEconRate("./murali.csv","Muralitharan")

kwm-bowlcer-3

dev.off()
## null device 
##           1

Future Wickets forecast

Here are plots that forecast how the bowler will perform in future. In this case 90% of the career wickets trend is used as the training set. the remaining 10% is the test set.

A Holt-Winters forecating model is used to forecast future performance based on the 90% training set. The forecated wickets trend is plotted. The test set is also plotted to see how close the forecast and the actual matches

Take a look at the wickets forecasted for the bowlers below. – Shane Warne and Muralitharan have a fairly consistent forecast – Kumble forecast shows a small dip

par(mfrow=c(1,3))
par(mar=c(4,4,2,2))
bowlerPerfForecast("./kumble.csv","Anil Kumble")
bowlerPerfForecast("./warne.csv","Shane Warne")
bowlerPerfForecast("./murali.csv","M Muralitharan")

kwm-perffcst-1

dev.off()
## null device 
##           1

Contribution to matches won and lost

The plot below is extremely interesting
1. Kumble wickets range from 2 to 4 wickets in matches wons with a mean of 3
2. Warne wickets in won matches range from 1 to 4 with more matches won. Clearly there are other bowlers contributing to the wins, possibly the pacers
3. Muralitharan wickets range in winning matches is more than the other 2 and ranges ranges 3 to 5 and clearly had a hand (pun unintended) in Sri Lanka’s wins

As discussed above the next 2 charts require the use of getPlayerDataSp()

kumblesp <- getPlayerDataSp(30176,tdir=".",tfile="kumblesp.csv",ttype="bowling")
warnesp <- getPlayerDataSp(8166,tdir=".",tfile="warnesp.csv",ttype="bowling")
muralisp <- getPlayerDataSp(49636,tdir=".",tfile="muralisp.csv",ttype="bowling")
par(mfrow=c(1,3))
par(mar=c(4,4,2,2))
bowlerContributionWonLost("kumblesp.csv","Kumble")
bowlerContributionWonLost("warnesp.csv","Warne")
bowlerContributionWonLost("muralisp.csv","Murali")

kwm-wl-1

dev.off()
## null device 
##           1

Performance home and overseas

From the plot below it can be seen that Kumble & Warne have played more matches overseas than Muralitharan. Both Kumble and Warne show an average of 2 wickers overseas,  Murali on the other hand has an average of 2.5 wickets overseas but a slightly less number of matches than Kumble & Warne

par(mfrow=c(1,3))
par(mar=c(4,4,2,2))
bowlerPerfHomeAway("kumblesp.csv","Kumble")
bowlerPerfHomeAway("warnesp.csv","Warne")
bowlerPerfHomeAway("muralisp.csv","Murali")

kwm-ha-1
dev.off()
## null device 
##           1
 

Relative Wickets Frequency Percentage

The Relative Wickets Percentage plot shows that M Muralitharan has a large percentage of wickets in the 3-8 wicket range

frames <- list("./kumble.csv","./murali.csv","warne.csv")
names <- list("Anil KUmble","M Muralitharan","Shane Warne")
relativeBowlingPerf(frames,names)

relBowlPerf-1

Relative Economy Rate against wickets taken

Clearly from the plot below it can be seen that Muralitharan has the best Economy Rate among the three

frames <- list("./kumble.csv","./murali.csv","warne.csv")
names <- list("Anil KUmble","M Muralitharan","Shane Warne")
relativeBowlingER(frames,names)

relBowlER-1

Relative cumulative average wickets of bowlers in career

The plot below shows that Murali has the best cumulative average wickets taken followed by Kumble and then Warne

frames <- list("./kumble.csv","./murali.csv","warne.csv")
names <- list("Anil KUmble","M Muralitharan","Shane Warne")
relativeBowlerCumulativeAvgWickets(frames,names)

rbcaw-1

Relative cumulative average economy rate of bowlers

Muralitharan has the best economy rate followed by Warne and then Kumble

frames <- list("./kumble.csv","./murali.csv","warne.csv")
names <- list("Anil KUmble","M Muralitharan","Shane Warne")
relativeBowlerCumulativeAvgEconRate(frames,names)

rbcer-1

Check for bowler in-form/out-of-form

The below computation uses Null Hypothesis testing and p-value to determine if the bowler is in-form or out-of-form. For this 90% of the career wickets is chosen as the population and the mean computed. The last 10% is chosen to be the sample set and the sample Mean and the sample Standard Deviation are caculated.

The Null Hypothesis (H0) assumes that the bowler continues to stay in-form where the sample mean is within 95% confidence interval of population mean The Alternative (Ha) assumes that the bowler is out of form the sample mean is beyond the 95% confidence interval of the population mean.

A significance value of 0.05 is chosen and p-value us computed If p-value >= .05 – Batsman In-Form If p-value < 0.05 – Batsman Out-of-Form

Note Ideally the p-value should be done for a population that follows the Normal Distribution. But the runs population is usually left skewed. So some correction may be needed. I will revisit this later

Note: The check for the form status of the bowlers indicate 1. That both Kumble and Muralitharan were out of form. This also shows in the moving average plot 2. Warne is still in great form and could have continued for a few more years. Too bad we didn’t see the magic later

checkBowlerInForm("./kumble.csv","Anil Kumble")
## *******************************************************************************************
## 
## Population size: 212  Mean of population: 2.69 
## Sample size: 24  Mean of sample: 2.04 SD of sample: 1.55 
## 
## Null hypothesis H0 : Anil Kumble 's sample average is within 95% confidence interval 
##         of population average
## Alternative hypothesis Ha : Anil Kumble 's sample average is below the 95% confidence
##         interval of population average
## 
## [1] "Anil Kumble 's Form Status: Out-of-Form because the p value: 0.02549  is less than alpha=  0.05"
## *******************************************************************************************
checkBowlerInForm("./warne.csv","Shane Warne")
## *******************************************************************************************
## 
## Population size: 240  Mean of population: 2.55 
## Sample size: 27  Mean of sample: 2.56 SD of sample: 1.8 
## 
## Null hypothesis H0 : Shane Warne 's sample average is within 95% confidence interval 
##         of population average
## Alternative hypothesis Ha : Shane Warne 's sample average is below the 95% confidence
##         interval of population average
## 
## [1] "Shane Warne 's Form Status: In-Form because the p value: 0.511409  is greater than alpha=  0.05"
## *******************************************************************************************
checkBowlerInForm("./murali.csv","M Muralitharan")
## *******************************************************************************************
## 
## Population size: 207  Mean of population: 3.55 
## Sample size: 23  Mean of sample: 2.87 SD of sample: 1.74 
## 
## Null hypothesis H0 : M Muralitharan 's sample average is within 95% confidence interval 
##         of population average
## Alternative hypothesis Ha : M Muralitharan 's sample average is below the 95% confidence
##         interval of population average
## 
## [1] "M Muralitharan 's Form Status: Out-of-Form because the p value: 0.036828  is less than alpha=  0.05"
## *******************************************************************************************
dev.off()
## null device 
##           1

Key Findings

The plots above capture some of the capabilities and features of my cricketr package. Feel free to install the package and try it out. Please do keep in mind ESPN Cricinfo’s Terms of Use.
Here are the main findings from the analysis above

Analysis of Top 4 batsman

The analysis of the Top 4 test batsman Tendulkar, Kallis, Ponting and Sangakkara show the folliwing

  1. Sangakkara has the highest average, followed by Tendulkar, Kallis and then Ponting.
  2. Ponting has the highest strike rate followed by Tendulkar,Sangakkara and then Kallis
  3. The predicted runs for a given Balls faced and Minutes at crease is highest for Ponting, followed by Tendulkar, Sangakkara and Kallis
  4. The moving average for Tendulkar and Ponting shows a downward trend while Kallis and Sangakkara retired too soon
  5. Tendulkar was out of form about the time of retirement while the rest were in-form. But this result has to be taken along with the moving average plot. Ponting was clearly on the way out.
  6. The home and overseas performance indicate that Tendulkar is the clear leader. He has the highest number of matches played overseas and his performance has been consistent. He is followed by Ponting, Kallis and finally Sangakkara

Analysis of Top 3 legs spinners

The analysis of Anil Kumble, Shane Warne and M Muralitharan show the following

  1. Muralitharan has the highest wickets and best economy rate followed by Warne and Kumble
  2. Muralitharan has higher wickets frequency percentage between 3 to 8 wickets
  3. Muralitharan has the best Economy Rate for wickets between 2 to 7
  4. The moving average plot shows that the time was up for Kumble and Muralitharan but Warne had a few years ahead
  5. The check for form status shows that Muralitharan and Kumble time was over while Warne still in great form
  6. Kumble’s has more matches abroad than the other 2, yet Kumble averages of 3 wickets at home and 2 wickets overseas liek Warne . Murali has played few matches but has an average of 4 wickets at home and 3 wickets overseas.

Final thoughts

Here are my final thoughts

Batting

Among the 4 batsman Tendulkar, Kallis, Ponting and Sangakkara the clear leader is Tendulkar for the following reasons

  1. Tendulkar has the highest test centuries and runs of all time.Tendulkar’s average is 2nd to Sangakkara, Tendulkar’s predicted runs for a given Balls faced and Minutes at Crease is 2nd and is behind Ponting. Also Tendulkar’s performance at home and overseas are consistent throughtout despite the fact that he has a highest number of overseas matches
  2. Ponting takes the 2nd spot with the 2nd highest number of centuries, 1st in Strike Rate and 2nd in home and away performance.
  3. The 3rd spot goes to Sangakkara, with the highest average, 3rd highest number of centuries, reasonable run frequency percentage in different run ranges. However he has a fewer number of matches overseas and his performance overseas is significantly lower than at home
  4. Kallis has the 2nd highest number of centuries but his performance overseas and strike rate are behind others
  5. Finally Kallis and Sangakkara had a few good years of batting still left in them (pity they retired!) while Tendulkar and Ponting’s time was up
  6. While Tendulkars cumulative average stays around 50 runs, Sangakkara briefly overtakes Tendulkar towards the end of his career. Sangakkara may have finished with a better average if he had played for a few more years
  7. Ponting has the best overall strike rate followed by Sangakkara

Bowling

Muralitharan leads the way followed closely by Warne and finally Kumble. The reasons are

  1. Muralitharan has the highest number of test wickets with the best Wickets percentage and the best Economy Rate. Murali on average gas taken 4 wickets at home and 3 wickets overseas
  2. Warne follows Murali in the highest wickets taken, however Warne has less matches overseas than Murali and average 3 wickets home and 2 wickets overseas
  3. Kumble has the 3rd highest wickets, with 3 wickets on an average at home and 2 wickets overseas. However Kumble has played more matches overseas than the other two. In that respect his performance is great. Also Kumble has played less matches at home otherwise his numbers would have looked even better.
  4. Also while Kumble and Muralitharan’s career was on the decline , Warne was going great and had a couple of years ahead.
  5. Muralitharan has the best cumulative wicket rate and economy rate. Kumble has a better wicket rate than Warne but is more expensive than Warne

You can download this analysis at Introducing cricketrYou can download this analysis at Re-Introducing cricketr

Also see

1.Introducing cricket package yorkr-Part1:Beaten by sheer pace!.
2.yorkr pads up for the Twenty20s: Part 1- Analyzing team“s match performance.
3.yorkr crashes the IPL party !Part 1
4.Introducing cricketr! : An R package to analyze performances of cricketers
5.Beaten by sheer pace! Cricket analytics with yorkr in paperback and Kindle versions
6. Cricket analytics with cricketr in paperback and Kindle versions

You may also like
1. A crime map of India in R: Crimes against women
2.  What’s up Watson? Using IBM Watson’s QAAPI with Bluemix, NodeExpress – Part 1
3.  Bend it like Bluemix, MongoDB with autoscaling – Part 2
4. Informed choices through Machine Learning : Analyzing Kohli, Tendulkar and Dravid
5. Thinking Web Scale (TWS-3): Map-Reduce – Bring compute to data
6. Deblurring with OpenCV:Weiner filter reloaded
7. Fun simulation of a Chain in Androidhttp://www.r-bloggers.com/introducing-cricketr-an-r-package-to-analyze-performances-of-cricketers/

Beaten by sheer pace! Cricket analytics with yorkr in paperback and Kindle versions


Untitled

My book “Beaten by sheer pace! Cricket analytics with yorkr” is now available in paperback and Kindle versions. The paperback is available from Amazon (US, UK and Europe) for $ 54.95. The Kindle version can be downloaded from the Kindle store for $4.99 (Rs 332/-). Do pick up your copy. It should be a good read for a Sunday afternoon.

This book of mine contains my posts based on my R package ‘yorkr’ now in CRAN. The package yorkr uses the data from Cricsheet (http://cricsheet.org/) and can perform analysis of ODI and T20 matches. yorkr can analyze teams against a specific opposition or all oppositions, besides providing details on batsmen or bowlers individual performances The analyses include team batting partnerships, performances of batsmen against bowlers, bowlers against batsmen, bowlers best performances etc.  Individual analyses of batsmen strike rate, cumulative average, bowler economy rate, bowler moving average etc can be performances

The book includes the following chapters based on my R package yorkr.

CONTENTS
Preface
Foreword
1.Introducing cricket package yorkr: Part 1- Beaten by sheer pace!
2.Introducing cricket package yorkr: Part 2-Trapped leg before wicket!
3.Introducing cricket package yorkr: Part 3-Foxed by flight!
4.Introducing cricket package yorkr:Part 4-In the block hole!
5.yorkr pads up for the Twenty20s: Part 1- Analyzing team’s match performance!
6.yorkr pads up for the Twenty20s: Part 2-Head to head confrontation between teams
7.yorkr pads up for the Twenty20s:Part 3:Overall team performance against all oppositions!
8.yorkr pads up for Twenty20s:Part 4- Individual batting and bowling performances!
9.yorkr crashes the IPL party ! – Part 1
10.yorkr crashes the IPL party! – Part 2
11.yorkr crashes the IPL party! – Part 3!
12.yorkr crashes the IPL party! – Part 4
13.yorkr ranks IPL batsmen and bowlers
14.yorkr ranks T20 batsmen and bowlers
15.yorkr ranks ODI batsmen and bowlers
16.yorkr is generic!
Important links
Afterword
Other books by author
About the author

Beaten by sheer pace – Cricket analytics with yorkr


coverMy ebook “Beaten by sheer pace – Cricket analytics with yorkr’  has been published in Leanpub.  You can now download the book (hot off the press!)  for all formats to your favorite device (mobile, iPad, tablet, Kindle)  from the Leanpub  “Beaten by sheer pace!”. The book has been published in the following formats namely

  • PDF (for your computer)
  • EPUB (for iPad or tablets. Save the file cricketAnalyticsWithYorkr.epub to Google Drive/Dropbox and choose “Open in” iBooks for iPad)
  • MOBI (for Kindle. For this format, I suggest that you download & install SendToKindle for PC/Mac. You can then right click the downloaded cricketAnalyticsWithYorkr.mobi and choose SendToKindle. You will need to login to your Kindle account)

From Leanpub
UntitledLeanpub uses a variable pricing model. I have priced the book attractively (I think!). You can choose a price between FREE to $4.99 . The link is “Beaten by sheer pace!

 

This format works with all type Kindle device, Kindle app, Android tablet, iPad.

yorkr is generic!


The features and functionality in my yorkr package is now complete. My R package yorkr, is totally generic, which means that the R package  can be used for all ODI, T20 matches. Hence yorkr can be used for professional or amateur ODI and T20 matches. The R package can be used for both men and women ODI, T20 international or domestic matches. The main requirement is, that the match data  be created as a Yaml file in the format Cricsheet (Required yaml format for the match data).

I have successfully used my R functions for the Indian Premier League (IPL) matches with changes only to the convertAllYamlFiles2RDataFramesXX (please see posts below)

The convertAllYamlFiles2RDataframes &convertAllYamlFiles2RDataFramesT20 will have to be customized for the names of the teams playing in the domestic professional or amateur matches. All other classes of functions namely Class1, Class2, Class 3 and Class 4 as discussed in my post Introducing cricket package yorkr-Part 1: Beaten by sheer pace can be used as is without any changes.

There are numerous professional & amateur T20 matches that are played around the world. Here are a list of domestic T20 tournaments that are played around the world (from Wikipedia). The yorkr package can be used for any of these matches once the match data is saved as yaml as mentioned above.

So do go ahead and have fun, analyzing cricket performances with yorkr!

Take a look at my book with all my articles related to yorkr now available at Amazon in paperback and Kindle formats  Beaten by sheer pace! Cricket analytics with yorkr. The book is also available at Leanpub, which has a variable pricing Beaten by sheer pace! Cricket analytics with yorkr.

Please take a look at my posts on how to use yorkr for ODI, Twenty20 matches.

  1. Introducing cricket package yorkr:Part 1- Beaten by sheer pace!
    2. Introducing cricket package yorkr:Part 2- Trapped leg before wicket!
    3.  Introducing cricket package yorkr:Part 3- foxed by flight!
    4. Introducing cricket package yorkr:Part 4-In the block hole!
    5. yorkr pads up for the Twenty20s: Part 1- Analyzing team”s match performance
    6. yorkr pads up for the Twenty20s: Part 2-Head to head confrontation between teams
    7. yorkr pads up for the Twenty20s:Part 3:Overall team performance against all oppositions!
    8. yorkr pads up for Twenty20s:Part 4- Individual batting and bowling performances!
    9. yorkr crashes the IPL party ! – Part 1
    10. yorkr crashes the IPL party! – Part 2
    11. yorkr crashes the IPL party! – Part 3
    12. yorkr crashes the IPL party! – Part 4
    13. yorkr ranks IPL batsmen and bowlers
    14. yorkr ranks T20 batsmen and bowlers
    15. yorkr ranks ODI batsmen and bowlers

yorkr ranks ODI batsmen and bowlers


This is the last and final post in which yorkr ranks ODI batsmen and bowlers. These are based on match data from Cricsheet. The ranking is done on

  1. average runs and average strike rate for batsmen and
  2. average wickets and average economy rate for bowlers.

This post has also been published in RPubs RankODIPlayers. You can download this as a pdf file at RankODIPlayers.pdf.

Take a look at my book with all my articles related to yorkr now available at Amazon in paperback and Kindle formats  Beaten by sheer pace! Cricket analytics with yorkr. The book is also available at Leanpub, which has a variable pricing Beaten by sheer pace! Cricket analytics with yorkr.

You can take a look at the code at rankODIPlayers (available in yorkr_0.0.5)

rm(list=ls())
library(yorkr)
library(dplyr)
source("rankODIBatsmen.R")
source("rankODIBowlers.R")

Rank ODI batsmen

The top 3 ODI batsmen are hashim Amla (SA), Matther Hayden(Aus) & Virat Kohli (Ind) . Note: For ODI a a cutoff of at least 50 matches played was chosen.

ODIBatsmanRank <- rankODIBatsmen()
as.data.frame(ODIBatsmanRank[1:30,])
##            batsman matches meanRuns    meanSR
## 1          HM Amla     185 51.96216  84.15508
## 2        ML Hayden      79 50.08861  81.20646
## 3          V Kohli     279 48.51971  78.55197
## 4   AB de Villiers     253 47.93676  95.05561
## 5     SR Tendulkar     151 45.82119  79.62311
## 6         S Dhawan     116 45.03448  81.54043
## 7         V Sehwag     167 44.49102 106.27563
## 8          JE Root     111 43.64865  81.66054
## 9        Q de Kock      85 43.61176  82.55235
## 10       IJL Trott     113 43.36283  70.69761
## 11   KC Sangakkara     293 42.81911  75.10420
## 12      TM Dilshan     283 41.76678  89.70360
## 13   KS Williamson     146 41.24658  73.49267
## 14   S Chanderpaul      93 40.07527  70.59613
## 15        HH Gibbs      75 40.00000  79.03813
## 16     Salman Butt      57 39.85965  59.29807
## 17    Anamul Haque      58 39.72414  56.45224
## 18      RT Ponting     238 38.88235  71.94294
## 19       JH Kallis     136 38.77941  67.17794
## 20        MS Dhoni     328 38.57927  90.30555
## 21      MJ Guptill     199 38.54774  73.88090
## 22       DA Warner     138 38.52174  87.24978
## 23 Mohammad Yousuf      94 38.44681  72.69851
## 24        JD Ryder      66 38.40909  91.29667
## 25       GJ Bailey     133 38.38346  75.74519
## 26       G Gambhir     209 37.83254  75.15483
## 27      AJ Strauss     122 37.80328  71.54844
## 28       MJ Clarke     301 37.67442  69.78415
## 29       SR Watson     274 37.08029  83.46489
## 30        AJ Finch     103 36.36893  79.49845

Rank ODI bowlers

The top 3 ODI bowlers are R J Harris (Aus), MJ Henry(NZ) and MA Starc(Aus). Mohammed Shami is 4th and Amit Mishra is 8th A cutoff of 20 matches was considered for bowlers

ODIBowlersRank <- rankODIBowlers()
## [1] 35072     3
## [1] "C:/software/cricket-package/york-test/yorkrData/ODI/ODI-matches"
as.data.frame(ODIBowlersRank[1:30,])
##               bowler matches meanWickets   meanER
## 1  Mustafizur Rahman      56    4.000000 4.293214
## 2           JH Davey      53    3.528302 4.455094
## 3          RJ Harris      94    3.276596 4.361489
## 4           MA Starc     208    3.144231 4.425865
## 5           MJ Henry      88    3.125000 4.961250
## 6         A Flintoff     139    2.956835 4.283022
## 7           A Mishra     106    2.886792 4.365849
## 8     Mohammed Shami     144    2.777778 5.609306
## 9     MJ McClenaghan     165    2.751515 5.640424
## 10          CJ McKay     230    2.704348       NA
## 11       MF Maharoof     114    2.701754 4.427018
## 12       Imran Tahir     156    2.660256 4.461923
## 13        BAW Mendis     234    2.641026 4.532308
## 14     RK Kleinveldt      54    2.629630 4.306667
## 15      Arafat Sunny      62    2.612903 4.103226
## 16         JE Taylor     156    2.602564 5.115192
## 17           AJ Hall      55    2.600000 3.879091
## 18        WD Parnell     129    2.596899 5.477597
## 19         CR Woakes     129    2.596899 5.340620
## 20      DE Bollinger     152    2.592105 4.282763
## 21        Wahab Riaz     206    2.567961 5.431748
## 22        PJ Cummins     148    2.567568 5.715405
## 23         R Rampaul     173    2.549133 4.726590
## 24      Taskin Ahmed      56    2.535714 5.325357
## 25          DW Steyn     292    2.534247 4.534007
## 26      JR Hazlewood      64    2.531250 4.392500
## 27        Abdur Rauf      84    2.523810 4.786667
## 28           SW Tait     141    2.517730 5.173191
## 29      Hamid Hassan     106    2.509434 4.686038
## 30        SL Malinga     419    2.498807 4.968974

Hope you have fun with my yorkr package.!

yorkr ranks T20 batsmen and bowlers


Here is another short post which ranks T20 batsmen and bowlers. These are based on match data from Cricsheet. The ranking is done on

  1. average runs and average strike rate for batsmen and
  2. average wickets and average economy rate for bowlers.

This post has also been published in RPubs RankT20Players. You can download this as a pdf file at RankT20Players.pdf.

Take a look at my book with all my articles related to yorkr now available at Amazon in paperback and Kindle formats  Beaten by sheer pace! Cricket analytics with yorkr. The book is also available at Leanpub, which has a variable pricing Beaten by sheer pace! Cricket analytics with yorkr.

You can take a look at the code at rankT20Players (available in yorkr_0.0.5)

rm(list=ls())
library(yorkr)
library(dplyr)
source("rankT20Batsmen.R")
source("rankT20Bowlers.R")

Rank T20 batsmen

Virat Kohli (Ind), Chris Gayle (WI) and Kevin Pietersen (Eng) top the T20 rankings. Virat Kohli stands tall among the batsmen with a average of 39.1935, followed by Chris Gayle who has an average of 32.69 and finally Kevin Pietersen.

Note: For T20 a cutoff of at least 30 matches played was chosen.

T20BatsmanRank <- rankT20Batsmen()
as.data.frame(T20BatsmanRank[1:30,])
##             batsman matches meanRuns   meanSR
## 1           V Kohli      31 39.19355 128.8371
## 2          CH Gayle      43 32.69767 119.6467
## 3      KP Pietersen      37 32.43243 138.6732
## 4     KS Williamson      31 32.25806 130.1255
## 5  Mohammad Shahzad      33 31.66667 115.4582
## 6       BB McCullum      69 30.98551 126.0610
## 7        MJ Guptill      54 30.83333 120.0669
## 8          AD Hales      37 30.75676 115.3511
## 9       H Masakadza      38 29.26316 109.6182
## 10         GC Smith      32 27.59375 114.1831
## 11        DA Warner      56 27.53571 123.2209
## 12        JP Duminy      58 26.84483 117.3952
## 13 DPMD Jayawardene      51 26.47059 112.4257
## 14        SR Watson      50 26.30000 118.9464
## 15    KC Sangakkara      52 26.23077 112.4665
## 16       TM Dilshan      66 26.18182 102.5683
## 17         SK Raina      43 25.90698 124.3044
## 18        RG Sharma      41 25.68293 123.3983
## 19        G Gambhir      36 25.66667 117.5764
## 20     Yuvraj Singh      41 25.12195 119.5846
## 21    Misbah-ul-Haq      32 25.09375 106.6762
## 22       EJG Morgan      52 24.71154 121.1462
## 23       MN Samuels      40 24.35000 105.8547
## 24       MEK Hussey      30 24.03333 129.1250
## 25    Ahmed Shehzad      41 23.82927 100.8805
## 26  Shakib Al Hasan      40 23.35000 109.3798
## 27          HM Amla      30 23.33333 111.2513
## 28         CL White      45 22.73333       NA
## 29      LMP Simmons      33 22.54545       NA
## 30       Umar Akmal      69 22.20290 108.3590

Rank T20 bowlers

 

The top 3 T20 bowlers are BAW Mendis (SL) Umar Gul (Pak) and Steyn(SA). R Ashwin is 13th. As with batsmen, a minimum of 30 matches played was taken into consideration.

T20BowlersRank <- rankT20Bowlers()
as.data.frame(T20BowlersRank[1:30,])
##             bowler matches meanWickets   meanER
## 1       BAW Mendis      36   1.6944444 6.581111
## 2         Umar Gul      57   1.5964912 7.306842
## 3         DW Steyn      38   1.5526316 6.407632
## 4      Saeed Ajmal      63   1.4920635 6.316190
## 5       SL Malinga      59   1.4576271 7.163898
## 6       TG Southee      37   1.4054054 8.840000
## 7       MG Johnson      30   1.4000000 7.080667
## 8         GP Swann      38   1.3947368 6.576842
## 9      JW Dernbach      33   1.3636364 8.550303
## 10        M Morkel      39   1.3333333 7.384872
## 11 Shakib Al Hasan      37   1.2972973 6.648649
## 12       SP Narine      32   1.2500000 5.757812
## 13        R Ashwin      33   1.2424242 7.247273
## 14 KMDN Kulasekara      42   1.2380952 6.938095
## 15       SCJ Broad      55   1.2363636 7.832182
## 16      WD Parnell      34   1.2058824 8.227941
## 17        KD Mills      41   1.1951220 8.077317
## 18      DL Vettori      34   1.1470588 5.708235
## 19   Shahid Afridi      85   1.1294118 6.748000
## 20       SR Watson      44   1.1136364 8.015227
## 21   Sohail Tanvir      48   1.1041667 7.354167
## 22   Sohail Tanvir      48   1.1041667 7.354167
## 23     NL McCullum      56   1.0535714 7.246964
## 24     NLTC Perera      34   1.0294118 8.916471
## 25         J Botha      39   1.0256410 6.647436
## 26        DJ Bravo      45   1.0222222 8.630000
## 27   Mohammad Nabi      32   0.9687500 7.208437
## 28       DJG Sammy      55   0.8909091 7.899818
## 29 Mohammad Hafeez      56   0.8392857 6.996964
## 30      AD Mathews      44   0.7954545 6.827727

Conclusion

Conclusion

As expected Virat Kohli stands head and shoulders above the rest. Hamid Hasan and Mohammed Shami figuring the top T20 bowlers was a bit of a surprise to me.

Watch this space!

  1. Introducing cricket package yorkr-Part1:Beaten by sheer pace!.
  2. yorkr pads up for the Twenty20s: Part 1- Analyzing team“s match performance.
  3. yorkr crashes the IPL party !Part 1
  4. Introducing cricketr! : An R package to analyze performances of cricketers
  5. Cricket analytics with cricketr in paperback and Kindle versions

yorkr ranks IPL batsmen and bowlers


Here is a short post which ranks IPL batsmen and bowlers. These are based on match data from Cricsheet. Ranking batsmen and bowlers in IPL is more challenging as the players can belong to different teams in different years. Hence I create a combined data frame of the batsmen and bowlers regardless of their IPL teams and calculate a) average runs and average strike rate for batsmen and c) average wickets and d) average economy rate for bowlers.

I will be doing this ranking for T20 and ODI batting and bowling performances shortly.

This post has also been published in RPubs RankIPLPlayers. You can download this as a pdf file at RankIPLPlayers.pdf.

You can take a look at the code at rankIPLPlayers (should be available in yorkr_0.0.5)

Take a look at my book with all my articles related to yorkr now available at Amazon in paperback and Kindle formats  Beaten by sheer pace! Cricket analytics with yorkr. The book is also available at Leanpub, which has a variable pricing Beaten by sheer pace! Cricket analytics with yorkr.

The results are slightly surprising

rm(list=ls())
library(yorkr)
library(dplyr)
setwd("C:/software/cricket-package/cricsheet/cleanup/IPL/rank")
source("rankIPLBatsmen.R")
source("rankIPLBowlers.R")

Rank IPL batsmen

Chris Gayle, MEK Hussey and Shane Watson are top 3 IPL batsmen. Gayle towers over the others in mean runs and mean strike rate. Surprisingly Ajinkya Rahane is the top Indian T20 batsman, if we leave out Sachin Tendulkar (who tops India yet again!). The other top IPL T20 batsmen are Raina, Gambhir, Rohit Sharma in that order. Virat Kohli comes a distant 14th.

iplBatsmanRank <- rankIPLBatsmen()
as.data.frame(iplBatsmanRank[1:30,])
##             batsman matches meanRuns    meanSR
## 1          CH Gayle     128 40.00781 144.92188
## 2        MEK Hussey      64 33.57812 107.23500
## 3         SR Watson      75 31.46667 129.97733
## 4      SR Tendulkar     127 29.74803 108.86622
## 5         AM Rahane      77 29.14286 101.40065
## 6         DA Warner     134 29.10448 118.38313
## 7         JP Duminy      94 28.77660 124.61702
## 8          SK Raina     128 28.62500 122.12656
## 9         G Gambhir     210 28.13810 108.78090
## 10        RG Sharma     181 28.07182 118.57801
## 11         DR Smith      78 27.82051 119.64462
## 12      BB McCullum      98 27.81633 114.91255
## 13         S Dhawan     109 27.74312 112.21000
## 14          V Kohli     188 27.56915 113.81261
## 15   AB de Villiers     150 27.46000 136.70860
## 16         R Dravid     104 27.02885 107.78923
## 17        JH Kallis     167 26.54491  94.65641
## 18         V Sehwag     174 26.39655 140.29011
## 19       RV Uthappa     166 26.27711 120.48506
## 20       SC Ganguly      86 25.98837  96.39849
## 21     AC Gilchrist      81 25.77778 122.69074
## 22    KC Sangakkara      70 25.67143 112.97529
## 23         MS Dhoni     119 25.29412 130.99832
## 24       TM Dilshan      82 24.13415 101.12634
## 25          M Vijay      96 23.92708 102.01771
## 26        AT Rayudu     146 23.63014 117.91000
## 27 DPMD Jayawardene     109 22.95413 110.73862
## 28        MK Pandey     105 22.71429        NA
## 29     Yuvraj Singh     112 22.48214 114.51018
## 30      S Badrinath      66 22.22727 114.97061

Rank IPL bowlers

The top 3 IPL T20 bowlers are SL Malinga,SP Narine and DJ Bravo.

Don’t get hung up on the decimals in the average wickets for the bowlers. All it implies is that if 2 bowlers have average wickets of 1.0 and 1.5, it implies that in 2 matches the 1st bowler will take 2 wickets and the 2nd bowler will take 3 wickets.

iplBowlersRank <- rankIPLBowlers()
as.data.frame(iplBowlersRank[1:30,])
##             bowler matches meanWickets   meanER
## 1       SL Malinga      96    1.645833 6.545208
## 2        SP Narine      54    1.555556 5.967593
## 3         DJ Bravo      58    1.517241 7.929310
## 4         M Morkel      37    1.405405 7.626216
## 5        IK Pathan      40    1.400000 7.579250
## 6         RP Singh      42    1.357143 7.966429
## 7         MM Patel      31    1.354839 7.282581
## 8  Shakib Al Hasan      32    1.343750 6.911250
## 9    R Vinay Kumar      63    1.317460 8.342540
## 10       MM Sharma      46    1.304348 7.740652
## 11         P Awana      33    1.303030 8.325758
## 12        MM Patel      30    1.300000 7.569667
## 13          Z Khan      41    1.292683 7.735854
## 14        A Mishra      43    1.255814 7.226512
## 15         PP Ojha      53    1.245283 7.268679
## 16     JP Faulkner      40    1.225000 8.502250
## 17     DS Kulkarni      32    1.156250 8.372188
## 18        UT Yadav      46    1.152174 8.394783
## 19        A Kumble      41    1.146341 6.567073
## 20       JA Morkel      73    1.136986 8.131370
## 21        SK Warne      53    1.132075 7.277170
## 22 Harbhajan Singh     107    1.102804 7.014953
## 23        L Balaji      34    1.088235 7.186176
## 24        R Ashwin      92    1.065217 6.812391
## 25        AR Patel      31    1.064516 7.137097
## 26  M Muralitharan      39    1.051282 6.470256
## 27         P Kumar      36    1.027778 8.148056
## 28       PP Chawla      85    1.023529 8.017765
## 29       SR Watson      67    1.014925 7.695224
## 30        DJ Bravo      30    1.000000 7.966333

Conclusion: The results are somewhat surprising. The ranking was based on data from Cricsheet. The data in this site are available from 2008-2015. I hope to do this ranking for T20 and ODIs shortly

Watch this space!

  1. Introducing cricket package yorkr-Part1:Beaten by sheer pace!.
  2. yorkr pads up for the Twenty20s: Part 1- Analyzing team“s match performance.
  3. yorkr crashes the IPL party !Part 1
  4. Introducing cricketr! : An R package to analyze performances of cricketers
  5. Cricket analytics with cricketr in paperback and Kindle versions

yorkr crashes the IPL party! – Part 4


Introduction

I’ve missed more than 9000 shots in my career. I’ve lost almost 300 games. 26 times, I’ve been trusted to take the game winning shot and missed. I’ve failed over and over and over again in my life. And that is why I succeed.

                      Michael Jordan

Success is where preparation and opportunity meet.

                      Bobby Unser

It is not whether you get knocked down. It is whether you get up.

                      Vince Lombardi

Make sure your worst enemy doesn’t live between your own two ears.

                      Laird Hamilton

This post should be the last post for “yorkr crashes the IPL party!”. In fact it is final post for the whole ‘yorkr’ series. I have now covered the use of yorkr for ODIs, Twenty20s and IPL T20 formats. I will not be including functionality in yorkr to handle Test cricket from Cricsheet. I would recommend that you use my R package cricketr. Please see my post Introducing cricketr! : An R package to analyze performances of cricketers

In this last post on IPL T20 I look at the top individual batting and bowling performances in the IPL Twenty20s. Also please take a look at my 3 earlier post on yorkr’s handling of IPL Twenty20 matches

  1. yorkr crashes the IPL party ! – Part 1
  2. yorkr crashes the IPL party ! – Part 2
  3. yorkr crashes the IPL party ! – Part 3

This post has also been published at RPubs IPLT20-Part4 and can also be downloaded as a PDF document from IPLT20-Part4.pdf.

You can clone/fork the code for the package yorkr from Github at yorkr-package

Take a look at my book with all my articles related to yorkr now available at Amazon in paperback and Kindle formats  Beaten by sheer pace! Cricket analytics with yorkr. The book is also available at Leanpub, which has a variable pricing Beaten by sheer pace! Cricket analytics with yorkr.

The list of Class 4 functions are shown below.The Twenty20 features will be available from yorkr_0.0.4

Batsman functions

  1. batsmanRunsVsDeliveries
  2. batsmanFoursSixes
  3. batsmanDismissals
  4. batsmanRunsVsStrikeRate
  5. batsmanMovingAverage
  6. batsmanCumulativeAverageRuns
  7. batsmanCumulativeStrikeRate
  8. batsmanRunsAgainstOpposition
  9. batsmanRunsVenue
  10. batsmanRunsPredict

Bowler functions

  1. bowlerMeanEconomyRate
  2. bowlerMeanRunsConceded
  3. bowlerMovingAverage
  4. bowlerCumulativeAvgWickets
  5. bowlerCumulativeAvgEconRate
  6. bowlerWicketPlot
  7. bowlerWicketsAgainstOpposition
  8. bowlerWicketsVenue
  9. bowlerWktsPredict
library(yorkr)
library(gridExtra)
library(rpart.plot)
library(dplyr)
library(ggplot2)
rm(list=ls())

A. Batsman functions

1. Get IPL Team Batting details

The function below gets the overall IPL team batting details based on the RData file available in IPL T20 matches. This is currently also available in Github at [IPL-T20-matches] (https://github.com/tvganesh/yorkrData/tree/master/IPL/IPL-T20-matches). The batting details of the IPL team in each match is created and a huge data frame is created by rbinding the individual dataframes. This can be saved as a RData file

setwd("C:/software/cricket-package/york-test/yorkrData/IPL/IPL-T20-matches")
csk_details <- getTeamBattingDetails("Chennai Super Kings",dir=".", save=TRUE)
dd_details <- getTeamBattingDetails("Delhi Daredevils",dir=".",save=TRUE)
kkr_details <- getTeamBattingDetails("Kolkata Knight Riders",dir=".",save=TRUE)
mi_details <- getTeamBattingDetails("Mumbai Indians",dir=".",save=TRUE)
rcb_details <- getTeamBattingDetails("Royal Challengers Bangalore",dir=".",save=TRUE)

2. Get IPL batsman details

This function is used to get the individual IPL T20 batting record for a the specified batsman of the team as in the functions below. For analyzing the batting performances I have chosen the top IPL T20 batsmen from the teams. This was based to a large extent on batting scorecard functions from yorkr crashes the IPL party!:Part 3 The top IPL batsmen chosen are the ones below

  1. Suresh Raina (CSK)
  2. MS Dhoni (CSK)
  3. Virendar Sehwag (DD)
  4. Rohit Sharma (MI)
  5. Gautham Gambhir (KKR)
  6. Virat Kohli (RCB)
setwd("C:/software/cricket-package/cricsheet/cleanup/IPL/part4")
raina <- getBatsmanDetails(team="Chennai Super Kings",name="SK Raina",dir=".")
## [1] "./Chennai Super Kings-BattingDetails.RData"
dhoni <- getBatsmanDetails(team="Chennai Super Kings",name="MS Dhoni")
## [1] "./Chennai Super Kings-BattingDetails.RData"
sehwag <-  getBatsmanDetails(team="Delhi Daredevils",name="V Sehwag",dir=".")
## [1] "./Delhi Daredevils-BattingDetails.RData"
gambhir <-  getBatsmanDetails(team="Kolkata Knight Riders",name="G Gambhir",dir=".")
## [1] "./Kolkata Knight Riders-BattingDetails.RData"
rsharma <-  getBatsmanDetails(team="Mumbai Indians",name="RG Sharma",dir=".")
## [1] "./Mumbai Indians-BattingDetails.RData"
kohli <-  getBatsmanDetails(team="Royal Challengers Bangalore",name="V Kohli",dir=".")
## [1] "./Royal Challengers Bangalore-BattingDetails.RData"

3. Runs versus deliveries (in IPL matches)

Sehwag has a superb strike rate. It can be seen that Sehwag averages around 80 runs for around 40 deliveries followed by Rohit Sharma. Raina and Dhoni average around 60 runs

p1 <-batsmanRunsVsDeliveries(raina, "SK Raina")
p2 <-batsmanRunsVsDeliveries(dhoni,"MS Dhoni")
p3 <-batsmanRunsVsDeliveries(sehwag,"V Sehwag")
p4 <-batsmanRunsVsDeliveries(gambhir,"G Gambhir")
p5 <-batsmanRunsVsDeliveries(rsharma,"RG Sharma")
p6 <-batsmanRunsVsDeliveries(kohli,"V Kohli")
grid.arrange(p1,p2,p3,p4,p5,p6, ncol=3)

runsVsDeliveries-1

4. Batsman Total runs, Fours and Sixes (in IPL matches)

Dhoni leads in the runs made from sixes in comparison to the others

raina46 <- select(raina,batsman,ballsPlayed,fours,sixes,runs)
p1 <-batsmanFoursSixes(raina46, "SK Raina")
dhoni46 <- select(dhoni,batsman,ballsPlayed,fours,sixes,runs)
p2 <-batsmanFoursSixes(dhoni46,"MS Dhoni")
sehwag46 <- select(sehwag,batsman,ballsPlayed,fours,sixes,runs)
p3 <-batsmanFoursSixes(sehwag46,"V Sehwag")
gambhir46 <- select(gambhir,batsman,ballsPlayed,fours,sixes,runs)
p4 <-batsmanFoursSixes(gambhir46,"G Gambhir")
rsharma46 <- select(rsharma,batsman,ballsPlayed,fours,sixes,runs)
p5 <-batsmanFoursSixes(rsharma46,"RG Sharma")
kohli46 <- select(kohli,batsman,ballsPlayed,fours,sixes,runs)
p6 <-batsmanFoursSixes(kohli46,"V Kohli")
grid.arrange(p1,p2,p3,p4,p5,p6, ncol=3)

foursSixes-1

5. Batsman dismissals (in IPL matches)

The type of dismissal for each batsman is shown below

p1 <-batsmanDismissals(raina, "SK Raina")
p2 <-batsmanDismissals(dhoni,"MS Dhoni")
p3 <-batsmanDismissals(sehwag,"V Sehwag")
p4 <-batsmanDismissals(gambhir,"G Gambhir")
p5 <-batsmanDismissals(rsharma,"RG Sharma")
p6 <-batsmanDismissals(kohli,"V Kohli")
grid.arrange(p1,p2,p3,p4,p5,p6, ncol=3)

dismissal-1

6. Runs versus Strike Rate (in IPL matches)

Raina, Dhoni and Kohli have an increasing strike rate with more runs scored

p1 <-batsmanRunsVsStrikeRate(raina, "SK Raina")
p2 <-batsmanRunsVsStrikeRate(dhoni,"MS Dhoni")
p3 <-batsmanRunsVsStrikeRate(sehwag,"V Sehwag")
p4 <-batsmanRunsVsStrikeRate(gambhir,"G Gambhir")
p5 <-batsmanRunsVsStrikeRate(rsharma,"RG Sharma")
p6 <-batsmanRunsVsStrikeRate(kohli,"V Kohli")
grid.arrange(p1,p2,p3,p4,p5,p6, ncol=3)

runsSR-1

7. Batsman moving average (in IPL matches)

Rohit Sharma seems to maintain an average of almost 30 runs, while Dhoni and Kohli average around 25.

p1 <-batsmanMovingAverage(raina, "SK Raina")
p2 <-batsmanMovingAverage(dhoni,"MS Dhoni")
p3 <-batsmanMovingAverage(sehwag,"V Sehwag")
p4 <-batsmanMovingAverage(gambhir,"G Gambhir")
p5 <-batsmanMovingAverage(rsharma,"RG Sharma")
p6 <-batsmanMovingAverage(kohli,"V Kohli")
grid.arrange(p1,p2,p3,p4,p5,p6, ncol=3)

ma-1

8. Batsman cumulative average (in IPL matches)

The cumulative runs average of Raina, Gambhir, Kohli and Rohit Sharma are around 28-30 runs.Dhoni drops to 25

p1 <-batsmanCumulativeAverageRuns(raina, "SK Raina")
p2 <-batsmanCumulativeAverageRuns(dhoni,"MS Dhoni")
p3 <-batsmanCumulativeAverageRuns(sehwag,"V Sehwag")
p4 <-batsmanCumulativeAverageRuns(gambhir,"G Gambhir")
p5 <-batsmanCumulativeAverageRuns(rsharma,"RG Sharma")
p6 <-batsmanCumulativeAverageRuns(kohli,"V Kohli")
grid.arrange(p1,p2,p3,p4,p5,p6, ncol=3)

cAvg-1

9. Cumulative Average Strike Rate (in IPL matches)

As seen above Sehwag has a phenomenal cumulative strike rate of around 150, followed by Dhoni around 130, then we Raina and finally Kohli.

p1 <-batsmanCumulativeStrikeRate(raina, "SK Raina")
p2 <-batsmanCumulativeStrikeRate(dhoni,"MS Dhoni")
p3 <-batsmanCumulativeStrikeRate(sehwag,"V Sehwag")
p4 <-batsmanCumulativeStrikeRate(gambhir,"G Gambhir")
p5 <-batsmanCumulativeStrikeRate(rsharma,"RG Sharma")
p6 <-batsmanCumulativeStrikeRate(kohli,"V Kohli")
grid.arrange(p1,p2,p3,p4,p5,p6, ncol=3)

cSR-1

10. Batsman runs against opposition (in IPL matches)

The following charts show the performance of te batsmen against opposing IPL teams


batsmanRunsAgainstOpposition(raina, "SK Raina")

runsOppn1-1

batsmanRunsAgainstOpposition(dhoni,"MS Dhoni")

runsOppn2-1

batsmanRunsAgainstOpposition(sehwag,"V Sehwag")

runsOppn3-1

batsmanRunsAgainstOpposition(gambhir,"G Gambhir")

runsOppn4-1

batsmanRunsAgainstOpposition(rsharma,"RG Sharma")

runsOppn5-1

batsmanRunsAgainstOpposition(kohli,"V Kohli")

runsOppn6-1

11. Runs at different venues (in IPL matches)

The plots below give the performances of the batsmen at different grounds.

batsmanRunsVenue(raina, "SK Raina")

runsVenue1-1

batsmanRunsVenue(dhoni,"MS Dhoni")

runsVenue2-1

batsmanRunsVenue(sehwag,"V Sehwag")

runsVenue3-1

batsmanRunsVenue(gambhir,"G Gambhir")

runsVenue4-1

batsmanRunsVenue(rsharma,"RG Sharma")

runsVenue5-1

batsmanRunsVenue(kohli,"V Kohli")

runsVenue6-1

12. Predict number of runs to deliveries (in IPL matches)

The plots below use rpart classification tree to predict the number of deliveries required to score the runs in the leaf node.

par(mfrow=c(1,3))
par(mar=c(4,4,2,2))
batsmanRunsPredict(raina, "SK Raina")
batsmanRunsPredict(dhoni,"MS Dhoni")
batsmanRunsPredict(sehwag,"V Sehwag")

runsPredict1,runsVenue1-1

par(mfrow=c(1,3))
par(mar=c(4,4,2,2))
batsmanRunsPredict(gambhir,"G Gambhir")
batsmanRunsPredict(rsharma,"RG Sharma")
batsmanRunsPredict(kohli,"V Kohli")

runsPredict2,runsVenue1-1

B. Bowler functions

13. Get bowling details in IPL matches

The function below gets the overall team IPL T20 bowling details based on the RData file available in IPL T20 matches. This is currently also available in Github at [yorkrData] (https://github.com/tvganesh/yorkrData/tree/master/IPL/IPL-T20-matches). The IPL T20 bowling details of the IPL team in each match is created, and a huge data frame is created by rbinding the individual dataframes. This can be saved as a RData file

setwd("C:/software/cricket-package/york-test/yorkrData/IPL/IPL-T20-matches")
kkr_bowling <- getTeamBowlingDetails("Kolkata Knight Riders",dir=".",save=TRUE)
csk_bowling <- getTeamBowlingDetails("Chennai Super Kings",dir=".",save=TRUE)
kxip_bowling <- getTeamBowlingDetails("Kings XI Punjab",dir=".",save=TRUE)
mi_bowling <- getTeamBowlingDetails("Mumbai Indians",dir=".",save=TRUE)
rcb_bowling <- getTeamBowlingDetails("Royal Challengers Bangalore",dir=".",save=TRUE)
rr_bowling <- getTeamBowlingDetails("Rajasthan Royals",dir=".",save=TRUE)
fl <- list.files(".","BowlingDetails.RData")
file.copy(fl, "C:/software/cricket-package/cricsheet/cleanup/IPL/part4")

14. Get bowling details of the individual IPL bowlers

This function is used to get the individual bowling record for a specified bowler of the country as in the functions below. For analyzing the bowling performances the following cricketers have been chosen based on the bowling scorecard from my post yorkr crashes the IPL party ! – Part 3

  1. Ravichander Ashwin (CSK)
  2. DJ Bravo (CSK)
  3. PP Chawla (KXIP)
  4. Harbhajan Singh (MI)
  5. R Vinay Kumar (RCB)
  6. SK Trivedi (RR)
setwd("C:/software/cricket-package/cricsheet/cleanup/IPL/part4")
ashwin <- getBowlerWicketDetails(team="Chennai Super Kings",name="R Ashwin",dir=".")
bravo <-  getBowlerWicketDetails(team="Chennai Super Kings",name="DJ Bravo",dir=".")
chawla <-  getBowlerWicketDetails(team="Kings XI Punjab",name="PP Chawla",dir=".")
harbhajan <-  getBowlerWicketDetails(team="Mumbai Indians",name="Harbhajan Singh",dir=".")
vinay <-  getBowlerWicketDetails(team="Royal Challengers Bangalore",name="R Vinay Kumar",dir=".")
sktrivedi <-  getBowlerWicketDetails(team="Rajasthan Royals",name="SK Trivedi",dir=".")

15. Bowler Mean Economy Rate (in IPL matches)

Ashwin & Chawla have the best economy rates of in the IPL teams, followed by Harbhajan Singh

p1<-bowlerMeanEconomyRate(ashwin,"R Ashwin")
p2<-bowlerMeanEconomyRate(bravo, "DJ Bravo")
p3<-bowlerMeanEconomyRate(chawla, "PP Chawla")
p4<-bowlerMeanEconomyRate(harbhajan, "Harbhajan Singh")
p5<-bowlerMeanEconomyRate(vinay, "R Vinay")
p6<-bowlerMeanEconomyRate(sktrivedi, "SK Trivedi")
grid.arrange(p1,p2,p3,p4,p5,p6, ncol=3)

meanER-1

16. Bowler Mean Runs conceded (in IPL matches)

p1<-bowlerMeanRunsConceded(ashwin,"R Ashwin")
p2<-bowlerMeanRunsConceded(bravo, "DJ Bravo")
p3<-bowlerMeanRunsConceded(chawla, "PP Chawla")
p4<-bowlerMeanRunsConceded(harbhajan, "Harbhajan Singh")
p5<-bowlerMeanRunsConceded(vinay, "R Vinay")
p6<-bowlerMeanRunsConceded(sktrivedi, "SK Trivedi")
grid.arrange(p1,p2,p3,p4,p5,p6, ncol=3)

meanRunsConceded-1

17. Bowler Moving average (in IPL matches)

Harbhajan’s moving average is the best hovering around 2 wickets

p1<-bowlerMovingAverage(ashwin,"R Ashwin")
p2<-bowlerMovingAverage(bravo, "DJ Bravo")
p3<-bowlerMovingAverage(chawla, "PP Chawla")
p4<-bowlerMovingAverage(harbhajan, "Harbhajan Singh")
p5<-bowlerMovingAverage(vinay, "R Vinay")
p6<-bowlerMovingAverage(sktrivedi, "SK Trivedi")
grid.arrange(p1,p2,p3,p4,p5,p6, ncol=3)

bowlerMA-1

17. Bowler cumulative average wickets (in IPL matches)

The cumulative average tells a different story. DJ Bravo and R Vinay have a cumulative average of 2 wickets. All others are around 1.5

p1<-bowlerCumulativeAvgWickets(ashwin,"R Ashwin")
p2<-bowlerCumulativeAvgWickets(bravo, "DJ Bravo")
p3<-bowlerCumulativeAvgWickets(chawla, "PP Chawla")
p4<-bowlerCumulativeAvgWickets(harbhajan, "Harbhajan Singh")
p5<-bowlerCumulativeAvgWickets(vinay, "R Vinay")
p6<-bowlerCumulativeAvgWickets(sktrivedi, "SK Trivedi")
grid.arrange(p1,p2,p3,p4,p5,p6, ncol=3)

cumWkts-1

18. Bowler cumulative Economy Rate (ER) (in IPL matches)

Ashwin & Harbhajan have the best cumulative economy rate

p1<-bowlerCumulativeAvgEconRate(ashwin,"R Ashwin")
p2<-bowlerCumulativeAvgEconRate(bravo, "DJ Bravo")
p3<-bowlerCumulativeAvgEconRate(chawla, "PP Chawla")
p4<-bowlerCumulativeAvgEconRate(harbhajan, "Harbhajan Singh")
p5<-bowlerCumulativeAvgEconRate(vinay, "R Vinay")
p6<-bowlerCumulativeAvgEconRate(sktrivedi, "SK Trivedi")
grid.arrange(p1,p2,p3,p4,p5,p6, ncol=3)

cumER-1

19. Bowler wicket plot (in IPL matches)

The plot below gives the average wickets versus number of overs

p1<-bowlerWicketPlot(ashwin,"R Ashwin")
p2<-bowlerWicketPlot(bravo, "DJ Bravo")
p3<-bowlerWicketPlot(chawla, "PP Chawla")
p4<-bowlerWicketPlot(harbhajan, "Harbhajan Singh")
p5<-bowlerWicketPlot(vinay, "R Vinay")
p6<-bowlerWicketPlot(sktrivedi, "SK Trivedi")
grid.arrange(p1,p2,p3,p4,p5,p6, ncol=3)

wktPlot-1

20. Bowler wicket against opposing IPL teams

bowlerWicketsAgainstOpposition(ashwin,"R Ashwin")

wktsOppn1-1

bowlerWicketsAgainstOpposition(bravo, "DJ Bravo")

wktsOppn2-1

bowlerWicketsAgainstOpposition(chawla, "PP Chawla")

wktsOppn3-1

bowlerWicketsAgainstOpposition(harbhajan, "Harbhajan Singh")

wktsOppn4-1

bowlerWicketsAgainstOpposition(vinay, "R Vinay")

wktsOppn5-1

bowlerWicketsAgainstOpposition(sktrivedi, "SK Trivedi")

wktsOppn6-1

21. Bowler wicket at cricket grounds in IPL

bowlerWicketsVenue(ashwin,"R Ashwin")

wktsAve1-1

bowlerWicketsVenue(bravo, "DJ Bravo")

wktsAve2-1

bowlerWicketsVenue(chawla, "PP Chawla")

wktsAve3-1

bowlerWicketsVenue(harbhajan, "Harbhajan Singh")

wktsAve4-1

bowlerWicketsVenue(vinay, "R Vinay")

wktsAve5-1

bowlerWicketsVenue(sktrivedi, "SK Trivedi")

wktsAve6-1

22. Get Delivery wickets for IPL bowlers

This function creates a dataframe of deliveries and the wickets taken

setwd("C:/software/cricket-package/york-test/yorkrData/IPL/IPL-T20-matches")
ashwin1 <- getDeliveryWickets(team="Chennai Super Kings",dir=".",name="R Ashwin",save=FALSE)
bravo1 <- getDeliveryWickets(team="Chennai Super Kings",dir=".",name="DJ Bravo",save=FALSE)
chawla1 <- getDeliveryWickets(team="Kings XI Punjab",dir=".",name="PP Chawla",save=FALSE)
harbhajan1 <- getDeliveryWickets(team="Mumbai Indians",dir=".",name="Harbhajan Singh",save=FALSE)
vinay1 <- getDeliveryWickets(team="Royal Challengers Bangalore",dir=".",name="R Vinay",save=FALSE)
sktrivedi1 <- getDeliveryWickets(team="Rajasthan Royals",dir=".",name="SK Trivedi",save=FALSE)

23. Predict number of deliveries to wickets in IPL T20

#Ashwin takes <6.5 deliveries for a wicket while Bravo takes around 5.5 deliveries. Don't get hung up on the .5 delivery. We can just take it that Bravo will provide a breakthrough quicker than Ashwin
par(mfrow=c(1,2))
par(mar=c(4,4,2,2))

bowlerWktsPredict(ashwin1,"R Ashwin")
bowlerWktsPredict(bravo1, "DJ Bravo")

wktsPred1-1

par(mfrow=c(1,2))
par(mar=c(4,4,2,2))
bowlerWktsPredict(chawla1, "PP Chawla")
bowlerWktsPredict(harbhajan1, "Harbhajan Singh")

wktsPred2-1

par(mfrow=c(1,2))
par(mar=c(4,4,2,2))
bowlerWktsPredict(vinay1, "R Vinay")
bowlerWktsPredict(sktrivedi1, "SK Trivedi")

wktsPred3-1

Conclusion

This concludes the 4 part writeup of yorkr’s handling of IPL Twenty20’s. You can fork/clone the code from Github at yorkr.

As I mentioned earlier, this brings to a close to all my posts based on my R cricket package yorkr. I do have a couple of more ideas, but this will take some time I think.

Hope you have a great time with my yorkr package!

Till next time, adieu!

Also see

  1. Introducing cricket package yorkr: Part 3-Foxed by flight!
  2. Introducing cricketr! : An R package to analyze performances of cricketers
  3. Cricket analytics with cricketr in paperback and Kindle versions
  4. Bend it like Bluemix, MongoDB with auto-scaling – Part 1
  5. The dark side of the Internet
  6. Modeling a Car in Android
  7. yorkr pads up for the Twenty20s: Part 1- Analyzing team”s match performance
  8. Cricket analytics with cricketr