Writing Our First Quantum Program

What You’ll Learn

  • How to set up a quantum solution and project in Visual Studio
  • The components of a Q# operation
  • How to call a Q# operation from C#
  • How to build and execute your quantum algorithm

Creating a Bell State in Q#

Now that you’ve installed the Microsoft Quantum Development Kit and seen how it works, let’s write your first quantum application. We’ll start with the simplest program possible and build it up to demonstrate quantum superposition and quantum entanglement. We will start with a qubit in a basis state |0⟩, perform some operations on it and then measure the result.

Step 1: Create a Project and Solution

Open up Visual Studio 2017. Go to the File menu and select New > Project.... In the project template explorer, under Installed > Visual C#, select the Q# Application template. Give your project the name MyFirstQuantumApplication.

Step 2 (optional): Update NuGet Packages

If you want to run the latest version, update the Microsoft.Quantum.Development.Kit and Microsoft.Quantum.CanonNuGet packages, as described in Updating a Package.

Step 3: Enter the Q# Code

Our goal is to create a Bell State showing entanglement. We will build this up piece by piece to show the concepts of qubit state, gates and measurement.

Visual Studio should have two files open: Driver.cs, which will hold the C# driver for your quantum code, and Operation.qs, which will hold the quantum code itself.+

The first step is to rename the Q# file to Bell.qs. Right-click on Operation.qs in the Visual Studio Solution Explorer, and select the Rename option. Replace Operation with Bell and hit return.

To enter the Q# code, make sure that you are editing the Bell.qs window. The Bell.qs file should have the following contents:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
namespace Quantum.MyFirstQuantumApplication
{
    open Microsoft.Quantum.Primitive;
    open Microsoft.Quantum.Canon;
 
    operation Set (desired: Result, q1: Qubit) : ()
    {
        body
        {
            let current = M(q1);
            if (desired != current)
            {
                X(q1);
            }
        }
    }
 
	}

First, replace the string Operation with Set, and change the operation parameters (the first pair of parentheses) to contain the string desired: Result, q1: Qubit. The file should now look like above.

Add the following operation to the namespace, after the end of the Set operation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
operation BellTest (count : Int, initial: Result) : (Int,Int)
    {
        body
        {
            mutable numOnes = 0;
            using (qubits = Qubit[1])
            {
                for (test in 1..count)
                {
                    Set (initial, qubits[0]);
 
                    let res = M (qubits[0]);
 
                    // Count the number of ones we saw:
                    if (res == One)
                    {
                        set numOnes = numOnes + 1;
                    }
                }
                Set(Zero, qubits[0]);
            }
            // Return number of times we saw a |0> and number of times we saw a |1>
            return (count-numOnes, numOnes);
        }
    }

This operation (BellTest) will loop for count iterations, set a specified initial value on a qubit and them measure (M) the result. It will gather statistics on how many zeros and ones we’ve measured and return them to the caller. It performs one other necessary operation. It resets the qubit to a known state (Zero) before returning it allowing others to allocate this qubit in a known state. This is required by the using statement.
All of these calls use primitive quantum operations that are defined in the Microsoft.Quantum.Primitive namespace. For instance, the M operation measures its argument qubit in the computational (Z) basis, and X applies a state flip around the x axis to its argument qubit.

Note

As you can see, Q# uses C#-like semicolons and braces to indicate program structure.
Q# has an if statement that is very much like C#.

Q# deals with variables in a unique way. By default, variables in Q# are immutable; their value may not be changed after they are bound. The let keyword is used to indicate the binding of an immutable variable. Operation arguments are always immutable.

If you need a variable whose value can change, such as numOnes in the example, you can declare the variable with the mutable keyword. A mutable variable’s value may be changed using a set statement.

In both cases, the type of a variable is inferred by the compiler. Q# doesn’t require any type annotations for variables.
The using statement is also special to Q#. It is used to allocate an array of qubits for use in a block of code. In Q#, all qubits are dynamically allocated and released, rather than being fixed resources that are there for the entire lifetime of a complex algorithm. A using statement allocates a set of qubits at the start and releases those qubits at the end of the block. There is an analogous borrowing statement that is used to allocate potentially dirty ancilla qubits.
A for loop in Q# always iterates through a range. There is no Q# equivalent to a traditional C-style computer for the statement. A range may be specified by the first and last integers in the range, as in the example: 1..10 is the range 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10. If a step other than +1 is needed, then three integers with .. between them are used: 1..2..10 is the range 1, 3, 5, 7, and 9. Note that ranges are inclusive at both ends.

The BellTest operation returns two values as a tuple. The operation’s return type is (Int, Int), and the return statement has an explicit tuple containing two integer variables. Q# uses tuples as a way to pass multiple values, rather than using structures or records.

Step 4: Enter the C# Driver Code

Switch to the Driver.cs file in Visual Studio. This file should have the following contents:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
 
namespace Quantum.MyFirstQuantumApplication
{
    public class Driver
    {
        static void Main(string[] args)
        {
            using (var sim = new QuantumSimulator())
            {
                // Try initial values
                Result[] initials = new Result[] { Result.Zero, Result.One };
                foreach (Result initial in initials)
                {
                    var res = BellTest.Run(sim, 1000, initial).Result;
                    var (numZeros, numOnes) = res;
                    System.Console.WriteLine(
                        $"Init:{initial,-4} 0s={numZeros,-4} 1s={numOnes,-4}");
                }
            }
            System.Console.WriteLine("Press any key to continue...");
            System.Console.ReadKey();
        }
    }
}

Step 5: Build and Run

Just hit F5, and your program should build and run!

The results should be:

The program will exit after you press a key.

Creating Superposition

Now we want to manipulate the qubit. First we’ll just try to flip it. This is accomplished by performing an X gate before we measure it in BellTest:

1
2
                    X(qubits[0]);
                    let res = M (qubits[0]);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
operation BellTest (count : Int, initial: Result) : (Int,Int)
    {
        body
        {
            mutable numOnes = 0;
            using (qubits = Qubit[1])
            {
                for (test in 1..count)
                {
                    Set (initial, qubits[0]);
 
                    <span style="color: #ff0000;"><strong>X(qubits[0]);</strong></span>
                    let res = M (qubits[0]);
 
                    // Count the number of ones we saw:
                    if (res == One)
                    {
                        set numOnes = numOnes + 1;
                    }
                }
                Set(Zero, qubits[0]);
            }
            // Return number of times we saw a |0> and number of times we saw a |1>
            return (count-numOnes, numOnes);
        }
    }

You have seen that the results are now inversed.

However, everything we’ve seen so far is classical. Let’s get a quantum result. All we need to do is replace the Xgate in the previous run with an H or Hadamard gate. Instead of flipping the qubit all the way from 0 to 1, we will only flip it halfway. The replaced lines in BellTest now look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
operation BellTest (count : Int, initial: Result) : (Int,Int)
    {
        body
        {
            mutable numOnes = 0;
            using (qubits = Qubit[1])
            {
                for (test in 1..count)
                {
                    Set (initial, qubits[0]);
		    <span style="color: #ff0000;"><strong>H(qubits[0]);</strong></span>
                    let res = M (qubits[0]);
 
                    // Count the number of ones we saw:
                    if (res == One)
                    {
                        set numOnes = numOnes + 1;
                    }
                }
                Set(Zero, qubits[0]);
            }
            // Return number of times we saw a |0> and number of times we saw a |1>
            return (count-numOnes, numOnes);
        }
    }

Now the results get more interesting:

Every time we measure, we ask for a classical value, but the qubit is halfway between 0 and 1, so we get (statistically) 0 half the time and 1 half the time. This is known as superposition and gives us our first real view of a quantum state.

Creating Entanglement

Now we’ll make the promised Bell State and show off entanglement. The first thing we’ll need to do is allocate 2 qubits instead of one in BellTest:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
operation BellTest (count : Int, initial: Result) : (Int,Int)
    {
        body
        {
            mutable numOnes = 0;
			// Qubit[2] in below line - This will allow us to add a new gate (CNOT) before we measure (M) in BellTest:
            using (qubits = Qubit[2])
            {
                for (test in 1..count)
                {
                    Set (initial, qubits[0]);
					Set(Zero, qubits[1]);
 
					H(qubits[0]);
					<span style="color: #ff0000;"><strong>CNOT(qubits[0], qubits[1]);</strong></span>
                    let res = M (qubits[0]);
 
                    // Count the number of ones we saw:
                    if (res == One)
                    {
                        set numOnes = numOnes + 1;
                    }
                }
                Set(Zero, qubits[0]);
				//We also need to reset the second qubit before releasing it (this could also be done with a for loop). We'll add a line after qubit 0 is reset
				<strong><span style="color: #ff0000;">Set(Zero, qubits[1]);</span></strong>
            }
            // Return number of times we saw a |0> and number of times we saw a |1>
            return (count-numOnes, numOnes);
        }
    }

If we run this, we’ll get exactly the same 50-50 result we got before. However, what we’re really interested in is how the second qubit reacts to the first being measured.

We’ll add this statistic with a new version of the BellTest operation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
operation BellTest (count : Int, initial: Result) : (Int,Int)
    {
        body
        {
            mutable numOnes = 0;
			<span style="color: #ff0000;"><strong>mutable agree=0;</strong></span>
			// Qubit[2] in below line - This will allow us to add a new gate (CNOT) before we measure (M) in BellTest:
            using (qubits = Qubit[2])
            {
                for (test in 1..count)
                {
                    Set (initial, qubits[0]);
					Set(Zero, qubits[1]);
 
					H(qubits[0]);
					<span style="color: #ff0000;"><strong>CNOT(qubits[0], qubits[1]);</strong></span>
                    let res = M (qubits[0]);
 
					<strong><span style="color: #ff0000;">if(M (qubits[1]) == res)
					{
						set agree=agree + 1;
					}</span></strong>
                    // Count the number of ones we saw:
                    if (res == One)
                    {
                        set numOnes = numOnes + 1;
                    }
                }
                Set(Zero, qubits[0]);
				//We also need to reset the second qubit before releasing it (this could also be done with a for loop). We'll add a line after qubit 0 is reset
				Set(Zero, qubits[1]);
            }
            // Return number of times we saw a |0> and number of times we saw a |1>
            return (count-numOnes, numOnes, <span style="color: #ff0000;"><strong>agree</strong></span>);
        }
    }

There is now a new return value (agree) that will keep track of every time the measurement from the first qubit matches the measurement of the second qubit. Of course, we also have to update the Driver.cs file accordingly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using (var sim = new QuantumSimulator())
            {
                // Try initial values
                Result[] initials = new Result[] { Result.Zero, Result.One };
                foreach (Result initial in initials)
                {
                    var res = BellTest.Run(sim, 1000, initial).Result;
                    var (numZeros, numOnes, agree) = res;
                    System.Console.WriteLine(
                        $"Init:{initial,-4} 0s={numZeros,-4} 1s={numOnes,-4} agree={agree,-4}");
                }
            }
            System.Console.WriteLine("Press any key to continue...");
            System.Console.ReadKey();

Our statistics for the first qubit haven’t changed (50-50 chance of a 0 or a 1), but now when we measure the second qubit, it is always the same as what we measured for the first qubit. Our CNOT has entangled the two qubits, so that whatever happens to one of them, happens to the other. If you reversed the measurements (did the second qubit before the first), the same thing would happen. The first measurement would be random and the second would be in lock step with whatever was discovered for the first.

I do hope this walkthrough will be enough for a kick start. I took help and guidance in steps from URL below.

https://docs.microsoft.com/en-gb/quantum/quantum-WriteAQuantumProgram?view=qsharp-preview

Installing and Validating the Q# Development Environment

Prerequisites

  • Microsoft’s quantum simulator, installed with the Quantum Development Kit, utilizes Advance Vector Extensions (AVX), and requires an AVX-enabled CPU. Intel processors shipped in Q1 2011 (Sandy Bridge) or later support AVX. We are evaluating support for earlier CPUs and may announce details at a later time.
  • The simulator included with the Quantum Development Kit requires a 64-bit installation of Microsoft Windows to run.
  • Visual Studio 2017

If you do not have Visual Studio installed, you can download Visual Studio 2017 Community Edition for free.

  1. Go to the Visual Studio download page.
  2. Click on the Visual Studio Community Free download button.
  3. Navigate to your browser’s download folder and double click on the executable file whose name begins with vs_community. The file name will contain a sequence of numbers that varies.
  4. Important!  When you are presented with the option to select the tools for specific workloads, check the boxes for Universal Windows Platform development and .NET desktop development
  5. After selecting your workloads, click Install to complete the installation.

Creating the Q# Development Environment

  1. Install the Microsoft Quantum Development Kit
    1. Browse to the Microsoft Quantum page and click the Download now button in the upper left.
    2. On the Visual Studio Marketplace Quantum Development Kit page, click Download.
    3. Your browser will ask you whether you wish to Open or Save the download, click Open.
    4. Your security software may present a confirmation pane. Click Allow, or the comparable term used by your browser.
    5. The Quantum Development Kit extension will be installed in Visual Studio 2017.

Validating Your Environment

In this section you will clone the quantum samples & libraries, and run a sample application to verify that your Q# environment is correctly installed and configured.

  1. Clone the Microsoft Quantum Developer Kit Samples and Libraries GitHub repository.
    1. Open Visual Studio.
    2. Open the Connect view in Team Explorer (Team > Manage Connections)
    3. Select Clone under Local Git Repositories and enter https://github.com/Microsoft/Quantum.git
    4. Click Clone to clone the repo.
    5. The repository will be cloned on your local computer and Visual Studio will switch to the Solution Explorer on the right populated with the libraries and samples.
  2. Open the QsharpLibraries.sln solution.
    • If prompted by the Install Missing Features pane, click Install to allow the installation of the necessary features. This is most often F# and tools used by some of the samples.
  3. Validate your Q# environment by running the teleport sample program:
    1. Right click on the TeleportationSample project in Samples > 0.Introduction folder of QsharpLibraries solution, and left click on “Set as Startup Project”.
    2. Run the solution (F5.) If teleport runs and the output is similar to the following (has 8 rounds of successful teleportation with varying values True/False sent each round), your Q# environment is ready to support Q# development.
Blog-Source : https://docs.microsoft.com/en-gb/quantum/quantum-installconfig?view=qsharp-preview

.net – Kick Start (Introduction) to quantum computing

What is Quantum Computing?

A lot of computer technologies had come up within the last couple of years but Quantum computing is by far the greatest paradigm shift on part of computer science developers.

At the time Quantum computers were proposed first in 1980 by Richard Feynman and Yuri Manin, It was highly criticized as due to limitations in modeling even simpler systems at that time. As time goes on during 1900 and 1925 it still had been a vital part of chemistry, condensed matter physics, and other technologies.

Simulating Quantum mechanics is hard to even to simulate. The simplest explanation could be like this that “A matter, at a quantum level, exists in a host of different possible states or configurations at the same time. Unlike, classical probability theory, which comes to a point that “every statistical experiment will contain elements that are equally likely to happen”, these many configurations of the quantum state, which can be potentially observed, may interfere with each other like waves. This interference prevents the use of statistical sampling to obtain the quantum state configurations.

Limitation in hardware is yet another factor to hinder in the path of quantum computing. Let us say a system of electrons can be in say any of 40 positions. We can, therefore, say that electron is in any of 2^40 configurations (since each position can either have or not have an electron). To store this state in system memory we would require around 130gb of memory. If next, we allow it to be in 41 positions, there would be twice as many configurations which may require around 260 Gb of memory to store the quantum state.

The core of quantum computing is to store information in quantum states of matter and to use quantum gate operations to compute on that information, by learning to “program” quantum interference. In future, we might be able to crack RSA and ECDLF using quantum computing.

MICROSOFT QUANTUM DEVELOPMENT KIT

Microsoft has taken a step by introducing “Microsoft Quantum Development Kit”, that will help in making quantum programming and algorithm development more accessible. Quantum programming is a distinct art from classical programming requiring very different tools to understand and express quantum algorithmic thinking. Microsoft has brought the Quantum Development tools to unlock the quantum revolution for their tasks, problems, and solutions.

Q# (Q Sharp) was designed to address the challenges of quantum information processing, it is integrated into a software stack that enables a quantum algorithm to be compiled down to the primitive operations of a quantum computer.

CSharp: Best way to handle null values

Lets say we receive some value and it is null and we are going to use that in our code

var divident=null;
var value=divident / 2;

Above line will throw a null exception.
To avoid that one might add a condition that could be

if(divident !=null)
{
var value=divident / 2;
}

a better way could be like below:

var value= (divident ?? 0) / 2;

Detecting mobile device in Asp.net and node.js

http://hgoebl.github.io/mobile-detect.js/

mobile-detect.js

A loose port of Mobile-Detect to JavaScript.

This script will detect the device by comparing patterns against a given User-Agent string. You can find out information about the device rendering your web page:

  • mobile or not
  • if mobile, whether phone or tablet
  • operating system
  • Mobile Grade (A, B, C)
  • specific versions (e.g. WebKit)

 

Usage

Browser

<script src="mobile-detect.js"></script>
<script>
    var md = new MobileDetect(window.navigator.userAgent);
    // ... see below
</script>

Node.js / Express

var MobileDetect = require('mobile-detect'),
    md = new MobileDetect(req.headers['user-agent']);
// ... see below

General

var md = new MobileDetect(
    'Mozilla/5.0 (Linux; U; Android 4.0.3; en-in; SonyEricssonMT11i' +
    ' Build/4.1.A.0.562) AppleWebKit/534.30 (KHTML, like Gecko)' +
    ' Version/4.0 Mobile Safari/534.30');

// more typically we would instantiate with 'window.navigator.userAgent'
// as user-agent; this string literal is only for better understanding

console.log( md.mobile() );          // 'Sony'
console.log( md.phone() );           // 'Sony'
console.log( md.tablet() );          // null
console.log( md.userAgent() );       // 'Safari'
console.log( md.os() );              // 'AndroidOS'
console.log( md.is('iPhone') );      // false
console.log( md.is('bot') );         // false
console.log( md.version('Webkit') );         // 534.3
console.log( md.versionStr('Build') );       // '4.1.A.0.562'
console.log( md.match('playstation|xbox') ); // false