Example #1
0
    public void Run()
    {
        int registerLength = 1; //кол-во кубитов. квантовый регистр это совокупность некоторого числа кубитов

        //Подготовка начально состояния
        QuantumRegister inputRegister  = new QuantumRegister(0, registerLength);             // Входной регистр
        QuantumRegister outputRegister = new QuantumRegister(1, registerLength);             // Выходной регистр
        QuantumRegister fullRegister   = new QuantumRegister(inputRegister, outputRegister); // Полный регистр (получается тензорным произведением)

        //Console.WriteLine(inputRegister);
        //Console.WriteLine(outputRegister);
        //Console.WriteLine(fullRegister);

        fullRegister = QuantumGate.HadamardGateOfLength(2) * fullRegister; // преобразование адамара
        Matrix <Complex> matrixOracle = MatrixOracle(registerLength);      //Проектирование оракула
        QuantumGate      GateOracle   = new QuantumGate(matrixOracle);     //Получаем гейт (на основе matrixOracle)

        fullRegister = GateOracle * fullRegister;
        fullRegister = QuantumGate.HadamardGateOfLength(2) * fullRegister; // преобразование адамара
        //Console.WriteLine(fullRegister);

        fullRegister.Collapse(this.Random);//измерение (наблюление) первого регистра
        int inputRegesterValue = fullRegister.GetValue(0, registerLength);

        FunctionDefinition(inputRegesterValue);

        Console.ReadKey();
    }
        public void QuantumGate_CombinedApplicationToQuantumRegister_IsValid()
        {
            QuantumGate     quantumGate     = new QuantumGate(QuantumGate.NotGate, QuantumGate.IdentityGate);
            QuantumRegister quantumRegister = new QuantumRegister(Qubit.Zero, Qubit.One);

            Assert.AreEqual(quantumGate * quantumRegister, new QuantumRegister(Qubit.One, Qubit.One));
        }
 public void QuantumGate_PhaseShiftGateFromPiOverTwo_IsValid()
 {
     Assert.IsTrue(QuantumGate.PhaseShiftGate(Math.PI / 2).AlmostEquals(new QuantumGate(new Complex[, ] {
         { 1, 0 },
         { 0, Complex.ImaginaryOne },
     })));
 }
Example #4
0
        double CountShipLive(int lives, int bombs)
        {
            double ones  = 0;
            double zeros = 0;
            int    trise = 102400;

            for (int i = 0; i < trise; i++)
            {
                if (bombs > lives)
                {
                    bombs = lives;
                }
                // QuantumRegisterVector zero = (QuantumRegisterVector) Qubit.Zero.QuantumRegister;
                // QuantumRegisterVector one = QuantumGate.Rotation((double)bombs * Math.PI / (double)lives) * zero;
                var    zero   = _producer.ProduceRegister(Qubit.Zero);
                var    one    = _producer.ProduceRegister(QuantumGate.Rotation((double)bombs * Math.PI / (double)lives) * zero);
                Random random = new Random();
                one.Collapse(random);
                if (one.GetValue() == 1)
                {
                    ones++;
                }
                else
                {
                    zeros++;
                }
            }

            return(ones / (double)trise);
        }
 public void QuantumGate_ControlledGateFromNotGate_IsValid()
 {
     Assert.AreEqual(QuantumGate.ControlledGate(QuantumGate.NotGate), new QuantumGate(new Complex[, ] {
         { 1, 0, 0, 0 },
         { 0, 1, 0, 0 },
         { 0, 0, 0, 1 },
         { 0, 0, 1, 0 },
     }));
 }
 public void QuantumGate_HadamardGateOfLength2_IsValid()
 {
     Assert.IsTrue(QuantumGate.HadamardGateOfLength(2).AlmostEquals(new QuantumGate(new Complex[, ] {
         { 0.5, 0.5, 0.5, 0.5 },
         { 0.5, -0.5, 0.5, -0.5 },
         { 0.5, 0.5, -0.5, -0.5 },
         { 0.5, -0.5, -0.5, 0.5 },
     })));
 }
Example #7
0
        //квантовая часть
        public int Period(int n, int a)
        {
            //1.	Выбрать число m такое, чтобы m=2l
            int registerLength = RegisterLength(n * n - 1);

            //2.	Подготовить два квантовых регистра, которые находятся в начальном состоянии |0⟩|0⟩.
            QuantumRegister inputRegister  = new QuantumRegister(0, registerLength); // первый регистр
            QuantumRegister outputRegister = new QuantumRegister(0, registerLength); // второй регистр

            //3.	Применить преобразование Адамара к первому регистру.
            inputRegister = QuantumGate.HadamardGateOfLength(registerLength) * inputRegister;
            //4.	Применить унитарный оператор (оракул)
            Matrix <Complex> modularExponentiationMatrix = ModularExponentiationMatrix(n, a, registerLength);

            QuantumGate     modularExponentiationGate = new QuantumGate(modularExponentiationMatrix);
            QuantumRegister fullRegister = new QuantumRegister(inputRegister, outputRegister);

            fullRegister = modularExponentiationGate * fullRegister;

            //5.	Применить обратное преобразование Фурье к первому регистру

            QuantumGate quantumFourierMatrixPlusIdentity = new QuantumGate(QuantumGate.QuantumFourierTransform(registerLength), QuantumGate.IdentityGateOfLength(registerLength));

            fullRegister = quantumFourierMatrixPlusIdentity * fullRegister;

            //6.	Измеряем первый регистр.
            fullRegister.Collapse(this.Random);
            int inputRegisterValue = fullRegister.GetValue(0, registerLength);

            //7.	Применить алгоритм цепных дробей
            float ratio       = (float)inputRegisterValue / (1 << registerLength);
            int   denominator = Denominator(ratio, n);

            //8. 9.	Убедится, что  . Если да, значит rʹ=r, алгоритм завершается. В противном случае выполнить предыдущий шаг с кратным rʹ.
            for (int period = denominator; period < n; period += denominator)
            {
                //if (ShorsAlgorithm.IntPow(a, period) % n == 1)
                if (ModIntPow(a, period, n) == 1)
                {
                    return(period);  ////////
                }
            }

            // 10.	В противном случае вернуться ко второму шагу.
            return(this.Period(n, a));
        }
        public void QuantumGate_QuantumFourierTranform_IsValid()
        {
            // Start with unnormalized samples
            Complex[] samples = new Complex[] { Complex.One, Complex.One + Complex.ImaginaryOne, Complex.ImaginaryOne, Complex.One - Complex.ImaginaryOne, Complex.One, Complex.Zero, Complex.ImaginaryOne, Complex.ImaginaryOne };

            // Create a quantum register from samples
            QuantumRegister quantumRegister = new QuantumRegister(samples);

            // Get normalized samples
            samples = quantumRegister.Vector.ToArray();

            // Transform quantum register
            quantumRegister = QuantumGate.QuantumFourierTransform(3) * quantumRegister;

            // Transform samples independently using Math.NET
            Fourier.Inverse(samples);

            // Compare results
            Assert.IsTrue(quantumRegister.AlmostEquals(new QuantumRegister(samples)));
        }
Example #9
0
        public void Run()
        {
            int registerLength = 3;//кол-во кубитов.
            //registerLength = Int32.Parse(Console.ReadLine());

            QuantumRegister fullRegister = new QuantumRegister(0, registerLength);          // Полный регистр

            fullRegister = QuantumGate.HadamardGateOfLength(registerLength) * fullRegister; // преобразование адамара

            Matrix <Complex> matrixOracle = MatrixOracle(registerLength);                   //Проектирование оракула
            QuantumGate      GateOracle   = new QuantumGate(matrixOracle);                  //Получаем гейт (на основе matrixOracle)


            Matrix <Complex> matrixPhaseInverse = PhaseInverse(registerLength);
            QuantumGate      GatePhaseInverse   = new QuantumGate(matrixPhaseInverse);

            ///////////////
            for (int count = 2; count > 0; count--)
            {
                // Console.WriteLine(1);
                fullRegister = GateOracle * fullRegister;
                //Console.WriteLine(fullRegister);
                //fullRegister = QuantumGate.HadamardGateOfLength(registerLength) * fullRegister;
                //Console.WriteLine(fullRegister);
                fullRegister = GatePhaseInverse * fullRegister;
                //Console.WriteLine(GatePhaseInverse);
                //fullRegister = QuantumGate.HadamardGateOfLength(registerLength) * fullRegister;
            }
            //fullRegister = QuantumGate.HadamardGateOfLength(registerLength) * fullRegister;


            //Console.WriteLine(fullRegister);
            fullRegister.Collapse(this.Random);//измерение (наблюление)
            int    RegisterValue       = fullRegister.GetValue(0, registerLength);
            string BinaryRegisterValue = Convert.ToString(RegisterValue, 2);

            Console.WriteLine(BinaryRegisterValue);
            Console.ReadKey();
        }
 public void QuantumGate_ControlledGateFromControlledNotGate_ThrowsArgumentException()
 {
     QuantumGate quantumGate = QuantumGate.ControlledGate(QuantumGate.ControlledGate(QuantumGate.NotGate));
 }
Example #11
0
 public CircuitModifiedEventArgs(QuantumGate gate, int qubitsNeeded)
 {
     Gate         = gate;
     QubitsNeeded = qubitsNeeded;
 }
Example #12
0
        void addtocalc(int activeregisters, int maximumWEigh)
        {
            List <QuantumGate> allregs = new List <QuantumGate> {
            };

            int[] weightReG  = new int[] { cR1, cR2, cR3, cR4, cR5, cR6, cR7, cR8, cR9, cR10, cR11 };//чтобы потом сравнить и добавить недостающие
            int[] weighFinal = new int[] { };
            for (int ia = 0; ia < maximumWEigh; ia++)
            {
                Array.Resize(ref weighFinal, weighFinal.Length + 1);
                weighFinal[weighFinal.Length - 1] = weightReG[ia];
            }
            for (int ia = 0; ia < weighFinal.Length; ia++)
            {
                weighFinal[ia] = activeregisters;
            }
            foreach (int xps in xpos)
            {
                foreach (int yps in ypos) // по горизонтали
                {
                    if (pictureBoxes.Count > 0)
                    {
                        foreach (PictureBox l in pictureBoxes)
                        {
                            if (l.Location.Y == yps && l.Location.X == xps)       //если совпадает с координатами по вертикали и горизонтали с изначальным
                            {
                                for (int i = 0; i < xpos.Count; i++)              //по количеству точек X массива
                                {
                                    if (xps == xpos[i])                           //по вертикали
                                    {
                                        for (int ix = 0; ix < gatsST.Count; ix++) //сверка вентилей ix - номер вентиля в списке
                                        {
                                            if (l.Name.IndexOf(gatsST[ix]) == 0)
                                            {
                                                weighFinal[i] -= gatsWeight[ix];
                                                allregs.Add(gatsQG[ix]);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            List <Qubit> flist = new List <Qubit> {
                st1, st2, st3, st4, st5, st6
            };
            List <Qubit> slist = new List <Qubit> {
            };

            for (int i = 0; i < activeregisters; i++)
            {
                slist.Add(flist[i]);
            }
            QuantumRegister reg  = new QuantumRegister(slist);
            int             ireg = 0;

            foreach (int weight in weighFinal)
            {
                int igs = 0;
                List <QuantumGate> fqg = new List <QuantumGate> {
                };
                for (int ih = ireg; ih < weight + ireg; ih++)
                {
                    fqg.Add(allregs[ih]);
                    igs++;
                }
                ireg += igs;
                QuantumGate gate = new QuantumGate(fqg);
                reg = gate * reg;
            }
            textBoxResult.Text = reg.ToString();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ProgramCode"/> class.
 /// </summary>
 /// <param name="gate">The gate.</param>
 /// <param name="bitIndex">Index of the bit.</param>
 public ProgramCode(QuantumGate gate, params int[] bitIndex)
 {
     Gate     = gate;
     BitIndex = bitIndex;
 }
 /// <summary>
 /// Adds the specified gate.
 /// </summary>
 /// <param name="gate">The gate.</param>
 /// <param name="bitIndex">Index of the bit.</param>
 public void Add(QuantumGate gate, params int[] bitIndex)
 {
     Codes.Add(new ProgramCode(gate, bitIndex));
 }
Example #15
0
 public ConnectControlsEventArgs(QuantumGate parent, Rectangle <int> area) : base(area)
 {
     Parent   = parent;
     Subgates = new List <ControlGate>();
 }