# Exploring Quantum Gate operations with QCSimulator

Introduction: Ever since I was initiated into Quantum Computing, through IBM’s Quantum Experience I have been hooked. My initial encounter with domain made me very excited and all wound up. The reason behind this, I think, is because there is an air of mystery around ‘Quantum’ anything.  After my early rush with the Quantum Experience, I have deliberately slowed down to digest the heady stuff.

This post also includes my early prototype of a Quantum Computing Simulator( QCSimulator) which I am creating in R. I hope to have a decent Quantum Computing simulator available, in the next couple of months. The ideas for this simulator are based on IBM’s Quantum Experience and the lectures on Quantum Mechanics and Quantum Computation by Prof Umesh Vazirani from University of California at Berkeley at edX. This calls to this simulator have been included in R Markdown file and has been published at RPubs as Quantum Computing Simulator

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

In this post I explore quantum gate operations

A) Quantum Gates
Quantum gates are represented as a n x n unitary matrix. In mathematics, a complex square matrix U is unitary if its conjugate transpose Uǂ is also its inverse – that is, if
U ǂU =U U ǂ=I

a) Clifford Gates
The following gates are known as Clifford Gates and are represented as the unitary matrix below

1. Pauli X
$\begin{pmatrix}0&1\\1&0\end{pmatrix}$

2.Pauli Y
$\begin{pmatrix}0&-i\\i&0\end{pmatrix}$

3. Pauli Z
$\begin{pmatrix}1&0\\0&-1\end{pmatrix}$

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

5. S Gate
$\begin{pmatrix}1 & 0\\ 0 & i\end{pmatrix}$

6. S1 Gate
$\begin{pmatrix}1 & 0\\ 0 & -i\end{pmatrix}$

7. CNOT
$\begin{pmatrix}1 & 0 & 0 &0 \\ 0 & 1 & 0 &0 \\ 0& 0 & 0&1 \\ 0 & 0 & 1 & 0\end{pmatrix}$

b) Non-Clifford Gate
The following are the non-Clifford gates
1. Toffoli Gate
T = $\begin{pmatrix}1 & 0\\ 0 & e^{^{i\prod /4}}\end{pmatrix}$

2. Toffoli1 Gate
T1 =$\begin{pmatrix}1 & 0\\ 0 & e^{^{-i\prod /4}}\end{pmatrix}$

B) Evolution of a 1 qubit Quantum System
The diagram below shows how a 1 qubit system evolves on the application of Quantum Gates.

C) Evolution of a 2 Qubit  System
The following diagram depicts the evolution of a 2 qubit system. The 4 different maximally entangled states can be obtained by using a Hadamard and a CNOT gate to |00>, |01>, |10> & |11> resulting in the entangled states  Φ+, Ψ+, Φ, Ψrespectively

D) Verifying Unitary’ness
XXǂ = XǂX= I
TTǂ = TǂT=I
SSǂ = SǂS=I
The Uǂ  function in the simulator is
Uǂ = GateDagger(U)

E) A look at some Simulator functions
The unitary functions for the Clifford and non-Clifford gates have been implemented functions. The unitary functions can be chained together by invoking each successive Gate as argument to the function.

1. Creating the dagger function
TDagger = GateDagger(TGate)
TDagger x TGate

H
##           [,1]       [,2]
## [1,] 0.7071068  0.7071068
## [2,] 0.7071068 -0.7071068
HDagger = GateDagger(H)
HDagger
##           [,1]       [,2]
## [1,] 0.7071068  0.7071068
## [2,] 0.7071068 -0.7071068
HDagger %*% H
##      [,1] [,2]
## [1,]    1    0
## [2,]    0    1
T
##      [,1]                 [,2]
## [1,] 1+0i 0.0000000+0.0000000i
## [2,] 0+0i 0.7071068+0.7071068i
TDagger = GateDagger(T)
TDagger
##      [,1]                 [,2]
## [1,] 1+0i 0.0000000+0.0000000i
## [2,] 0+0i 0.7071068-0.7071068i
TDagger %*% T
##      [,1] [,2]
## [1,] 1+0i 0+0i
## [2,] 0+0i 1+0i

2. Angle between 2 vectors – Inner product
The angle between 2 vectors can be obtained by taking the inner product between the vectors

#1. a is the diagonal vector 1/2 |0> + 1/2 |1> and b = q0 = |0>
diagonal <-  matrix(c(1/sqrt(2),1/sqrt(2)),nrow=2,ncol=1)
q0=matrix(c(1,0),nrow=2,ncol=1)
innerProduct(diagonal,q0)
##      [,1]
## [1,]   45
#2. a = 1/2|0> + sqrt(3)/2|1> and  b= 1/sqrt(2) |0> + 1/sqrt(2) |1>
a = matrix(c(1/2,sqrt(3)/2),nrow=2,ncol=1)
b = matrix(c(1/sqrt(2),1/sqrt(2)),nrow=2,ncol=1)
innerProduct(a,b)
##      [,1]
## [1,]   15

3. Chaining Quantum Gates
For e.g.
H x q0
S x H x q0 == > SGate(Hadamard(q0))

Or
H x S x S x H x q0 == > Hadamard(SGate(SGate(Hadamard))))

# H x q0
##           [,1]
## [1,] 0.7071068
## [2,] 0.7071068
# S x H x q0
##                      [,1]
## [1,] 0.7071068+0.0000000i
## [2,] 0.0000000+0.7071068i
# H x S x S x H x q0
##      [,1]
## [1,] 0+0i
## [2,] 1+0i
# S x T x H x T x H x q0
##                      [,1]
## [1,] 0.8535534+0.3535534i
## [2,] 0.1464466+0.3535534i

4. Measurement
The output of Quantum Gate operations can be measured with
measurement(a)
measurement(q0)
measurement(a)

measurement(q0)
##   0 1
## v 1 0
##     0   1
## v 0.5 0.5
measurement(a)
##           0         1
## v 0.8535534 0.1464466

5. Plot the measurements

plotMeasurement(q1)

plotMeasurement(a)

6. Using the QCSimulator for one of the Bell tests
Here I compute the following measurement of  Bell state ZW  with the QCSimulator

When this is simulated on IBM’s Quantum Experience the result is

Below I simulate the same on my R based QCSimulator

# Compute the effect of the Composite H gate with the Identity matrix (I)
a=kronecker(H,I,"*")
a
##           [,1]      [,2]       [,3]       [,4]
## [1,] 0.7071068 0.0000000  0.7071068  0.0000000
## [2,] 0.0000000 0.7071068  0.0000000  0.7071068
## [3,] 0.7071068 0.0000000 -0.7071068  0.0000000
## [4,] 0.0000000 0.7071068  0.0000000 -0.7071068
# Compute the applcation of CNOT on this result
b = CNOT(a)
b
##           [,1]      [,2]       [,3]       [,4]
## [1,] 0.7071068 0.0000000  0.7071068  0.0000000
## [2,] 0.0000000 0.7071068  0.0000000  0.7071068
## [3,] 0.0000000 0.7071068  0.0000000 -0.7071068
## [4,] 0.7071068 0.0000000 -0.7071068  0.0000000
# Obtain the result of CNOT on q00
c = b %*% q00
c
##           [,1]
## [1,] 0.7071068
## [2,] 0.0000000
## [3,] 0.0000000
## [4,] 0.7071068
# Compute the effect of the composite HxTxHxS gates and the Identity matrix(I) for measurement
e=kronecker(I, d,"*")

# Applying  the composite gate on the output 'c'
f = e %*% c
# Measure the output
g <- measurement(f)
g
##          00        01        10        11
## v 0.4267767 0.0732233 0.0732233 0.4267767
#Plot the measurement
plotMeasurement(g)

aa
which is exactly the result obtained with IBM’s Quantum Experience!

Conclusion : In  this post I dwell on 1 and 2-qubit quantum gates and explore their operation. I have started to construct a  R based Quantum Computing Simulator. I hope to have a reasonable simulator in the next couple of months. Let’s see.

Watch this space!

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

Index of posts

# 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

In 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

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

i) Quantum gate operations and Bloch measurements

ii) Quantum gate operations as Superposition operations

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

Simulating in Composer

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

Bloch measurement

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 = 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)

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

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

1) Simulations on Ideal Quantum processor

a) Bell state ZW (Ideal)

Simulation

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

b) Bell state ZV (Ideal)

Simulation

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

c) Bell state XW (Ideal)

Measurement

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

d) Bell state XV (Ideal)

Simulating Bell State XV in Composer

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

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

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)

b) Bell state ZV measurement  (Real)

c) Bell State XW measurement (Real)

d) Bell state XV measurement (Real)

;

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

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

# What’s up Watson? Using IBM Watson’s QAAPI with Bluemix, NodeExpress – Part 1

Published in IBM developerWorks ‘Whats up Watson? Using Watson QAAPI with Bluemix and NodeExpress

In this post I take the famed IBM Watson through the paces (yes, that’s right!, this post is about  using the same  IBM  Watson which trounced 2 human Jeopardy titans in a classic duel in 2011).  IBM’s Watson (see  What is Watson?) is capable of understanding the nuances of the English language and heralds a new era in the domain of cognitive computing. IBM Bluemix now includes 8 services from Watson ranging from Concept Expansion, Language Identification, Machine Translation, Question-Answer etc. For more information on Watson’s QAAPI and the many services that have been included in Bluemix please see Watson Services.

In this article I create an application on IBM Bluemix and use Watson’s QAAPI (Question-Answer API) as a service to the Bluemix application. For the application I have used NodeExpress to create a Webserver and post the REST queries to Watson.  Jade is used format the results of Watson’s Response.

In this current release of Bluemix Watson comes with a corpus of medical facts. In other words Watson has been made to ingest medical documents in multiple formats (doc, pdf, html, text  etc) and the user can pose medical questions to Dr.Watson. In its current avatar, its medical diet consisted of dishes from (CDC Health Topics, National Heart, Lung, and Blood Institute (NHLBI) National Institute of Arthritis and Musculoskeletal and Skin Diseases (NIAMS), National Institute of Diabetes and Digestive and Kidney Diseases (NIDDK), National Institute of Neurological Disorders and Stroke (NINDS), Cancer.gov (physician data query) etc.)

Try out my Watson app  on Bluemix here –  Whats up Watson?

To get down to Watson QAAPI business with Bluemix app you can fork the code from Devops at whatsup. This can then be downloaded to your local machine. You can also clone the code from GitHub at whatsup

1. To get started go to the directory where you have cloned the code for Whatsup app

2.Push the app to Bluemix using Cloud Foundry’s ‘cf’ commands as shown below

3. Next push the app to Bluemix
cf push whatsup –p . –m 512M

In the Bluemix dashboard you should see ‘whatsup’ app running. Now click ‘Add Service’ and under Watson add ‘Question Answer’

You will be prompted with ‘Restage Application’. Click ‘Ok’. Once you have the app running you should be able to get started with Doc Watson.

The code for this Bluemix app with QAAPI as a Service is based on the following article Examples using the Question and Answer API

1. Here’s a look at the code for the Bluemix & Watson app.

In this Bluemix app I show the different types of Questions we can ask Watson and the responses we get from it. The app has a route for each of the different types of questions and options

a. Simple Synchronous Query: Post a simple synchronous query to Watson
This is the simplest query that we can pose to Watson. Here we need to just include the text of the question and the also a Sync Timeout. The Sync Timeout denotes the time client will wait for responses from the Watson service
// Ask Watson a simple synchronous query

app.get('/question',question.list);
app.post('/simplesync',simplesync.list);

b. Evidence based question: Ask Watson to respond to evidence given to it
Ask Watson for responses based on evidence given like medical conditions etc. This would be a used for diagnostic purposes I would presume.
// Ask Watson for responses based on evidence provided
app.get('/evidence',evidence.list);
app.post('/evidencereq',evidencereq.list);

c. Request for a specified set of answers to a question: Ask Dr. Watson to give a specified number of responses to a question
// Ask Watson to provide specified number of responses to a query
app.get('/items',items.list);
app.post('/itemsreq',itemsreq.list);

d. Get a formatted response to a question: Ask Dr. Watson to format the response to the question
// Get a formatted response from Watson for a query
app.get('/format',format.list);
app.post('/formatreq',formatreq.list);

1. To get started with Watson we would need to connect the Bluemix app to the Watson’s QAAPI as a service by parsing the environment variable. This is shown below

//Get the VCAP environment variables to connect Watson service to the Bluemix application

question.js
o o o
if (process.env.VCAP_SERVICES) {
var VCAP_SERVICES = JSON.parse(process.env.VCAP_SERVICES);
// retrieve the credential information from VCAP_SERVICES for Watson QAAPI
var hostname   = VCAP_SERVICES["Watson QAAPI-0.1"][0].name;
var userid = VCAP_SERVICES["Watson QAAPI-0.1"][0].credentials.userid;
var watson_url = VCAP_SERVICES["Watson QAAPI-0.1"][0].credentials.url;

Next we need to format the header for the POST request

var parts = url.parse(watson_url);
// Create the request options to POST our question to Watson
var options = {host: parts.hostname,
port: 443,
path: parts.pathname,
method: 'POST',
rejectUnauthorized: false, // ignore certificates
requestCert: true,
agent: false};

The question that is to be asked of Watson needs to be formatted appropriately based on the input received in the appropriate form (for e.g. simplesync.jade)

question.js
// Get the values from the form
var syncTimeout = req.body.timeout;
var query = req.body.query;
// create the Question text to ask Watson
var question = {question : {questionText :query }};
var evidence = {"evidenceRequest":{"items":1,"profile":"yes"}};
// Set the POST body and send to Watson
req.write(JSON.stringify(question));
req.write("\n\n");
req.end();

Now you POST the Question to Dr. Watson and receive the stream of response using Node.js’ .on(‘data’,) & .on(‘end’) shown below

question.js
…..
var req = https.request(options, function(result) {
// Retrieve and return the result back to the client
result.on(“data”, function(chunk) {
output += chunk;
});

result.on('end', function(chunk) {
// Capture Watson's response in output. Parse Watson's answer for the fields
var results = JSON.parse(output);
res.render(
"results":results
});
});
});

The results are parsed and formatted displayed using Jade. For the Jade templates I have used a combination of Jade and inline HTML tags (Jade can occasionally be very stubborn and make you sweat quite a bit. So I took the easier route of inline HTML tagging. In a later post I will try out CSS stylesheets to format the response.)

Included below is the part of the jade template with inline HTML tagging

o o o
<h2 style="color:blueviolet">  Question Details </style> </h2>
for result in results.question.qclasslist
p <font color="blueviolet">  Value   = <font color="black "> #{result.value} </font>
p <font color="blueviolet">  Focuslist  </font> = <font color="black "> #{results.question.focuslist[0].value} </font>
// The 'How' query's response does not include latlist. Hence conditional added.
if latlist
p <font color="blueviolet">  Latlist  </font> = <font color="black "> #{results.question.latlist[0].value} </font>

o o o

Now that the code is all set you can fire the Watson. To do this click on the route

Click the route whatsup.mybluemix.net and ‘Lo and behold’ you should see Watson ready and raring to go.

As the display shows there are 4 different Question-Answer options that there is for Watson QAAPI

This option is the simplest option. Here we need to just include the text of the question and the also a Sync Timeout. The question can be any medical related question as Watson in its current Bluemix avatar has a medical corpus

For e.g.1) What is carotid artery disease?

2) What is the difference between hepatitis A and hepatitis B etc.

The Sync Timeout parameter specifies the number of seconds the QAAPI client will wait for the streaming response from Watson. An example question and Watson’s response are included below

;

When we click Submit Watson spews out the following response

Evidence based response:

In this mode of operation, questions can be posed to Watson based on observed evidence. Watson will output all relevant information based on the evidence provided. As seen in the output Watson provides a “confidence factor” for each of its response

Watson gives response with appropriate confidence values based on the given evidence

Question with specified number of responses
In this option we can ask Watson to provide us with at least ‘n’ items in its response. If it cannot provide as many items it will give an error notification

This will bring up the following screen where the question asked is “What is the treatment for Down’s syndrome?” and Items as 3.

Watson gives 3 items in the response as shown below

Formatted Response: Here Watson gives a formatted response to question asked. Since I had already formatted the response using Jade it does not do extra formatting as seen in the screen shot.

Updated synonym based response. In this response we can change the synonym list based on which Watson will search its medical corpus and modify its response. The synonym list for the the question “What is fever?” is shown below. We can turn off synonyms by setting to ‘false’ and possibly adding other synonyms for the search

This part of the code has not been included in this post and is left as an exercise to the reader 🙂

As mentioned before you can fork and clone the code from IBM devops at whatsup or clone from GitHub at whatsup

There are many sections to Watson’s answer which cannot be included in this post as the amount of information is large and really needs to be pared to pick out important details. I am including small sections from each part of Watson’s response below to the question “How is carotid artery disease treated/”

I will follow up this post with another post where I will take a closer look at Watson’s response which has many parts to it
namely

– Question Details

– Evidence list

– Synonym list