Ejemplo n.º 1
0
        public List <Estimate> Sample()
        {
            // # Now we draw from the distribution to sample from the gaussian prior.
            t = gp.draw_multivariate_gaussian(mC.Item1, mC.Item2);

            return(MakePredictions());
        }
Ejemplo n.º 2
0
        public static PointD[] Straight(double[][] initPoints, CameraParameters param)
        {
            int N = initPoints.Length;

            MathNet.Numerics.LinearAlgebra.Vector <double> C = param.Pos;
            Matrix <double> R = param.R;

            R = M.DenseOfDiagonalArray(new double[] { 1, -1, -1 }) * R;

            MathNet.Numerics.LinearAlgebra.Vector <double>[] Apoints = new MathNet.Numerics.LinearAlgebra.Vector <double> [N];
            for (int i = 0; i < N; i++)
            {
                Apoints[i] = V.DenseOfArray(initPoints[i]);
            }

            MathNet.Numerics.LinearAlgebra.Vector <double>[] Cpoints = new MathNet.Numerics.LinearAlgebra.Vector <double> [N];
            for (int i = 0; i < N; i++)
            {
                Cpoints[i] = R * (Apoints[i] - C);
            }

            PointD[] Bpoints = new PointD[N];
            for (int i = 0; i < N; i++)
            {
                Bpoints[i] = new PointD(Cpoints[i][0] / Cpoints[i][2], Cpoints[i][1] / Cpoints[i][2]);
            }

            return(Bpoints);
        }
Ejemplo n.º 3
0
        public PolynominalRegression(DenseVector xData, DenseVector yData, int order)
        {
            _order = order;
            int n = xData.Count;

            var vandMatrix = new DenseMatrix(xData.Count, order + 1);

            for (int i = 0; i < n; i++)
            {
                vandMatrix.SetRow(i, VandermondeRow(xData[i], _order));
            }

            // var vandMatrixT = vandMatrix.Transpose();
            // 1 variant:
            //_coefs = (vandMatrixT * vandMatrix).Inverse() * vandMatrixT * yData;
            // 2 variant:
            //_coefs = (vandMatrixT * vandMatrix).LU().Solve(vandMatrixT * yData);
            // 3 variant (most fast I think. Possible LU decomposion also can be replaced with one triangular matrix):
            _coefs    = vandMatrix.TransposeThisAndMultiply(vandMatrix).LU().Solve(TransposeAndMult(vandMatrix, yData));
            _coefsDer = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(order);
            for (int i = 0; i < order; i++)
            {
                _coefsDer[i] = _coefs[i + 1] * (i + 1);
            }
        }
Ejemplo n.º 4
0
        public override MathNet.Numerics.LinearAlgebra.Vector <double> Predict(MathNet.Numerics.LinearAlgebra.Vector <double> input)
        {
            //Ax where A is the input and x are the weights

            if (Degree > 1)
            {
                double[] row = new double[input.Count * Degree];

                for (int j = 0; j < input.Count; j++)
                {
                    row[j] = input[j];
                    for (int k = 1; k < Degree; k++)
                    {
                        row[k * input.Count + j] = Math.Pow(row[j], k + 1);
                    }
                }
                input = CreateVector.Dense <double>(row);
            }

            if (bias)
            {
                List <double> data = input.ToList();
                data.Insert(0, 1.0);
                input = CreateVector.Dense <double>(data.ToArray <double>());
            }
            Vector <double> output = CreateVector.Dense <double>(new double[] { input.DotProduct(Weights.Column(0)) });

            return(output);
        }
        public static MathNet.Numerics.LinearAlgebra.Vector <Complex> GenerateTransmissionVector(int size, bool align_to_x)
        {
            MathNet.Numerics.LinearAlgebra.Vector <Complex> t_vector = GenerateTransmissionVector(size);
            Complex align_multiplier = t_vector.Sum().Conjugate();

            align_multiplier /= align_multiplier.Magnitude;
            return(t_vector * align_multiplier);
        }
Ejemplo n.º 6
0
 public MathNet.Numerics.LinearAlgebra.Vector <double>[] BatchApply(MathNet.Numerics.LinearAlgebra.Vector <double>[] zeta)
 {
     MathNet.Numerics.LinearAlgebra.Vector <double>[] t_vectors_est =
         new MathNet.Numerics.LinearAlgebra.Vector <double> [zeta.Length];
     for (int i = 0; i < t_vectors_est.Length; i++)
     {
         t_vectors_est[i] = Apply(zeta[i]);
     }
     return(t_vectors_est);
 }
Ejemplo n.º 7
0
        private MathNet.Numerics.LinearAlgebra.Vector <double> Normalize(MathNet.Numerics.LinearAlgebra.Vector <double> vec)
        {
            double vecTvec = 0;

            for (int i = 0; i < vec.Count; i++)
            {
                vecTvec += vec[i] * vec[i];
            }
            return(vec / Math.Sqrt(vecTvec));
        }
Ejemplo n.º 8
0
    // Compute the optimal rotation and translation vectors
    // Accepts the Matrix4X4 registration matrix, center of mass of source and target point sets
    //outputs the rotationMatrix and the translation vector
    public static void GetTransformationVectors
        (float[,] registrationMatrix, Vector3 SourceCenterOfMass, Vector3 TargeCenterOfMass, out Vector3 TranslationVector, out Quaternion UnityQuat)
    {
        //initialise matrix builder
        MatrixBuilder <float> regMatrix = Matrix <float> .Build;

        //fill matrix builder with contents of our params registrationmatri to create a Matrix
        Matrix <float> reg = regMatrix.DenseOfArray(registrationMatrix);

        //EVD decompose to generate our eignevalues
        Evd <float> registrationevd = reg.Evd();

        //Cholesky<float> registrationevd = reg.Cholesky();
        Console.WriteLine("Symmetric" + registrationevd.IsSymmetric);

        //get inex of maximum eigenvalue for correspond eigenvector
        double maxValue = double.NegativeInfinity;

        //int maxEigenValue = registrationevd.EigenValues.
        int index = 0;

        for (int i = 0; i < registrationevd.EigenValues.Count; i++)
        {
            if (registrationevd.EigenValues[i].Real > maxValue)
            {
                maxValue = registrationevd.EigenValues[i].Real;
                index    = i;
            }
        }

        //Get the eigenvalue index and copy the vector as our unit eigenvector.
        //Our unit EigenVector below
        MathNet.Numerics.LinearAlgebra.Vector <float> unitEigenVector = registrationevd.EigenVectors.Column(index);

        float q0 = unitEigenVector.At(0);
        float q1 = unitEigenVector.At(1);
        float q2 = unitEigenVector.At(2);
        float q3 = unitEigenVector.At(3);

        UnityQuat = new Quaternion(q1, q2, q3, q0);

        Matrix4x4 rotMatrix = Matrix4x4.CreateFromQuaternion(UnityQuat);



        Vector3 y = new Vector3(0, 0, 0);

        //get optimal translation vector
        // Vector3 y = Matrix4x4.Rotate(UnityQuat).MultiplyPoint(SourceCenterOfMass);


        Vector3 optimalTranslation = TargeCenterOfMass - y;

        TranslationVector = optimalTranslation;
    }
Ejemplo n.º 9
0
        public void Reset()
        {
            if (_params.PopulationSize == -1)
            {
                _params.PopulationSize = (int)(4.0 + Math.Floor(3.0 * Math.Log(_numParams)));
            }
            if (_params.NumParents == -1)
            {
                _params.NumParents = _params.PopulationSize / 2;
            }
            _mutationPower = _params.MutationPower;

            _weights = MathNet.Numerics.LinearAlgebra.
                       Vector <double> .Build.Dense(_params.NumParents);

            for (int i = 0; i < _params.NumParents; i++)
            {
                _weights[i] = Math.Log(_params.NumParents + 0.5) - Math.Log(i + 1);
            }
            _weights /= _weights.Sum();
            double sum_weights = _weights.Sum();
            double sum_squares = _weights.Sum(x => x * x);

            _mueff = sum_weights * sum_weights / sum_squares;

            _mean = LA.Vector <double> .Build.Dense(_numParams);

            if (_bestIndividual != null)
            {
                for (int i = 0; i < _numParams; i++)
                {
                    _mean[i] = _bestIndividual.ParamVector[i];
                }
            }
            Console.WriteLine("RESET");
            Console.WriteLine(_mean);

            _cc  = (4 + _mueff / _numParams) / (_numParams + 4 + 2 * _mueff / _numParams);
            _cs  = (_mueff + 2) / (_numParams + _mueff + 5);
            _c1  = 2 / (Math.Pow(_numParams + 1.3, 2) + _mueff);
            _cmu = Math.Min(1 - _c1,
                            2 * (_mueff - 2 + 1 / _mueff) / (Math.Pow(_numParams + 2, 2) + _mueff));
            _damps = 1 + 2 * Math.Max(0, Math.Sqrt((_mueff - 1) / (_numParams + 1)) - 1) + _cs;
            _chiN  = Math.Sqrt(_numParams) *
                     (1.0 - 1.0 / (4.0 * _numParams) + 1.0 / (21.0 * Math.Pow(_numParams, 2)));

            _pc = LA.Vector <double> .Build.Dense(_numParams);

            _ps = LA.Vector <double> .Build.Dense(_numParams);

            _C = new DecompMatrix(_numParams);

            _individualsEvaluated = 0;
        }
        public static MathNet.Numerics.LinearAlgebra.Vector <Complex>[] GenerateTransmissionVectorsArray(int size, int length, bool align)
        {
            MathNet.Numerics.LinearAlgebra.Vector <Complex>[] t_vectors =
                new MathNet.Numerics.LinearAlgebra.Vector <Complex> [length];

            for (int i = 0; i < length; i++)
            {
                t_vectors[i] = GenerateTransmissionVector(size, align);
            }

            return(t_vectors);
        }
Ejemplo n.º 11
0
        /// <summary>
        ///     map a polynomial with roots at least "barrier" OUTSIDE the unit circle to a cube vector of dimension equal to the
        ///     order of the polynomial,
        ///     assuming the zero-order coefficient is equal to 1.0
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static MathNet.Numerics.LinearAlgebra.Vector <double> MapToCube(
            this MathNet.Numerics.LinearAlgebra.Vector <double> p, double barrier)
        {
            var allRoots = p.Roots();

            StripConjugates(allRoots);
            var order = p.Count - 1;
            var cube  = MathNet.Numerics.LinearAlgebra.Vector <double> .Build.Dense(order);

            var complexRoots = new List <Complex>();
            var realRoots    = new List <double>();

            var j = 0;

            for (var i = 0; i < allRoots.Count; ++i)
            {
                if (Math.Abs(allRoots[i].Imaginary) > epsilon)
                {
                    complexRoots.Add(1.0 / allRoots[i]);
                }
                else
                {
                    realRoots.Add(1.0 / allRoots[i].Real);
                }
            }

            for (var i = 0; i < complexRoots.Count; ++i)
            {
                cube[j]     = complexRoots[i].Real;
                cube[j + 1] = Math.Abs(complexRoots[i].Imaginary);
                j          += 2;
            }

            for (var i = 0; i < realRoots.Count;)
            {
                if (realRoots.Count - i > 1)
                {
                    cube[j]     = realRoots[i];
                    cube[j + 1] = (realRoots[i + 1] - 1.0) / 2.0; // between -1 and 0
                    i          += 2;
                    j          += 2;
                }
                else
                {
                    cube[j] = realRoots[i];
                    ++i;
                    ++j;
                }
            }

            return((cube + 1.0) * 0.5);
        }
Ejemplo n.º 12
0
        public static Matrix4x4 ComputeTransformMatrix(int width, int height, Point newTopLeft, Point newTopRight, Point newBottomLeft, Point newBottomRight)
        {
            //FIX - generalize the calculation of A & B matrices into function - code too W E T rn
            //compute A matrix
            Matrix <double> solveA = Matrix <double> .Build.DenseOfArray(new double[, ] {
                { 0, width, width },
                { 0, 0, height },
                { 1, 1, 1 }
            });

            MathNet.Numerics.LinearAlgebra.Vector <double> augmentA = MathNet.Numerics.LinearAlgebra.Vector <double> .Build.Dense(new double[]
                                                                                                                                  { 0, height, 1 }
                                                                                                                                  );

            MathNet.Numerics.LinearAlgebra.Vector <double> coefficientsA = solveA.Solve(augmentA);

            Matrix <double> A = Matrix <double> .Build.DenseOfArray(new double[, ] {
                { 0, coefficientsA[1] * width, coefficientsA[2] * width },
                { 0, 0, coefficientsA[2] * height },
                { coefficientsA[0], coefficientsA[1], coefficientsA[2] }
            });

            //compute B matrix
            Matrix <double> solveB = Matrix <double> .Build.DenseOfArray(new double[, ] {
                { newTopLeft.X, newTopRight.X, newBottomRight.X },
                { newTopLeft.Y, newTopRight.Y, newBottomRight.Y },
                { 1, 1, 1 }
            });

            MathNet.Numerics.LinearAlgebra.Vector <double> augmentB = MathNet.Numerics.LinearAlgebra.Vector <double> .Build.Dense(new double[]
                                                                                                                                  { newBottomLeft.X, newBottomLeft.Y, 1 }
                                                                                                                                  );

            MathNet.Numerics.LinearAlgebra.Vector <double> coefficientsB = solveB.Solve(augmentB);

            Matrix <double> B = Matrix <double> .Build.DenseOfArray(new double[, ] {
                { coefficientsB[0] * newTopLeft.X, coefficientsB[1] * newTopRight.X, coefficientsB[2] * newBottomRight.X },
                { coefficientsB[0] * newTopLeft.Y, coefficientsB[1] * newTopRight.Y, coefficientsB[2] * newBottomRight.Y },
                { coefficientsB[0], coefficientsB[1], coefficientsB[2] }
            });

            //compute matrix C = B * A^-1
            Matrix <double> AInv = A.Inverse();
            Matrix <double> C    = B * AInv;

            //return the homogeneous transform matrix based on C
            return(new Matrix4x4((float)C[0, 0], (float)C[1, 0], 0, (float)C[2, 0],
                                 (float)C[0, 1], (float)C[1, 1], 0, (float)C[2, 1],
                                 0, 0, 1, 0,
                                 (float)C[0, 2], (float)C[1, 2], 0, (float)C[2, 2]));
        }
Ejemplo n.º 13
0
        public static void WriteToCSV(this MathNet.Numerics.LinearAlgebra.Vector <double> vec, string path)
        {
            CsvHelper.Configuration.Configuration cfg =
                new CsvHelper.Configuration.Configuration(CultureInfo.InvariantCulture);

            using (StreamWriter sw = new StreamWriter(path))
                using (CsvWriter cw = new CsvWriter(sw, cfg))
                {
                    for (int e = 0; e < vec.Count; e++)
                    {
                        cw.WriteField(e);
                        cw.WriteField(vec[e]);
                        cw.NextRecord();
                    }
                }
        }
        public static MathNet.Numerics.LinearAlgebra.Vector <Complex> GenerateTransmissionVector(int size)
        {
            // The transmission vector is normalized according to Vellekoop thesis (p. 93).
            // Normalization factor is 1 / sqrt(size). Additional factor 1 / sqrt(2) appears
            // due to construction of the transmission vector of two Normal random numbers.
            MathNet.Numerics.LinearAlgebra.Vector <Complex> tm =
                MathNet.Numerics.LinearAlgebra.Vector <Complex> .Build.Dense(size);

            double denom = Math.Sqrt(2.0 * size);

            for (int i = 0; i < size; i++)
            {
                tm[i] = new Complex(Normal.Sample(0.0, 1.0) / denom,
                                    Normal.Sample(0.0, 1.0) / denom);
            }
            return(tm);
        }
Ejemplo n.º 15
0
        public static void PCA(DenseMatrix input, out MathNet.Numerics.LinearAlgebra.Vector <double> latent, out Matrix <double> score, out Matrix <double> coeff)
        {
            int n = input.RowCount;
            int p = input.ColumnCount;

            //de-mean input
            var tmpInput = DenseMatrix.OfMatrix(input);

            for (int i = 0; i < tmpInput.ColumnCount; i++)
            {
                double avg = tmpInput.Column(i).Average();
                tmpInput.SetColumn(i, tmpInput.Column(i).Subtract(avg));
            }

            var svd      = tmpInput.Svd(true);
            var sigma    = svd.S;
            var tmpCoeff = svd.VT.Transpose();

            score = DenseMatrix.Create(n, p, (_, __) => 0);
            var U = svd.U.SubMatrix(0, n, 0, p);

            for (int i = 0; i < U.RowCount; i++)
            {
                score.SetRow(i, U.Row(i).PointwiseMultiply(sigma));
            }

            sigma  = sigma.Divide(Math.Sqrt(n - 1));
            latent = sigma.PointwiseMultiply(sigma);

            //give the largest absolute value in each column a positive sign
            var maxIndices = tmpCoeff.EnumerateColumns().Select(x => x.AbsoluteMaximumIndex());
            var colSigns   = maxIndices.Select((x, j) => Math.Sign(tmpCoeff[x, j])).ToList();

            for (int j = 0; j < tmpCoeff.ColumnCount; j++)
            {
                tmpCoeff.SetColumn(j, tmpCoeff.Column(j) * colSigns[j]);
                score.SetColumn(j, score.Column(j) * colSigns[j]);
            }

            coeff = tmpCoeff;
        }
Ejemplo n.º 16
0
        public Wrapper(List <Tuple <double, double> > points = null, double scale = 100, IKernel kernel = null)
        {
            _scale = scale;
            // kernel = OrnsteinKernel(1.0)
            _kernel = kernel ?? new Kernel(2.0, 6.0, 0.0, 0.0);

            if (points == null)
            {
                axpts = new double[10];
                Normal.Samples(rand, axpts, 0, 2);
            }
            else
            {
                axpts = points.Select(_ => _.Item2).ToArray();
                t     = Vector <double> .Build.DenseOfArray(points.Select(_ => _.Item1).ToArray());

                AddMeasurements();
            }

            Initialise();
        }
Ejemplo n.º 17
0
        private void EstimateCore(Microphone[] microphones, int sampleRate, int frameLength, double maxSpace)
        {
            var estimator = new GeneralPerFrequencyDoaEstimator2D(microphones, sampleRate, frameLength);

            for (var deg = 1; deg < 360; deg++)
            {
                var expectedDoa = Math.PI * deg / 180 - Math.PI;

                MathNet.Numerics.LinearAlgebra.Vector <double> dv = DenseVector.OfArray(new double[]
                {
                    Math.Cos(expectedDoa),
                    Math.Sin(expectedDoa),
                    0
                });

                var dfts = new Complex[frameLength][];
                for (var ch = 0; ch < microphones.Length; ch++)
                {
                    var distance         = microphones[ch].Position * dv;
                    var delaySampleCount = -distance / AcousticConstants.SoundSpeed * sampleRate;
                    var delayFilter      = Filtering.CreateFrequencyDomainDelayFilter(frameLength, delaySampleCount);
                    var dft = new Complex[frameLength];
                    Array.Copy(delayFilter, dft, delayFilter.Length);
                    dfts[ch] = dft;
                }

                var actualDoa = estimator.Estimate(dfts);

                for (var w = 1; w < frameLength / 2 + 1; w++)
                {
                    var waveLength = (double)frameLength / w / sampleRate * AcousticConstants.SoundSpeed;

                    if (maxSpace + 1.0E-6 < waveLength / 2)
                    {
                        Assert.AreEqual(expectedDoa, actualDoa[w], 1.0E-6);
                    }
                }
            }
        }
Ejemplo n.º 18
0
        public Gate(string name, int nb_entries, Matrix <Complex> matrix)
        {
            if (matrix.RowCount != matrix.ColumnCount || !Stuff.IsPowerOfTwo(matrix.ColumnCount))
            {
                throw new ArgumentException("Gate Matrix must be 2^n rows and 2^n columns");
            }

            // put identity on zeroed rows
            MathNet.Numerics.LinearAlgebra.Vector <Complex> row_absums = matrix.RowAbsoluteSums();
            for (int i = 0; i < matrix.RowCount; i++)
            {
                if (row_absums[i] == Complex.Zero)
                {
                    matrix[i, i] = Complex.One;
                }
            }

            this.NbEntries = nb_entries;
            this.Matrix    = matrix.NormalizeRows(2.0);

            this.Name = name;
        }
Ejemplo n.º 19
0
        //Vector stands for the coefficients of a polynomial

        public static List <Complex> Roots(this MathNet.Numerics.LinearAlgebra.Vector <double> p)
        {
            var allRoots = new List <Complex>();

            // build matrix whose char. polynomial is the target polynomial
            var sz = p.Count - 1;

            while (Math.Abs(p[sz]) < epsilon && sz > 0)
            {
                --sz;
            }
            if (sz > 0) // it has to be bigger than zero to have any roots at all
            {
                var highestCoeff = p[sz];
                var m            = Matrix <double> .Build.Dense(sz, sz);

                for (var i = 0; i < sz - 1; ++i)
                {
                    m[i, i + 1] = 1.0;
                }
                for (var i = 0; i < sz; ++i)
                {
                    m[sz - 1, i] = -p[i] / highestCoeff;
                }

                var ed = m.Evd(); //new EigenvalueDecomposition(m);
                //ed.Solve(m);

                for (var i = 0; i < sz; ++i)
                {
                    var c = new Complex(ed.EigenValues[i].Real, ed.EigenValues[i].Imaginary);
                    allRoots.Add(c);
                }
            }

            return(allRoots);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// ranks a given document using semantic algorithem and BM25 algorithem
        /// </summary>
        /// <param name="R"></param>
        /// <param name="N"></param>
        /// <param name="k1"></param>
        /// <param name="k2"></param>
        /// <param name="b"></param>
        /// <param name="queryWordsData"></param>
        /// <param name="dl"></param>
        /// <param name="avdl"></param>
        /// <param name="docId"></param>
        /// <param name="q"></param>
        /// <param name="Dk_T"></param>
        /// <param name="docsMap"></param>
        /// <returns></returns>
        public static double rankDoc(int R, int N, double k1, double k2, double b, Dictionary <string /*word in query*/, queryWordData /*struct of data*/> queryWordsData, double dl, double avdl, string docId, MathNet.Numerics.LinearAlgebra.Vector <double> q, MathNet.Numerics.LinearAlgebra.Matrix <double> Dk_T, Dictionary <string, int> docsMap)
        {
            double rank;

            rank = BM25(R, N, k1, k2, b, queryWordsData, dl, avdl, docId);/*LSI(docId,q, Dk_T, docsMap);*/
            return(rank);
        }
Ejemplo n.º 21
0
        /// <summary>
        ///     translates a cube into a polynomial with inverse-roots at least "barrier" inside the unit circle, and
        ///     zero-order coefficient = 1.0
        /// </summary>
        /// <returns></returns>
        public static MathNet.Numerics.LinearAlgebra.Vector <double> MapFromCube(
            MathNet.Numerics.LinearAlgebra.Vector <double> originalCube, double barrier)
        {
            var invRoots = new List <Complex>();

            var cube = originalCube * 2 - 1;

            for (var i = 0; i < cube.Count;)
            {
                if (i < cube.Count - 1) // we can grab a pair
                {
                    var x1 = cube[i];
                    var y1 = cube[i + 1];
                    if (y1 > 0) // it's a conjugate pair
                    {
                        invRoots.Add(new Complex(x1, y1));
                        invRoots.Add(new Complex(x1, -y1));
                    }
                    else
                    {
                        invRoots.Add(new Complex(x1, 0));
                        invRoots.Add(new Complex(2 * y1 + 1, 0));
                    }

                    i += 2;
                }
                else
                {
                    invRoots.Add(new Complex(cube[i], 0));
                    ++i;
                }
            }

            for (var i = 0; i < invRoots.Count; ++i)
            {
                // make sure norm is less than 1-epsilon, if not, invert
                var r     = invRoots[i].Magnitude;
                var theta = invRoots[i].Phase;
                if (r > 1 - barrier)
                {
                    r           = 1.0 / (r + 2 * barrier);
                    invRoots[i] = new Complex(r, theta);
                }
            }

            // now rebuild polynomial from roots
            var retval = new Complex[invRoots.Count + 1];

            retval[0] = 1.0;
            for (var i = 0; i < invRoots.Count; ++i)
            {
                for (var j = invRoots.Count; j > 0; --j)
                {
                    retval[j] -= invRoots[i] * retval[j - 1];
                }
            }

            var p = MathNet.Numerics.LinearAlgebra.Vector <double> .Build
                    .Dense(invRoots.Count + 1); //new Polynomial(invRoots.Count);

            for (var i = 0; i <= invRoots.Count; ++i)
            {
                if (Math.Abs(retval[i].Imaginary) > epsilon)
                {
                    p[i] = retval[i].Real;
                }
                //throw new ApplicationException("Unmapped polynomial has complex coefficients.");
                else
                {
                    p[i] = retval[i].Real;
                }
            }
            return(p);
        }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            //int slm_size = 256;
            //int t_vecs_count = 1024;
            int slm_size     = 64;  // Set the number of the SLM channels
            int t_vecs_count = 512; // Set the number of transmission vectors for the filter calculation
            // SLM: 64, TVEC: 512
            // SLM: 128, TVEC: 1024
            // SLM: 256, TVEC: 2048
            // SLM: 512, TVEC: 4096
            Complex e_field    = new Complex(1.0, 0.0); // Incident electric field
            double  wavelength = 632.8e-9;
            //Complex e_inc = new Complex(1.0 / Math.Sqrt(2.0), 0.0);
            double  e_inc_factor = 1.0 / 4.0; // Factor that increases or decreases incident intensity
            Complex e_inc        = new Complex(1.0 * Math.Sqrt(e_inc_factor), 0.0);

            int    det_rows = 1, det_cols = 1;
            double temperature = 325.15;
            //double pga_gain = 2.0;
            //double integration_time = 0.035;
            double pga_gain         = 1.0 * 4.0;  // Gain of the image sensor
            double integration_time = 1.0 / 25.0; //0.040 / 128.0;

            // Maximum photon shot noise without the influence of dark current
            // e_inc_factor = 8.0 or 9.0
            // pga_gain = 64.0
            // integration_time = 1.0 / 8000.0

            // Maximum dark current
            // e_inc_factor = 1.0 / 4.0
            // pga_gain = 4.0
            // integration_time = 1.0 / 25.0

            double planck_const = 6.62607004e-34;
            double light_speed  = 299792458.0;
            double ph_energy    = planck_const * light_speed / wavelength; // Photon energy
            double poynting_vec = e_inc.MagnitudeSquared() / (2.0 * 377);
            double ph_flux      = poynting_vec / ph_energy;                // Photon flux

            double q_eff            = 0.8;
            double det_area         = 5.0e-6 * 5.0e-6;
            double sensor_electrons = ph_flux * q_eff * det_area * integration_time;

            double well_capacity = 20.0e3;
            double intensity_dn  = sensor_electrons / well_capacity * 255.0;


            Console.WriteLine("Photon flux [1/(m^2 s)]: {0:E4}", ph_flux);
            Console.WriteLine("Generated electrons:     {0}", Math.Round(sensor_electrons, 0));
            Console.WriteLine("Intensity [DN]:          {0}", Math.Round(intensity_dn, 0));

            // Create functions that calculate intensity directly and simulate an image sensor
            Func <double, double> ideal_detector = new Func <double, double>((input_intensity) => {
                return(input_intensity);
                //double poynting_vec_local = input_intensity / (2.0 * 377.0);
                //double ph_flux_local = poynting_vec_local / ph_energy;
                //double sensor_electrons_local = ph_flux_local * q_eff * det_area * integration_time;
                //double intensity_dn_local = sensor_electrons_local / well_capacity * 255.0;
                //return intensity_dn_local;
            });
            Func <double, double> experimental_detector = new Func <double, double>((input_intensity) => {
                //double poynting_vec_local = input_intensity / (2.0 * 377.0);
                //double ph_flux_local = poynting_vec_local / ph_energy;
                //double sensor_eklectrons = ph_flux_local * q_eff * det_area * integration_time;
                //if (sensor_eklectrons == 0.0)
                //    return 0.0;
                //else if (sensor_eklectrons < 1000.0)
                //    return Poisson.Sample(sensor_eklectrons);
                //else
                //    return Normal.Sample(sensor_eklectrons, Math.Sqrt(sensor_eklectrons));

                double signal = Normal.Sample(input_intensity, 1.0);
                if (signal < 0.0)
                {
                    return(0.0);
                }
                else
                {
                    return(signal);
                }

                //return ContinuousUniform.Sample(0.1, 1.0);
            });
            ImageSensor sensor_w_noise = ImageSensorConstructor.CustomSensor(
                det_rows, det_cols, temperature, pga_gain, integration_time, true);
            Func <double, double> advanced_detector = new Func <double, double>((input_intensity) => {
                double poynting_vec_local = input_intensity / (2.0 * 377.0);
                double ph_flux_local      = poynting_vec_local / ph_energy;
                return(SimulateCamera(sensor_w_noise, ph_flux_local));
            });
            ImageSensor sensor_wo_noise = ImageSensorConstructor.CustomSensor(
                det_rows, det_cols, temperature, pga_gain, integration_time, false);
            Func <double, double> advanced_detector_noiseless = new Func <double, double>((input_intensity) => {
                double poynting_vec_local = input_intensity / (2.0 * 377.0);
                double ph_flux_local      = poynting_vec_local / ph_energy;
                return(SimulateCamera(sensor_wo_noise, ph_flux_local));
            });

            //double conversion_coefficient = SimulateCamera(sensor_wo_noise, ph_flux);
            double conversion_coefficient = advanced_detector_noiseless(e_inc.MagnitudeSquared());

            Console.WriteLine("Conversion coefficient: {0}", conversion_coefficient);
            Console.WriteLine("w/o noise: {0}", advanced_detector_noiseless(e_inc.MagnitudeSquared()));
            Console.WriteLine("w/  noise: {0}", advanced_detector(e_inc.MagnitudeSquared()));
            //for (int i = 0; i < 100; i++)
            //    Console.WriteLine(advanced_detector(e_inc.MagnitudeSquared()));
            ImageSensor sensor_w_noise_tp = ImageSensorConstructor.CustomSensor(
                512, 512, temperature, pga_gain, integration_time, true);
            ImageSensor sensor_wo_noise_tp = ImageSensorConstructor.CustomSensor(
                512, 512, temperature, pga_gain, integration_time, false);

            ImageSensorConstructor.GenerateTestPattern(
                sensor_w_noise_tp, 2.0 * e_inc.MagnitudeSquared() / (2.0 * 377.0) / ph_energy)
            .WriteToBinary("d:/Wavefront shaping/Tasks/01_CCD_noise_Wiener_filter/sensor_w_noise_tp.raw");
            ImageSensorConstructor.GenerateTestPattern(
                sensor_wo_noise_tp, 2.0 * e_inc.MagnitudeSquared() / (2.0 * 377.0) / ph_energy)
            .WriteToBinary("d:/Wavefront shaping/Tasks/01_CCD_noise_Wiener_filter/sensor_wo_noise_tp.raw");

            // Create a set of transmission matrices for Wiener filter calculation
            Console.Write("Preparing transmission vectors... ");
            MathNet.Numerics.LinearAlgebra.Vector <Complex>[] t_vectors =
                TransmissionMatrix.GenerateTransmissionVectorsArray(slm_size, t_vecs_count, true);

            //List<mn_linalg::Vector<Complex>> t_vectors_filtered = new List<mn_linalg.Vector<Complex>>(t_vectors.Length);
            //for (int i = 0; i < t_vectors.Length; i++)
            //{
            //    if (experimental_detector((t_vectors[i].Sum() * e_inc).MagnitudeSquared()) != 0.0)
            //    {
            //        t_vectors_filtered.Add(t_vectors[i]);
            //    }
            //}
            //t_vectors = t_vectors_filtered.ToArray();

            //for (int i = 0; i < t_vectors.Length; i++)
            //    Console.WriteLine((t_vectors[i] * t_vectors[i].Conjugate()).MagnitudeSquared());
            Console.WriteLine("DONE");

            Console.Write("Preparing transmission vectors for filter verification... ");
            MathNet.Numerics.LinearAlgebra.Vector <Complex>[] t_vectors_fverif =
                TransmissionMatrix.GenerateTransmissionVectorsArray(slm_size, t_vecs_count, true);
            Console.WriteLine("DONE");

            //mn_linalg::Vector<Complex>[] t_vectors_all =
            //    TransmissionMatrix.GenerateTransmissionVectorsArray(slm_size, 2 * t_vecs_count, true);
            //t_vectors = t_vectors_all.Take(t_vecs_count).ToArray();
            //t_vectors_fverif = t_vectors_all.Skip(t_vecs_count).Take(t_vecs_count).ToArray();


            //List<mn_linalg::Vector<Complex>> t_vectors_fverif_filtered = new List<mn_linalg.Vector<Complex>>(t_vectors_fverif.Length);
            //for (int i = 0; i < t_vectors_fverif.Length; i++)
            //{
            //    if (experimental_detector((t_vectors_fverif[i].Sum() * e_inc).MagnitudeSquared()) != 0.0)
            //    {
            //        t_vectors_fverif_filtered.Add(t_vectors_fverif[i]);
            //    }
            //}
            //t_vectors_fverif = t_vectors_fverif_filtered.ToArray();

            Analyzer a1 = new Analyzer(experimental_detector);

            a1.Analyze(t_vectors, t_vectors_fverif, e_inc, true);
            a1.PrintResults();

            a1.Filter.GammaZeta.WriteToBinary("d:/Wavefront shaping/Tasks/01_CCD_noise_Wiener_filter/gamma_zeta.raw");
            a1.Filter.GammaZeta.Svd().W.Diagonal().WriteToCSV("d:/Wavefront shaping/Tasks/01_CCD_noise_Wiener_filter/gamma_zeta_sing_vals.csv");
            a1.Filter.GammaZetaEig.WriteToCSV("d:/Wavefront shaping/Tasks/01_CCD_noise_Wiener_filter/gamma_zeta_eig.csv");

            string line = "";
            int    num  = 0;

            while (line != "q")
            {
                Console.Write("Number of a vector to save or q tu quit: ");
                line = Console.ReadLine();
                if (!int.TryParse(line, out num))
                {
                    continue;
                }
                t_vectors[num].WriteToCSV("d:/Wavefront shaping/Tasks/01_CCD_noise_Wiener_filter/t_vector_original.csv");
                a1.TransmissionVectorsFiltered[num].WriteToCSV(
                    "d:/Wavefront shaping/Tasks/01_CCD_noise_Wiener_filter/t_vector_filtered.csv");
                a1.HResults[num].TransmissionVectorEstimated.WriteToCSV(
                    "d:/Wavefront shaping/Tasks/01_CCD_noise_Wiener_filter/t_vector_estimated.csv");
            }

            return;

            Console.Write("Simulating focusing... ");
            HadamardResult[] hr_ideal_detector        = HadamardAlgorithm.BatchSimulate(ideal_detector, t_vectors, e_inc);
            HadamardResult[] hr_sensor_w_noise        = HadamardAlgorithm.BatchSimulate(advanced_detector, t_vectors, e_inc, true);
            HadamardResult[] hr_sensor_w_noise_fverif = HadamardAlgorithm.BatchSimulate(advanced_detector, t_vectors_fverif, e_inc, true);
            HadamardResult[] hr_sensor_wo_noise       = HadamardAlgorithm.BatchSimulate(advanced_detector_noiseless, t_vectors, e_inc, true);
            Console.WriteLine("DONE");

            Console.Write("Scaling output... ");
            for (int i = 0; i < hr_sensor_wo_noise.Length; i++)
            {
                hr_ideal_detector[i].TransmissionVectorEstimated /= Math.Sqrt(e_inc_factor);
                hr_ideal_detector[i].Zeta /= Math.Sqrt(e_inc_factor);
                hr_sensor_wo_noise[i].TransmissionVectorEstimated /= Math.Sqrt(conversion_coefficient);
                hr_sensor_wo_noise[i].Zeta /= Math.Sqrt(conversion_coefficient);
                hr_sensor_w_noise[i].TransmissionVectorEstimated /= Math.Sqrt(conversion_coefficient);
                hr_sensor_w_noise[i].Zeta /= Math.Sqrt(conversion_coefficient);

                hr_sensor_w_noise_fverif[i].TransmissionVectorEstimated /= Math.Sqrt(conversion_coefficient);
                hr_sensor_w_noise_fverif[i].Zeta /= Math.Sqrt(conversion_coefficient);
            }
            Console.WriteLine("DONE");

            // Build Wiener filters
            Console.Write("Building Wiener filters... ");
            WienerFilter wf_ideal_detector  = new WienerFilter(hr_ideal_detector, t_vectors);
            WienerFilter wf_sensor_w_noise  = new WienerFilter(hr_sensor_w_noise, t_vectors);
            WienerFilter wf_sensor_wo_noise = new WienerFilter(hr_sensor_wo_noise, t_vectors);

            Console.WriteLine("DONE");

            Console.Write("Filtering input data... ");
            MathNet.Numerics.LinearAlgebra.Vector <double>[] t_vectors_est_ideal_detector =
                wf_ideal_detector.BatchApply(hr_ideal_detector.Select(e => e.Zeta.Real()).ToArray());
            //MathNet.Numerics.LinearAlgebra.Vector<double>[] t_vectors_est_sensor_w_noise =
            //    wf_sensor_w_noise.BatchApply(hr_ideal_detector.Select(e => e.Zeta.Real()).ToArray());
            //MathNet.Numerics.LinearAlgebra.Vector<double>[] t_vectors_est_sensor_wo_noise =
            //    wf_sensor_wo_noise.BatchApply(hr_ideal_detector.Select(e => e.Zeta.Real()).ToArray());
            MathNet.Numerics.LinearAlgebra.Vector <double>[] t_vectors_est_sensor_w_noise =
                wf_sensor_w_noise.BatchApply(hr_sensor_w_noise.Select(e => e.Zeta.Real()).ToArray());
            MathNet.Numerics.LinearAlgebra.Vector <double>[] t_vectors_est_sensor_wo_noise =
                wf_sensor_wo_noise.BatchApply(hr_sensor_wo_noise.Select(e => e.Zeta.Real()).ToArray());

            MathNet.Numerics.LinearAlgebra.Vector <double>[] t_vectors_est_sensor_w_noise_fverif =
                wf_sensor_w_noise.BatchApply(hr_sensor_w_noise_fverif.Select(e => e.Zeta.Real()).ToArray());
            Console.WriteLine("DONE");

            Console.Write("Calculating correct estimation statistics... ");
            double hr_ideal_detector_cs =
                hr_ideal_detector.Average(new Func <HadamardResult, double>(e => (double)e.CorrectSignsNumber));
            double hr_sensor_w_noise_cs =
                hr_sensor_w_noise.Average(new Func <HadamardResult, double>(e => (double)e.CorrectSignsNumber));
            double hr_sensor_wo_noise_cs =
                hr_sensor_wo_noise.Average(new Func <HadamardResult, double>(e => (double)e.CorrectSignsNumber));

            double hr_sensor_w_noise_cs_fverif =
                hr_sensor_w_noise_fverif.Average(new Func <HadamardResult, double>(e => (double)e.CorrectSignsNumber));

            double hr_ideal_detector_cs_f  = 0.0;
            double hr_sensor_w_noise_cs_f  = 0.0;
            double hr_sensor_wo_noise_cs_f = 0.0;

            double hr_sensor_w_noise_cs_ffverif = 0.0;

            for (int i = 0; i < t_vectors.Length; i++)
            {
                for (int j = 0; j < t_vectors[j].Count; j++)
                {
                    if (Math.Sign(t_vectors_est_sensor_w_noise[i][j]) == Math.Sign(t_vectors[i][j].Real))
                    {
                        hr_sensor_w_noise_cs_f += 1.0;
                    }
                    if (Math.Sign(t_vectors_est_sensor_wo_noise[i][j]) == Math.Sign(t_vectors[i][j].Real))
                    {
                        hr_sensor_wo_noise_cs_f += 1.0;
                    }
                    if (Math.Sign(t_vectors_est_ideal_detector[i][j]) == Math.Sign(t_vectors[i][j].Real))
                    {
                        hr_ideal_detector_cs_f += 1.0;
                    }

                    if (Math.Sign(t_vectors_est_sensor_w_noise_fverif[i][j]) == Math.Sign(t_vectors_fverif[i][j].Real))
                    {
                        hr_sensor_w_noise_cs_ffverif += 1.0;
                    }
                }
            }
            hr_ideal_detector_cs_f       /= t_vectors.Length;
            hr_sensor_w_noise_cs_f       /= t_vectors.Length;
            hr_sensor_wo_noise_cs_f      /= t_vectors.Length;
            hr_sensor_w_noise_cs_ffverif /= t_vectors_fverif.Length;


            // Count wrong to right and right to wrong estimations
            double hr_ideal_detector_cs_rtw  = 0.0;
            double hr_ideal_detector_cs_wtr  = 0.0;
            double hr_sensor_w_noise_cs_rtw  = 0.0;
            double hr_sensor_w_noise_cs_wtr  = 0.0;
            double hr_sensor_wo_noise_cs_rtw = 0.0;
            double hr_sensor_wo_noise_cs_wtr = 0.0;

            double hr_sensor_w_noise_cs_fverif_rtw = 0.0;
            double hr_sensor_w_noise_cs_fverif_wtr = 0.0;

            for (int i = 0; i < t_vectors.Length; i++)
            {
                for (int j = 0; j < t_vectors[j].Count; j++)
                {
                    if (Math.Sign(hr_ideal_detector[i].TransmissionVectorEstimated[j].Real) != Math.Sign(t_vectors[i][j].Real) &&
                        Math.Sign(t_vectors_est_ideal_detector[i][j]) == Math.Sign(t_vectors[i][j].Real))
                    {
                        hr_ideal_detector_cs_wtr += 1.0;
                    }
                    else if (Math.Sign(hr_ideal_detector[i].TransmissionVectorEstimated[j].Real) == Math.Sign(t_vectors[i][j].Real) &&
                             Math.Sign(t_vectors_est_ideal_detector[i][j]) != Math.Sign(t_vectors[i][j].Real))
                    {
                        hr_ideal_detector_cs_rtw += 1.0;
                    }

                    if (Math.Sign(hr_sensor_wo_noise[i].TransmissionVectorEstimated[j].Real) != Math.Sign(t_vectors[i][j].Real) &&
                        Math.Sign(t_vectors_est_sensor_wo_noise[i][j]) == Math.Sign(t_vectors[i][j].Real))
                    {
                        hr_sensor_wo_noise_cs_wtr += 1.0;
                    }
                    else if (Math.Sign(hr_sensor_wo_noise[i].TransmissionVectorEstimated[j].Real) == Math.Sign(t_vectors[i][j].Real) &&
                             Math.Sign(t_vectors_est_sensor_wo_noise[i][j]) != Math.Sign(t_vectors[i][j].Real))
                    {
                        hr_sensor_wo_noise_cs_rtw += 1.0;
                    }

                    if (Math.Sign(hr_sensor_w_noise[i].TransmissionVectorEstimated[j].Real) != Math.Sign(t_vectors[i][j].Real) &&
                        Math.Sign(t_vectors_est_sensor_w_noise[i][j]) == Math.Sign(t_vectors[i][j].Real))
                    {
                        hr_sensor_w_noise_cs_wtr += 1.0;
                    }
                    else if (Math.Sign(hr_sensor_w_noise[i].TransmissionVectorEstimated[j].Real) == Math.Sign(t_vectors[i][j].Real) &&
                             Math.Sign(t_vectors_est_sensor_w_noise[i][j]) != Math.Sign(t_vectors[i][j].Real))
                    {
                        hr_sensor_w_noise_cs_rtw += 1.0;
                    }


                    if (Math.Sign(hr_sensor_w_noise_fverif[i].TransmissionVectorEstimated[j].Real) != Math.Sign(t_vectors_fverif[i][j].Real) &&
                        Math.Sign(t_vectors_est_sensor_w_noise_fverif[i][j]) == Math.Sign(t_vectors_fverif[i][j].Real))
                    {
                        hr_sensor_w_noise_cs_fverif_wtr += 1.0;
                    }
                    else if (Math.Sign(hr_sensor_w_noise_fverif[i].TransmissionVectorEstimated[j].Real) == Math.Sign(t_vectors_fverif[i][j].Real) &&
                             Math.Sign(t_vectors_est_sensor_w_noise_fverif[i][j]) != Math.Sign(t_vectors_fverif[i][j].Real))
                    {
                        hr_sensor_w_noise_cs_fverif_rtw += 1.0;
                    }
                }
            }

            MathNet.Numerics.LinearAlgebra.Vector <Complex>[] slm_sensor_w_noise = t_vectors_est_sensor_w_noise.Select(e => {
                MathNet.Numerics.LinearAlgebra.Vector <Complex> res =
                    MathNet.Numerics.LinearAlgebra.Vector <Complex> .Build.Dense(e.Count);
                for (int i = 0; i < e.Count; i++)
                {
                    if (e[i] >= 0.0)
                    {
                        res[i] = 1.0;
                    }
                }
                return(res);
            }).ToArray();
            MathNet.Numerics.LinearAlgebra.Vector <Complex>[] slm_sensor_wo_noise = t_vectors_est_sensor_wo_noise.Select(e => {
                MathNet.Numerics.LinearAlgebra.Vector <Complex> res =
                    MathNet.Numerics.LinearAlgebra.Vector <Complex> .Build.Dense(e.Count);
                for (int i = 0; i < e.Count; i++)
                {
                    if (e[i] >= 0.0)
                    {
                        res[i] = 1.0;
                    }
                }
                return(res);
            }).ToArray();

            MathNet.Numerics.LinearAlgebra.Vector <Complex>[] slm_sensor_w_noise_fverif = t_vectors_est_sensor_w_noise_fverif.Select(e => {
                MathNet.Numerics.LinearAlgebra.Vector <Complex> res =
                    MathNet.Numerics.LinearAlgebra.Vector <Complex> .Build.Dense(e.Count);
                for (int i = 0; i < e.Count; i++)
                {
                    if (e[i] >= 0.0)
                    {
                        res[i] = 1.0;
                    }
                }
                return(res);
            }).ToArray();

            double ideal_detector_opt_int    = 0.0;
            double sensor_w_noise_opt_int    = 0.0;
            double sensor_w_noise_f_opt_int  = 0.0;
            double sensor_wo_noise_opt_int   = 0.0;
            double sensor_wo_noise_f_opt_int = 0.0;

            double sensor_w_noise_opt_int_fverif   = 0.0;
            double sensor_w_noise_f_opt_int_fverif = 0.0;

            for (int i = 0; i < t_vectors.Length; i++)
            {
                ideal_detector_opt_int    += ideal_detector(((t_vectors[i] * e_inc) * hr_ideal_detector[i].SLMPatternOptimized).MagnitudeSquared());
                sensor_w_noise_opt_int    += ideal_detector(((t_vectors[i] * e_inc) * hr_sensor_w_noise[i].SLMPatternOptimized).MagnitudeSquared());
                sensor_w_noise_f_opt_int  += ideal_detector(((t_vectors[i] * e_inc) * slm_sensor_w_noise[i]).MagnitudeSquared());
                sensor_wo_noise_f_opt_int += ideal_detector(((t_vectors[i] * e_inc) * slm_sensor_wo_noise[i]).MagnitudeSquared());
                sensor_wo_noise_opt_int   += ideal_detector(((t_vectors[i] * e_inc) * hr_sensor_wo_noise[i].SLMPatternOptimized).MagnitudeSquared());

                sensor_w_noise_opt_int_fverif   += ideal_detector(((t_vectors_fverif[i] * e_inc) * hr_sensor_w_noise_fverif[i].SLMPatternOptimized).MagnitudeSquared());
                sensor_w_noise_f_opt_int_fverif += ideal_detector(((t_vectors_fverif[i] * e_inc) * slm_sensor_w_noise_fverif[i]).MagnitudeSquared());
            }
            ideal_detector_opt_int    /= t_vecs_count;
            sensor_w_noise_opt_int    /= t_vecs_count;
            sensor_w_noise_f_opt_int  /= t_vecs_count;
            sensor_wo_noise_f_opt_int /= t_vecs_count;
            sensor_wo_noise_opt_int   /= t_vecs_count;

            sensor_w_noise_opt_int_fverif   /= t_vecs_count;
            sensor_w_noise_f_opt_int_fverif /= t_vecs_count;

            double sensor_w_noise_avg_int =
                hr_sensor_w_noise.Average(new Func <HadamardResult, double>(e => (e.IntensityPlus.Average() + e.IntensityMinus.Average()) / 2.0));
            double sensor_w_noise_max_int =
                hr_sensor_w_noise.Average(new Func <HadamardResult, double>(e => Math.Max(e.IntensityPlus.Max(), e.IntensityMinus.Max())));
            double sensor_w_noise_min_int =
                hr_sensor_w_noise.Average(new Func <HadamardResult, double>(e => Math.Max(e.IntensityPlus.Min(), e.IntensityMinus.Min())));

            double sensor_wo_noise_avg_int =
                hr_sensor_wo_noise.Average(new Func <HadamardResult, double>(e => (e.IntensityPlus.Average() + e.IntensityMinus.Average()) / 2.0));
            double sensor_wo_noise_max_int =
                hr_sensor_wo_noise.Average(new Func <HadamardResult, double>(e => Math.Max(e.IntensityPlus.Max(), e.IntensityMinus.Max())));
            double sensor_wo_noise_min_int =
                hr_sensor_wo_noise.Average(new Func <HadamardResult, double>(e => Math.Max(e.IntensityPlus.Min(), e.IntensityMinus.Min())));


            double sensor_w_noise_avg_int_fverif =
                hr_sensor_w_noise_fverif.Average(new Func <HadamardResult, double>(e => (e.IntensityPlus.Average() + e.IntensityMinus.Average()) / 2.0));
            double sensor_w_noise_max_int_fverif =
                hr_sensor_w_noise_fverif.Average(new Func <HadamardResult, double>(e => Math.Max(e.IntensityPlus.Max(), e.IntensityMinus.Max())));
            double sensor_w_noise_min_int_fverif =
                hr_sensor_w_noise_fverif.Average(new Func <HadamardResult, double>(e => Math.Max(e.IntensityPlus.Min(), e.IntensityMinus.Min())));

            Console.WriteLine("DONE");

            Console.WriteLine("- Ideal detector");
            Console.WriteLine("WtR - RtW switches:                   {0}", hr_ideal_detector_cs_wtr - hr_ideal_detector_cs_rtw);
            Console.WriteLine("Optimized intensity:                  {0:E4}", ideal_detector_opt_int);
            //Console.WriteLine("Optimized intensity (filtered): {0:E4}", ideal_detector_opt_int);
            Console.WriteLine("Correct estimations:                  {0}", hr_ideal_detector_cs);
            Console.WriteLine("- Sensor w/o noise");
            Console.WriteLine("Correct estimations:                  {0}", hr_sensor_wo_noise_cs);
            Console.WriteLine("Correct estimations (filtered):       {0}", hr_sensor_wo_noise_cs_f);
            Console.WriteLine("WtR - RtW switches:                   {0}", hr_sensor_wo_noise_cs_wtr - hr_sensor_wo_noise_cs_rtw);
            Console.WriteLine("Optimized intensity (true):           {0:E4}", sensor_wo_noise_opt_int);
            Console.WriteLine("Optimized intensity (true, filtered): {0:E4}", sensor_wo_noise_f_opt_int);
            Console.WriteLine("Average intensity (camera):           {0}", Math.Round(sensor_wo_noise_avg_int, 0));
            Console.WriteLine("Minimal intensity (camera):           {0}", Math.Round(sensor_wo_noise_min_int, 0));
            Console.WriteLine("Maximal intensity (camera):           {0}", Math.Round(sensor_wo_noise_max_int, 0));
            Console.WriteLine("- Sensor w/ noise");
            Console.WriteLine("Correct estimations:                  {0}", hr_sensor_w_noise_cs);
            Console.WriteLine("Correct estimations (filtered):       {0}", hr_sensor_w_noise_cs_f);
            Console.WriteLine("WtR - RtW switches:                   {0}", hr_sensor_w_noise_cs_wtr - hr_sensor_w_noise_cs_rtw);
            Console.WriteLine("Optimized intensity (true):           {0:E4}", sensor_w_noise_opt_int);
            Console.WriteLine("Optimized intensity (true, filtered): {0:E4}", sensor_w_noise_f_opt_int);
            Console.WriteLine("Average intensity (camera):           {0}", Math.Round(sensor_w_noise_avg_int, 0));
            Console.WriteLine("Minimal intensity (camera):           {0}", Math.Round(sensor_w_noise_min_int, 0));
            Console.WriteLine("Maximal intensity (camera):           {0}", Math.Round(sensor_w_noise_max_int, 0));

            Console.WriteLine("- Sensor w/ noise (verification)");
            Console.WriteLine("Correct estimations:                  {0}", hr_sensor_w_noise_cs_fverif);
            Console.WriteLine("Correct estimations (filtered):       {0}", hr_sensor_w_noise_cs_ffverif);
            Console.WriteLine("WtR - RtW switches:                   {0}", hr_sensor_w_noise_cs_fverif_wtr - hr_sensor_w_noise_cs_fverif_rtw);
            Console.WriteLine("Optimized intensity (true):           {0:E4}", sensor_w_noise_opt_int_fverif);
            Console.WriteLine("Optimized intensity (true, filtered): {0:E4}", sensor_w_noise_f_opt_int_fverif);
            Console.WriteLine("Average intensity (camera):           {0}", Math.Round(sensor_w_noise_avg_int_fverif, 0));
            Console.WriteLine("Minimal intensity (camera):           {0}", Math.Round(sensor_w_noise_min_int_fverif, 0));
            Console.WriteLine("Maximal intensity (camera):           {0}", Math.Round(sensor_w_noise_max_int_fverif, 0));

            hr_ideal_detector[0].TransmissionVectorEstimated.Real().WriteToCSV(
                "d:/Wavefront shaping/Tasks/01_CCD_noise_Wiener_filter/ideal_detector.csv");
            hr_sensor_w_noise[0].TransmissionVectorEstimated.Real().WriteToCSV(
                "d:/Wavefront shaping/Tasks/01_CCD_noise_Wiener_filter/sensor_w_noise.csv");
            t_vectors_est_sensor_w_noise[0].WriteToCSV(
                "d:/Wavefront shaping/Tasks/01_CCD_noise_Wiener_filter/sensor_w_noise_filtered.csv");
            hr_sensor_wo_noise[0].TransmissionVectorEstimated.Real().WriteToCSV(
                "d:/Wavefront shaping/Tasks/01_CCD_noise_Wiener_filter/sensor_wo_noise.csv");
        }
Ejemplo n.º 23
0
 public MathNet.Numerics.LinearAlgebra.Vector <double> CalculateDerivative(MathNet.Numerics.LinearAlgebra.Vector <double> x)
 {
     return(CreateVector.Dense <double>(x.Count, 1.0));
 }
Ejemplo n.º 24
0
 public MathNet.Numerics.LinearAlgebra.Vector <double> CalculateActivation(MathNet.Numerics.LinearAlgebra.Vector <double> x)
 {
     return(x);
 }
Ejemplo n.º 25
0
 public MathNet.Numerics.LinearAlgebra.Vector <double> Apply(MathNet.Numerics.LinearAlgebra.Vector <double> zeta)
 {
     return(zeta * G_inv);
 }
        public static HadamardResult Simulate(MathNet.Numerics.LinearAlgebra.Vector <Complex> t_vector,
                                              Complex e_inc, Func <double, double> detector, bool avoid_zero_i_1 = false)
        {
            Matrix <Complex> h_matrix = HadamardMartix.GenerateHadamardMatrix(t_vector.Count);
            HadamardResult   h_res    = new HadamardResult();

            int slm_size = t_vector.Count;

            h_res.IntensityMinus = MathNet.Numerics.LinearAlgebra.Vector <double> .Build.Dense(slm_size);

            h_res.IntensityPlus = MathNet.Numerics.LinearAlgebra.Vector <double> .Build.Dense(slm_size);

            h_res.ReSigma = MathNet.Numerics.LinearAlgebra.Vector <double> .Build.Dense(slm_size);

            h_res.TransmissionVectorEstimated = MathNet.Numerics.LinearAlgebra.Vector <Complex> .Build.Dense(slm_size);

            h_res.SLMPatternOptimized = MathNet.Numerics.LinearAlgebra.Vector <Complex> .Build.Dense(slm_size);

            h_res.Zeta = MathNet.Numerics.LinearAlgebra.Vector <Complex> .Build.Dense(2 *slm_size - 1);

            MathNet.Numerics.LinearAlgebra.Vector <Complex> h_1 = h_matrix.Row(0);
            double i_1 = detector(((t_vector * e_inc) * h_1).MagnitudeSquared());

            if (avoid_zero_i_1 && i_1 == 0.0)
            {
                h_res.ZeroInitialIntensity = true;
                i_1 = 1.0;
                Console.WriteLine("I_1 was equal to zero.");
            }

            double i_plus;
            double i_minus;
            double re_sigma;

            for (int pix = 0; pix < t_vector.Count; pix++)
            {
                MathNet.Numerics.LinearAlgebra.Vector <Complex> h_i     = h_matrix.Row(pix);
                MathNet.Numerics.LinearAlgebra.Vector <Complex> v_plus  = (h_1 + h_i) / 2.0;
                MathNet.Numerics.LinearAlgebra.Vector <Complex> v_minus = (h_1 - h_i) / 2.0;

                i_plus  = detector(((t_vector * e_inc) * v_plus).MagnitudeSquared());
                i_minus = detector(((t_vector * e_inc) * v_minus).MagnitudeSquared());
                h_res.IntensityPlus[pix]  = i_plus;
                h_res.IntensityMinus[pix] = i_minus;

                h_res.Zeta[pix] = i_plus / Math.Sqrt(i_1) / t_vector.Count;
                if (pix != 0)
                {
                    h_res.Zeta[slm_size + pix - 1] = i_minus / Math.Sqrt(i_1) / t_vector.Count;
                }


                re_sigma           = (i_plus - i_minus) / Math.Sqrt(i_1) / t_vector.Count;
                h_res.ReSigma[pix] = re_sigma;

                h_res.TransmissionVectorEstimated += re_sigma * h_i;
            }

            for (int i = 0; i < slm_size; i++)
            {
                if (h_res.TransmissionVectorEstimated[i].Real >= 0)
                {
                    h_res.SLMPatternOptimized[i] = new Complex(1, 0);
                }
                else
                {
                    h_res.SLMPatternOptimized[i] = new Complex(0, 0);
                }
            }

            for (int i = 0; i < slm_size; i++)
            {
                if (Math.Sign(h_res.TransmissionVectorEstimated[i].Real) == Math.Sign(t_vector[i].Real))
                {
                    h_res.CorrectSignsNumber++;
                }
            }

            //h_res.Enhancement = detector(((t_vector * e_inc) * h_res.SLMPatternOptimized).MagnitudeSquared()) /
            //    detector(((t_vector * e_inc) * h_1).MagnitudeSquared());
            h_res.OptimizedIntensity = detector(((t_vector * e_inc) * h_res.SLMPatternOptimized).MagnitudeSquared());
            h_res.Enhancement        = h_res.OptimizedIntensity / i_1;

            return(h_res);
        }
Ejemplo n.º 27
0
 private static Vector3 ToVector3(MathNet.Numerics.LinearAlgebra.Vector <float> v)
 {
     return(new Vector3(v[0], v[1], v[2]));
 }