public void CanCreateComplexNumberWithModulusArgument()
        {
            var complex = Complex32.FromPolarCoordinates(2, (float)-Math.PI / 6);

            Assert.AreEqual((float)Math.Sqrt(3), complex.Real, 1e-7f, "Real part is Sqrt(3).");
            Assert.AreEqual(-1.0f, complex.Imaginary, 1e-7f, "Imaginary part is -1.");
        }
Example #2
0
        /// <summary>
        /// Convert Polar coordianates to a cartesean point
        /// </summary>
        /// <param Name="direction">The direction the point is in</param>
        /// <param Name="magnitude">The distance from the origin of the point</param>
        /// <returns>The point in polar coordinates</returns>
        protected PointF PolarToPoint(double direction, double magnitude)
        {
            //C#'sections only way of dealing with polar coordinates is as a complex number
            //So we're going to create a new complex number, and read off its components
            Complex32 comp = Complex32.FromPolarCoordinates((float)magnitude, (float)direction);

            return(new PointF(comp.Real, comp.Imaginary));
        }
 public ACVoltageGenerator(ComponentContainer owner, float ACMagnitude = 1, float ACPhase = 0)
     : base(owner)
 {
     ACVoltage = Complex32.FromPolarCoordinates(ACMagnitude, ACPhase);
     //ACVoltage = new Complex32(ACMagnitude, 0);
 }
        /// <summary>
        /// Read a netlist file (.net) containing componentsdescription y nodes
        /// A Circuit object with components y nodes will be created
        /// </summary>
        /// <param name="CircuitName"></param>
        public void ReadCircuit(string CircuitName)
        {
            if (!File.Exists(CircuitName))
            {
                HasErrors = true;
                throw new FileNotFoundException();
            }
            try
            {
                TextReader reader = File.OpenText(CircuitName);

                string txt = reader.ReadToEnd();
                reader.Close();

                string[] lines = txt.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < lines.Length; i++)
                {
                    string item = lines[i];
                    //un comentario
                    if (item.StartsWith("*"))
                    {
                        continue;
                    }

                    int j = i + 1;
                    while (j < lines.Length && lines[j].StartsWith("+"))
                    {
                        item += " " + lines[j].Substring(1);
                        j++;
                        i++;
                    }

                    //R_R1         $N_0002 $N_0001  1k
                    string[]          elemn = item.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    ElectricComponent comp  = null;
                    string[]          comp1 = elemn[0].Split("_".ToCharArray());
                    switch (comp1[0].ToUpper())
                    {
                    case "R":
                        comp = new Resistor(this, comp1[1], elemn[3]);
                        break;

                    case "V":
                        if (elemn.Length == 4)
                        {
                            comp = new VoltageGenerator(this, comp1[1], elemn[3]);
                        }
                        else if (elemn.Length == 7 || elemn.Length == 8)
                        {
                            ACVoltageGenerator ac = new ACVoltageGenerator(this, comp1[1], elemn[4]);
                            if (elemn.Length == 8)
                            {
                                ac.ACVoltage = Complex32.FromPolarCoordinates((float)StringUtils.DecodeString(elemn[6]),
                                                                              (float)StringUtils.DecodeString(elemn[7]));
                            }
                            else
                            {
                                ac.ACVoltage = new Complex32((float)StringUtils.DecodeString(elemn[6]), 0);
                            }
                            comp = (ACVoltageGenerator)ac;
                        }
                        else if (elemn.Length > 8)
                        {
                            //V_V1         $N_0001 0 DC 0 AC 1
                            //+SIN 1 1 1k 0 0 0
                            SineVoltageGenerator vsin = new SineVoltageGenerator(this, comp1[1]);
                            //if (elemn.Length == 8)
                            //vsin.ACVoltage = new Complex32((float)StringUtils.DecodeString(elemn[6]),
                            //                            (float)StringUtils.DecodeString(elemn[6]));
                            //else
                            vsin.ACVoltage = new Complex32((float)StringUtils.DecodeString(elemn[6]), 0);
                            vsin.Amplitude = elemn[9];
                            vsin.Offset    = elemn[8];
                            vsin.Frequency = elemn[10];
                            vsin.Thau      = elemn[12];
                            vsin.Delay     = elemn[11];
                            vsin.Phase     = elemn[13];
                            comp           = vsin;
                        }
                        else
                        {
                            throw new NotImplementedException();
                        }
                        break;

                    case "I":
                        if (elemn[3] == "DC")
                        {
                            comp = new CurrentGenerator(this, comp1[1], elemn[4]);
                        }
                        else
                        {
                            //aun sin resolver para otros generadores
                            comp = new CurrentGenerator(this, comp1[1], elemn[4]);
                        }

                        break;

                    case "L":
                        comp = new Inductor(this, comp1[1], elemn[3]);

                        break;

                    case "C":
                        comp = new Capacitor(this, comp1[1], elemn[3]);

                        break;

                    case "E":
                        //E_E1         $N_0002 0 $N_0001 0 10
                        VoltageControlledGenerator E = new VoltageControlledGenerator(this, comp1[1]);
                        E.Gain = elemn[5];

                        Node node1 = null;
                        node1 = CreateOrFindNode(elemn[3]);
                        E.InputNodes.Add(node1);

                        node1 = CreateOrFindNode(elemn[4]);
                        E.InputNodes.Add(node1);

                        comp = E;
                        break;

                    default:
                        throw new Exception();
                    }

                    comp.Nodes.Clear();
                    //agrego los nodos al circuito y al componente
                    Node n;
                    if (!Nodes.ContainsKey(elemn[1]))
                    {
                        n = new Node(elemn[1]);
                        Nodes.Add(n.Name, n);
                    }
                    else
                    {
                        n = Nodes[elemn[1]];
                    }

                    comp.Nodes.Add(n);
                    n.Components.Add(comp);
                    if (n.Name == "0")
                    {
                        n.IsReference = true;
                        Reference     = n;
                    }
                    //agrego el segundo nodo
                    if (!Nodes.ContainsKey(elemn[2]))
                    {
                        n = new Node(elemn[2]);
                        Nodes.Add(elemn[2], n);
                    }
                    else
                    {
                        n = Nodes[elemn[2]];
                    }

                    comp.Nodes.Add(n);
                    n.Components.Add(comp);

                    if (n.Name == "0")
                    {
                        n.IsReference = true;
                        Reference     = n;
                    }
                    Components.Add(comp);
                }
                State           = CircuitState.FileLoaded;
                OriginalCircuit = this;
            }
            catch (Exception ex)
            {
                HasErrors = true;
                throw;
            }
        }
Example #5
0
    public DenseMatrix MatchGate(string gate) // Method to take string gate name -> 2x2 or 4x4 DenseMatrix of equivalent gate //
    {
        // 1. Unary Gates, 2x2
        // 1.A Pauli Matricies (rotate on x, y and z matrices 180 degrees)
        // X operator, NOT operator, bit flip, sigma_x
        var X = DenseMatrix.OfArray(new Complex32[, ]
        {
            { new Complex32(0, 0), new Complex32(1, 0) },
            { new Complex32(1, 0), new Complex32(0, 0) }
        });
        // Y operator, sigma_y
        var Y = DenseMatrix.OfArray(new Complex32[, ]
        {
            { new Complex32(0, 0), new Complex32(0, -1) },
            { new Complex32(0, 1), new Complex32(0, 0) }
        });
        // Z operator, phase flip operator, flips by pi rad aka 180 deg)
        var Z = DenseMatrix.OfArray(new Complex32[, ]
        {
            { new Complex32(1, 0), new Complex32(0, 0) },
            { new Complex32(0, 0), new Complex32(-1, 0) }
        });
        // I operator, identity
        var I = DenseMatrix.OfArray(new Complex32[, ]
        {
            { new Complex32(1, 0), new Complex32(0, 0) },
            { new Complex32(0, 0), new Complex32(1, 0) }
        });

        // 1.B Special cases of phase shift operator, R_phi
        // S operator, phi = pi/2, rotate on z axis by 90 deg
        var S = DenseMatrix.OfArray(new Complex32[, ]
        {
            { new Complex32(1, 0), new Complex32(0, 0) },
            { new Complex32(0, 0), new Complex32(0, 1) }
        });
        // T operator, phi = pi/2, rotate on z axis by 45 deg
        var T = DenseMatrix.OfArray(new Complex32[, ]
        {
            { new Complex32(1, 0), new Complex32(0, 0) },
            { new Complex32(0, 0), Complex32.FromPolarCoordinates(1, Mathf.PI / 4) }
        });

        // 1.C Hadamard operator, takes qubit from definite computational basis to a superposition of two states
        var H = DenseMatrix.OfArray(new Complex32[, ]
        {
            { new Complex32((1 / Mathf.Sqrt(2)), 0), new Complex32((1 / Mathf.Sqrt(2)), 0) },
            { new Complex32((1 / Mathf.Sqrt(2)), 0), new Complex32(-(1 / Mathf.Sqrt(2)), 0) }
        });

        // 2. Binary Operators, 4x4
        // 2.A Swap operator, swaps states of two qubits
        var SWAP = DenseMatrix.OfArray(new Complex32[, ]
        {
            { new Complex32(1, 0), new Complex32(0, 0), new Complex32(0, 0), new Complex32(0, 0) },
            { new Complex32(0, 0), new Complex32(0, 0), new Complex32(1, 0), new Complex32(0, 0) },
            { new Complex32(0, 0), new Complex32(1, 0), new Complex32(0, 0), new Complex32(0, 0) },
            { new Complex32(0, 0), new Complex32(0, 0), new Complex32(0, 0), new Complex32(1, 0) }
        });
        // 2.B CNOT operator, if control qubit (1st q) is 0, do nothing to target qubit (2nd q),
        // but if control qubit is 1, apply NOT operator to target qubit
        var CNOT = DenseMatrix.OfArray(new Complex32[, ]
        {
            { new Complex32(1, 0), new Complex32(0, 0), new Complex32(0, 0), new Complex32(0, 0) },
            { new Complex32(0, 0), new Complex32(1, 0), new Complex32(0, 0), new Complex32(0, 0) },
            { new Complex32(0, 0), new Complex32(0, 0), new Complex32(0, 0), new Complex32(1, 0) },
            { new Complex32(0, 0), new Complex32(0, 0), new Complex32(1, 0), new Complex32(0, 0) }
        });
        // 2.C CZ operator, if control qubit (1st q) is 0, do nothing to target qubit (2nd q),
        // but if control qubit is 1, apply Z operator to target qubit
        // is symmetric so same result if either qubit is target/control
        var CZ = DenseMatrix.OfArray(new Complex32[, ]
        {
            { new Complex32(1, 0), new Complex32(0, 0), new Complex32(0, 0), new Complex32(0, 0) },
            { new Complex32(0, 0), new Complex32(1, 0), new Complex32(0, 0), new Complex32(0, 0) },
            { new Complex32(0, 0), new Complex32(0, 0), new Complex32(1, 0), new Complex32(0, 0) },
            { new Complex32(0, 0), new Complex32(0, 0), new Complex32(0, 0), new Complex32(-1, 0) }
        });

        //Debug.Log((X)); Debug.Log((Y)); Debug.Log((Z)); Debug.Log((S)); Debug.Log((T)); Debug.Log((H));

        // 3. Match the gate


        //int numQubits = 2;
        //int rows = numQubits;
        //int columns = gate.Length/numQubits;

        if (gate == "x")
        {
            return(X);
        }

        if (gate == "y")
        {
            return(Y);
        }

        if (gate == "z")
        {
            return(Z);
        }

        if (gate == "i")
        {
            return(I);
        }

        if (gate == "s")
        {
            return(S);
        }

        if (gate == "t")
        {
            return(T);
        }

        if (gate == "h")
        {
            return(H);
        }

        if (gate == "cnot" || gate == "cnott")
        {
            return(CNOT);
        }

        if (gate == "cz" || gate == "czt")
        {
            return(CZ);
        }

        if (gate == "swap" || gate == "swapt")
        {
            return(SWAP);
        }
        else
        {
            return(null);
        }
    }
Example #6
0
        public DigitalAudio Embed(DigitalAudio cover, byte[] message)
        {
            BitArray embeddingMessage = CreateEmbeddedMessage(message);
            var      msgLength        = embeddingMessage.Length;
            // Create embeddingMessage
            var value = (float)(Math.PI / 2.0);

            float[] embeddingData = new float[msgLength];
            for (int i = 0; i < msgLength; i++)
            {
                if (embeddingMessage[i])
                {
                    embeddingData[i] = -value;
                }
                else
                {
                    embeddingData[i] = value;
                }
            }

            // Signal
            var coverSignal   = cover.GetSignal();
            var ComplexSignal = coverSignal.Select(x => new Complex32(x, 0)).ToArray();

            double ratio = cover.SamplesInChannel / segmentLength;
            int    N     = (int)Math.Floor(ratio); //Segmnets count
            //---------------------------------------------
            List <Complex32[]> signalSegments = new List <Complex32[]>(N);
            List <float[]>     phases         = new List <float[]>(N);
            List <float[]>     magnitude      = new List <float[]>(N);
            List <float[]>     deltaPhases    = new List <float[]>(N);

            for (int seg = 0; seg < N; seg++)
            {
                //----------Create-----
                signalSegments.Add(new Complex32[segmentLength]);
                phases.Add(new float[segmentLength]);
                magnitude.Add(new float[segmentLength]);
                deltaPhases.Add(new float[segmentLength]);
                //---------------------
                //---Segments init---
                Array.Copy(ComplexSignal, seg * segmentLength, signalSegments[seg], 0, segmentLength); // Signal copy
                //---------------------
                //-------FFT----------
                Fourier.Forward(signalSegments[seg], FourierOptions.Matlab); // Signal transform for each segment
                //--------------------
                for (int j = 0; j < segmentLength; j++)
                {
                    phases[seg][j]    = signalSegments[seg][j].Phase;     //Phases for each segment
                    magnitude[seg][j] = signalSegments[seg][j].Magnitude; //Magnitude for each segment
                }
            }

            var spectrumMiddle = segmentLength / 2;

            // Delta phases
            for (int seg = 1; seg < N; seg++)
            {
                for (int j = 0; j < segmentLength; j++)
                {
                    deltaPhases[seg][j] = phases[seg][j] - phases[seg - 1][j];
                }
            }

            int startIndex         = spectrumMiddle - 1;
            int startSymmetryIndex = spectrumMiddle + 1;

            for (int i = 0; i < msgLength; i++)
            {
                phases[0][startIndex - i]         = embeddingData[i];
                phases[0][startSymmetryIndex + i] = -embeddingData[i]; // symmetry
            }
            // New phases
            for (int seg = 1; seg < N; seg++)
            {
                for (int j = 0; j < segmentLength; j++)
                {
                    phases[seg][j] = phases[seg - 1][j] + deltaPhases[seg][j];
                }
            }

            //Restore signal
            for (int seg = 0; seg < N; seg++)
            {
                for (int j = 0; j < segmentLength; j++)
                {
                    var A     = magnitude[seg][j];
                    var phase = phases[seg][j];
                    signalSegments[seg][j] = Complex32.FromPolarCoordinates(A, phase);
                }
                Fourier.Inverse(signalSegments[seg], FourierOptions.Matlab);
            }

            for (int i = 0; i < N; i++)
            {
                for (int j = 0; j < segmentLength; j++)
                {
                    coverSignal[segmentLength * i + j] = (int)signalSegments[i][j].Real;
                }
            }

            return(cover);
        }