Beispiel #1
1
 protected NcaModel(NcaModel original, Cloner cloner)
   : base(original, cloner) {
   this.transformationMatrix = (double[,])original.transformationMatrix.Clone();
   this.allowedInputVariables = (string[])original.allowedInputVariables.Clone();
   this.nnModel = cloner.Clone(original.nnModel);
   this.classValues = (double[])original.classValues.Clone();
 }
Beispiel #2
0
 public userDefinedGoals()
 {
     inputLocation = Matrix.makeIdentity(4);
     outputLocation = Matrix.multiply(inputLocation, Matrix.translate(2.0, 2.0, 4.0));
     outputLocation = Matrix.multiply(outputLocation, Matrix.rotationX(-40));
     //outputLocation = Matrix.multiply(outputLocation, Matrix.rotationY(20));
 }
Beispiel #3
0
        public void FourierRowMethod(int n, double [] X,double []Y,out double A,out double [,] B, out double [,] C)
        {
            double w;
             A = 0;
             B=new double[n,1];
             C=new double[n,1];
            double sumaA = 0, sumaB, sumaC;
            w = (Math.PI*2)/n;

            for (int i = 0; i < n; i++)
            {
                sumaA += Y[i];
            }
            A = sumaA/n;
            for (int k = 0; k < n; k++)
            {
                sumaB = 0;
                sumaC = 0;
                for (int i = 0; i < n; i++)
                {
                    sumaB += Math.Cos((k + 1)*w*X[i])*Y[i];
                    sumaC += Math.Sin((k + 1)*w*X[i])*Y[i];
                }
                B[k,0] = (2*sumaB)/n;
                C[k,0] = (2*sumaC)/n;
            }
        }
Beispiel #4
0
        public double[,] LeastSquares(double[] X, double[] Y, int w,int n)
        {
            A = new double[w + 1,1];
            S=new double[w+1,w+1];
            T=new double[w+1,1];
            double sumaS = 0;
            double sumaT = 0;
            for (int k = 0; k<=w; k++)//w - stopień wielomianu którym aproksymujemy
            {
                for (int i = 0; i <=w; i++)
                {
                    for (int j = 0; j <= n; j++)
                    {
                        sumaS += (Math.Pow(X[j], k+i));
                    }
                    S[i, k] = sumaS;
                }
            }
            for (int k = 0; k < w; k++)
            {
                for (int j = 0; j < n; j++)
                {
                    sumaT += (Math.Pow(X[j], k)*Y[j]);
                }
                T[k, 0] = sumaT;
            }
            Matrix inverseMatrix=new Matrix();
            double[,] sodwr = inverseMatrix.InverseMatrix(S, n, n);
            A = inverseMatrix.MultiplyMatrix(sodwr, T, n, n, n, n);

            return A;
        }
Beispiel #5
0
 private void LoadTeapot(object sender, EventArgs e)
 {
     DisplayObject = NewCustomMatrix();
     DisplayObject.LoadMatrix(@"objects\teapot.txt");
     scalingMatrix = Dmatrix.ScalingMatrix(10, 10, 10);
     transformAndDrawAll();
 }
Beispiel #6
0
 private void LoadDolphin(object sender, EventArgs e)
 {
     DisplayObject =NewCustomMatrix();
     DisplayObject.LoadMatrix(@"objects\Dolphin.txt");
     scalingMatrix = Dmatrix.ScalingMatrix(1, 1, 1);
     transformAndDrawAll();
 }
 //for demonstration purposes merged with client//
 public void makePrediction()
 {
     current_prediction_lock.EnterWriteLock();
         Logger.Instance.log(" ==== Making prediction for "+ ServerCore.Instance.current_time_stamp.ToString() +" ==== ");
         current_prediction = this.tpm1.makePrediction(ds.get_current_X_TPM1(ServerCore.Instance.current_time_stamp));
         current_prediction_lock.ExitWriteLock();
 }
        public ComplexData GetData(ref int x, ref int y, ref double[,] res, ref double[,] ims, ref double[,] other, ref UInt64[,] height)
        {
            m_hasOne.WaitOne();
            x = m_tileX;
            y = m_tileY;
            res = m_res;
            ims = m_ims;
            other = m_other;
            height = m_height;
            ComplexData ret = m_data;
            m_gotOne.Set();

            if (ret == null)
            {
                m_thread.Join();
                m_thread = null;
            }

            m_tileX = 0;
            m_tileY = 0;
            m_data = null;
            m_res = null;
            m_ims = null;
            m_other = null;
            m_height = null;

            return ret;
        }
 public LeastSquaresRuntime(Double[,] trainingSet, Double[,] trainingOutput, Double[,] testSet, int[] expected)
 {
     this.trainingSet = trainingSet;
     this.trainingOutput = trainingOutput;
     this.testSet = testSet;
     this.expected = expected;
 }
        public MainWindow()
        {
            // file I/O
            string now = DateTime.Now.ToString("yyMMddhhmmss");
            string csvname = String.Format("./{0}.csv", now);
            swt = new StreamWriter(csvname);

            // read annotated regions from data.csv
            string datapath = ("../../roi.csv");
            double[,] roi_org = readfromcsv(datapath); // id, x, y, width, height, roi[0, :]: imageSize
            roi = adjustroi(roi_org);

            double max_roi_id = 0;
            for (int j = 0; j < roi.GetLongLength(0); j++)
            {
                swt.WriteLine("RoI_id{0}: x:{1}--{2}, y:{3}--{4}",  roi[j,0], roi[j,1], roi[j,1] + roi[j,3], roi[j,2], roi[j,2] + roi[j,4]);
                max_roi_id = (max_roi_id > roi[j,0])? max_roi_id : roi[j,0]; //0: add empty region for y axis, 1: add empty region for x axis
            }
            roi_hist = new int[(int)max_roi_id+1];

            // eye tribe
            GazeManager.Instance.Activate(GazeManager.ApiVersion.VERSION_1_0, GazeManager.ClientMode.Push);
            GazeManager.Instance.AddGazeListener(this);
            if (!GazeManager.Instance.IsActivated)
            {
                Dispatcher.BeginInvoke(new Action(() => MessageBox.Show("EyeTribe Server has not been started")));
                Close();
                return;
            }
            // Register for key events
            KeyDown += WindowKeyDown;

            InitializeComponent();
        }
Beispiel #11
0
 public clsRarray()
 {
     matrix = null;
     mstrMatrix = null;
     rowNames = null;
     colHeaders = null;
 }
Beispiel #12
0
        public override void calculate()
        {
            aPoints = Database.getINSTANCE().getAPoints();
            bPoints = Database.getINSTANCE().getBPointsCoord();
            double[,] result = new double[bPoints.GetLength(0), 3];

            double progressStep = 25.0 / bPoints.GetLength(0);
            Stopwatch sw = new Stopwatch();

            for (int bIndex = 0; bIndex < bPoints.GetLength(0); bIndex++)
            {
                sw.Start();
                //x
                result[bIndex, Constants.X] = calculateInduction(Constants.X, bPoints[bIndex, Constants.X]);

                //y
                result[bIndex, Constants.Y] = calculateInduction(Constants.Y, bPoints[bIndex, Constants.Y]);

                //z
                result[bIndex, Constants.Z] = calculateInduction(Constants.Z, bPoints[bIndex, Constants.Z]);
                while (sw.ElapsedMilliseconds < (20.0 * progressStep)) { }
                sw.Reset();

                Progress.getINSTANCE().addToProgress(progressStep);
            }

            Database.getINSTANCE().setBPointsInd(result);
        }
        //constructor for creating all nodes but the first
        public Node(Node prev, bool isInclude, int exit, int enter)
        {
            //copy info needed from parent node
            this.lowerBound = prev.lowerBound;
            this.matrixLength = prev.matrixLength;
            this.rCmatrix = copy2Darray(prev.rCmatrix);
            this.entered = copyArray(prev.entered);
            this.exited = copyArray(prev.exited);

            if (isInclude)//code only for an include node
            {
                this.totalEdges = prev.totalEdges + 1;
                entered[enter] = exit;
                exited[exit] = enter;
                rCmatrix[enter, exit] = Double.PositiveInfinity;
                eliminateEdges(rCmatrix, exit, enter);
                if(this.totalEdges < matrixLength)
                {
                    eliminatePCycles(rCmatrix, exit, enter);
                }

            }
            else//code only for an exclude node
            {
                this.totalEdges = prev.totalEdges;
                rCmatrix[exit, enter] = Double.PositiveInfinity;
            }

            reduceMatrix(rCmatrix);
        }
Beispiel #14
0
 public TopographicSeries(Chart chart, string name)
     : base(chart, name)
 {
     _dataList.Add(null); // DataX
       _dataList.Add(null); // DataY
       _dataZ = null;
 }
Beispiel #15
0
        /// <summary>
        /// Кнопка "Решить". Запускается решение
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSolve_Click(object sender, EventArgs e)
        {
            // Заполняем поля и проводим проверку
            СчитатьОсновныеДанные();
            ПроверитьПравильностьДанных();

            // Теперь, инициализируем переменные
            gridSupport.RowCount = задача.КоличествоПоставщиков;
            gridFinal.RowCount = задача.КоличествоПоставщиков;

            gridSupport.ColumnCount = задача.КоличествоПотребителей;
            gridFinal.ColumnCount = задача.КоличествоПотребителей;
            
            // Выводим опорный план, который получен при запуске конструктора в задаче
            ОпорныйПлан = задача.МатрицаПоискаОптимальногоПлана;
            ЗаполнитьУказаннуюТаблицу(gridSupport, ОпорныйПлан);

            // Запускаем задачу на решение:
            задача.НачатьРешение();// Там же и выводится результат

            // Получим оптимальный план(после решения)
            ОптимальныйПлан = задача.МатрицаПоискаОптимальногоПлана;
            ЗаполнитьУказаннуюТаблицу(gridFinal, ОптимальныйПлан);
            
            lblOptimum.Text = "Цена перевозок: " + задача.КонечнаяСумма.ToString();
        }
Beispiel #16
0
 //
 public NCommittee(DataSet pat, DataSet tar, params string[] netFiles)
 {
     try
     {
         networks = new BackPropNet[netFiles.Length];
         //
         for(int i=0; i<netFiles.Length; i++)
             networks[i] = BackPropNet.BinaryLoad(netFiles[i]);
         //
         this.SetData(pat, tar);
         this.CheckNetworks();
         //
         // allocate memory
         alpha = new double[networks.Length];
         outputs = new Double[patterns.GetNumberOfVectors()];
         errors = new double[networks.Length, patterns.GetNumberOfVectors()];
     }
     catch(System.Exception e)
     {
         Console.WriteLine(e.Message);
         networks = null;
         patterns = null;
         targets  = null;
         errors   = null;
         alpha    = null;
         throw;
     }
 }
 private IsobaricTagPurityCorrection(double[,] matrix)
 {
     _purityMatrix = matrix;
     int[] index;
     _purityLUMatrix = _purityMatrix.LUDecompose(out index);
     _purityLUMatrixIndex = index;
 }
        public SVD(double[] A, int m, int n)
        {
            int i, j;
            this.m = m;
            this.n = n;
            if (A.GetLength(0) < (m * n)) throw new ArgumentException();
            u = dmatrix(1,m,1,n);
            w = dvector(1,n);
            v = dmatrix(1,n,1,n);
            fullRank = true;

            for (i=0; i<m; i++)
                for (j=0; j<n; j++)
                    u[i+1,j+1] = A[i*n + j];

            state = dsvdcmp(u, m, n, w, v);

            double max = 0.0;
            for (i=1; i<=n; i++) if (w[i]>max) max = w[i];

            double min = max * 1.0e-6;	// can be 1.0e-12 here
            for (i=1; i<=n; i++)
                if (w[i]<min)
                {
                    w[i] = 0;
                    fullRank = false;
                }
        }
Beispiel #19
0
        /// <summary>
        /// Reads an ICC profile from disk
        /// </summary>
        /// <param name="path">Path to the icc file</param>
        public ICC(string path)
        {
            ProfileName = Path.GetFileNameWithoutExtension(path);
            profile = new ICCProfile(path, true);

            //mediaWhitePointTag
            double[] wpXYZ = null;
            TagDataEntry wpEn = profile.GetFirstEntry(TagSignature.mediaWhitePointTag);
            if (wpEn != null && wpEn.Signature == TypeSignature.XYZ) { wpXYZ = ((XYZTagDataEntry)wpEn).Data[0].GetArray(); }

            if (wpXYZ != null) { wp = new Whitepoint(wpXYZ); }
            else { wp = new Whitepoint(Header.PCSIlluminant.GetArray()); }

            //profileDescriptionTag
            TagDataEntry desc = profile.GetFirstEntry(TagSignature.profileDescriptionTag);
            if (desc.Signature == TypeSignature.multiLocalizedUnicode) { des = ((multiLocalizedUnicodeTagDataEntry)desc).Text; }
            else if (desc.Signature == TypeSignature.text) { des = new LocalizedString[] { new LocalizedString(new CultureInfo("en"), ((textTagDataEntry)desc).Text) }; }

            //copyrightTag
            TagDataEntry cpr = profile.GetFirstEntry(TagSignature.copyrightTag);
            if (cpr.Signature == TypeSignature.multiLocalizedUnicode) { cprs = ((multiLocalizedUnicodeTagDataEntry)cpr).Text; }
            else if (cpr.Signature == TypeSignature.text) { cprs = new LocalizedString[] { new LocalizedString(new CultureInfo("en"), ((textTagDataEntry)cpr).Text) }; }

            //chromaticAdaptationTag (if data has different reference white as PCS)
            s15Fixed16ArrayTagDataEntry cam = (s15Fixed16ArrayTagDataEntry)profile.GetFirstEntry(TagSignature.chromaticAdaptationTag);
            if (cam != null)
            {
                ma = new double[,] { { cam.Data[0], cam.Data[1], cam.Data[2] }, { cam.Data[3], cam.Data[4], cam.Data[5] }, { cam.Data[6], cam.Data[7], cam.Data[8] } };
                ma1 = MMath.StaticInvertMatrix(ma);
            }

            SetHasVariables();
        }
 public Segmentator(Bitmap picture)
 {
     matrix = new float[picture.Width, picture.Height];
     pic = ImageHelper.LoadImage<double>(picture);
     width = picture.Width;
     height = picture.Height;
 }
        public SVD(double[,] A)
        {
            int i, j;
            m = A.GetLength(0);
            n = A.GetLength(1);
            u = dmatrix(1,m,1,n);
            w = dvector(1,n);
            v = dmatrix(1,n,1,n);
            fullRank = true;

            for(i=0; i<m; i++)
                for (j=0; j<n; j++)
                    u[i+1,j+1] = A[i,j];

            state = dsvdcmp(u, m, n, w, v);

            double max = 0.0;
            for (i=1; i<=n; i++) if (w[i]>max) max = w[i];

            double min = max * 1.0e-6;	// can be 1.0e-12 here
            for (i=1; i<=n; i++)
                if (w[i]<min)
                {
                    w[i] = 0;
                    fullRank = false;
                }
        }
        // pass a pointer to a heightmap
        // when rendered, x pos will be multiplied by xscale, and y points by yscale
        public RenderableHeightMap(TerrainView terrainview, TerrainModel terrainmodel, int xscale, int yscale )
        {
            this.terrainmodel = terrainmodel;
            this.terrainview = terrainview;

            this.heightmap = terrainmodel.Map;
            width = heightmap.GetLength(0) - 1;
            height = heightmap.GetLength(1) - 1;
            this.xscale = xscale;
            this.yscale = yscale;

            //maptexturestageviews = terrainview.maptexturestageviews;
            maptexturestagemodels = terrainmodel.texturestages;
            //    foreach (MapTextureStageView maptexturestageview in maptexturestageviews)
              //  {
            //    viewbymodel.Add( maptexturestageview.maptexturestagemodel, maptexturestageview );
            //}

            CacheChunkTextureStageUsage();
            normalsperquad = new Vector3[width, height];
            terrain_HeightmapInPlaceEdited(0, 0, width - 1, height - 1);
            RendererFactory.GetInstance().WriteNextFrameEvent += new WriteNextFrameCallback(Render);
            terrainmodel.HeightmapInPlaceEdited += new TerrainModel.HeightmapInPlaceEditedHandler(terrain_HeightmapInPlaceEdited);
            terrainmodel.TerrainModified += new TerrainModel.TerrainModifiedHandler(terrain_TerrainModified);
            terrainmodel.BlendmapInPlaceEdited += new TerrainModel.BlendmapInPlaceEditedHandler(terrain_BlendmapInPlaceEdited);
        }
Beispiel #23
0
        public void Move()
        {
            int nX = 0, nY = 0;
            double xMove = 0, yMove = 0;
            aliMove = alignment();
            coMove = cohesion();
            sepMove = seperation();
            xMove = ((1.6 * aliMove[0, 0]) + coMove[0, 0] + (1.5 * sepMove[0, 0])); //moves are weighted to make movement better
            xMove = Math.Round(xMove); //rounds them answer to an integer
            yMove = ((1.6 * aliMove[1, 0]) + coMove[1, 0] + (1.5 * sepMove[1, 0])); //literally no idea why they all need different weighting
            yMove = Math.Round(yMove);
            xMove = sizeCheck(xMove); //makes sure the moves aren -1 --> 1
            yMove = sizeCheck(yMove);
            nX = x + Convert.ToInt32(xMove); //makes the next x & y positions without doing the move, so it can make sure that position is empty
            nY = y + Convert.ToInt32(yMove);
            nX = overlapMove(nX); //keeps the movement going so they don't all stop at the edges
            nY = overlapMove(nY);
            if (grid[nX, nY] != empty) //does a separation move if the cell they are meant to move to is full
            {
                xMove = sepMove[0, 0];
                yMove = sepMove[1, 0];
                nX = this.x + Convert.ToInt32(xMove); //makes the next x & y positions without doing the move, so it can make sure that position is empty
                nY = this.y + Convert.ToInt32(yMove);
                nX = overlapMove(nX);
                nY = overlapMove(nY);
            }

            grid[this.x, this.y] = empty; //sets the current position the boid is in the array as empty, as setpos will update the new position as a boid with the new x&y values
            this.x = nX; //sets the next x and y values as current
            this.y = nY;
            this.dirX = Convert.ToInt32(xMove); //sets the direction taken
            this.dirY = Convert.ToInt32(yMove);
            this.setPos(); //sets the position of the boid in the display array
        }
Beispiel #24
0
 public clsRarray(string[,] mat, string[] rows, string[] cols)
 {
     matrix = null;
     mstrMatrix = mat;
     rowNames = rows;
     colHeaders = cols;
 }
Beispiel #25
0
        /// <summary>Construct a QR decomposition.</summary>	
        public QrDecomposition(double[,] value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            this.qr = (double[,])value.Clone();
            double[,] qr = this.qr;
            int m = value.GetLength(0);
            int n = value.GetLength(1);
            this.Rdiag = new double[n];

            for (int k = 0; k < n; k++)
            {
                // Compute 2-norm of k-th column without under/overflow.
                double nrm = 0;
                for (int i = k; i < m; i++)
                {
                    nrm = Tools.Hypotenuse(nrm,qr[i,k]);
                }

                if (nrm != 0.0)
                {
                    // Form k-th Householder vector.
                    if (qr[k,k] < 0)
                    {
                        nrm = -nrm;
                    }

                    for (int i = k; i < m; i++)
                    {
                        qr[i,k] /= nrm;
                    }

                    qr[k,k] += 1.0;

                    // Apply transformation to remaining columns.
                    for (int j = k+1; j < n; j++)
                    {
                        double s = 0.0;

                        for (int i = k; i < m; i++)
                        {
                            s += qr[i,k]*qr[i,j];
                        }

                        s = -s/qr[k,k];

                        for (int i = k; i < m; i++)
                        {
                            qr[i,j] += s*qr[i,k];
                        }
                    }
                }

                this.Rdiag[k] = -nrm;
            }
        }
Beispiel #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MatrixPrinter"/> class.
 /// </summary>
 /// <param name="matrix">The matrix.</param>
 /// <param name="newlinechar">The newlinechar.</param>
 /// <param name="blankchar">The blankchar.</param>
 public MatrixPrinter(List<List<double>> matrix, string newlinechar, string blankchar)
 {
     _matrix = matrix;
     _matrixArray = null;
     _matrixDict = null;
     _newLineChar = newlinechar;
     _blankChar = blankchar;
 }
 /// <summary>
 ///  Constructs a repeat pattern.
 /// </summary>
 /// <param name="name">Name of the repeat.</param>
 /// <param name="pattern">The Pattern to repeat.</param>
 /// <param name="mode">DIRECT, INVERTED</param>
 /// <param name="threshold">Similarity threshold</param>
 public Repeat
     (string name, IPattern pattern, string mode, double threshold)
     : base(name)
 {
     Threshold = threshold;
     Set(pattern, mode);
     weights = null;
 }
		private void Window1_Loaded(object sender, RoutedEventArgs e)
		{
			data = BuildSampleData(imageSize);

			NaiveColorMap map = new NaiveColorMap { Data = data, Palette = UniformLinearPalettes.BlackAndWhitePalette };
			var bmp = map.BuildImage();
			image.Source = bmp;
		}
 public ImplicitFeedbackAlternatingLeastSquaresSolver(int numFeatures, double lambda, double alpha,
     IDictionary<int,double[]> Y) {
   this.numFeatures = numFeatures;
   this.lambda = lambda;
   this.alpha = alpha;
   this.Y = Y;
   YtransposeY = getYtransposeY(Y);
 }
Beispiel #30
0
 private void OnGuidanceForceScoreAvailableEvent(object sender, GuidanceForceScoreEventArgs e)
 {
     var neuron = e.Neuron;
     if (neuron == Neuron)
     {
         _latestScore = (double[,])e.Score.Clone();
     }
 }
Beispiel #31
0
 /// <summary>Exponential value.</summary>
 protected static mat exp(double[,] d)
 {
     return(Matrix.Apply(d, x => System.Math.Exp(x)));
 }
Beispiel #32
0
 /// <summary>Logarithm.</summary>
 protected static mat log(double[,] d)
 {
     return(Matrix.Apply(d, x => System.Math.Log(x)));
 }
Beispiel #33
0
 public Macierz(int liczbaWierczy, int liczbaKolumn)
 {
     macierz = new double[liczbaWierczy, liczbaKolumn];
 }
 // метод розширення для отримання кількості рядків матриці
 public static int RowsCount(this double[,] matrix)
 {
     return(matrix.GetUpperBound(0) + 1);
 }
Beispiel #35
0
        int AmpScalefacBands(double[] xr, double[,] xfsf, double[,,] xmin_l, double[,,,] xmin_s, ref SideInfo l3_side, int[][][] scalefact_l, int[][][][] scalefact_s, int gr, int ch, int iteration)
        {
            int    start, end, l, i, scfsi_band, over = 0;
            int    sfb;
            double ifqstep, ifqstep2;
            int    copySF, preventSF;

            copySF    = 0;
            preventSF = 0;

            if (l3_side.TT[ch, gr].ScalefacScale == 0)
            {
                ifqstep = 1.414213562;
            }
            else
            {
                ifqstep = Math.Pow(2.0, 0.5 * (1.0 + l3_side.TT[ch, gr].ScalefacScale));
            }

            if (gr == 1)
            {
                for (scfsi_band = 0; scfsi_band < 4; scfsi_band++)
                {
                    if (l3_side.Scfsi[ch, scfsi_band] != 0)
                    {
                        if (l3_side.TT[ch, 0].ScalefacScale == 0)
                        {
                            ifqstep = 1.414213562;
                        }
                        else
                        {
                            ifqstep = Math.Pow(2.0, 0.5 * (1.0 + l3_side.TT[ch, 0].ScalefacScale));
                        }

                        if (iteration == 1)
                        {
                            copySF = 1;
                        }
                        else
                        {
                            preventSF = 1;
                        }
                        break;
                    }
                }
            }

            ifqstep2   = ifqstep * ifqstep;
            scfsi_band = 0;

            for (sfb = 0; sfb < l3_side.TT[ch, gr].SfbLmax; sfb++)
            {
                if (copySF != 0 || preventSF != 0)
                {
                    if (sfb == scfsi_band_long[scfsi_band + 1])
                    {
                        scfsi_band += 1;
                    }
                    if (l3_side.Scfsi[ch, scfsi_band] != 0)
                    {
                        if (copySF != 0)
                        {
                            scalefact_l[ch][gr][sfb] = scalefact_l[ch][0][sfb];
                        }
                        continue;
                    }
                }


                if (xfsf[0, sfb] > xmin_l[ch, gr, sfb])
                {
                    over++;
                    xmin_l[ch, gr, sfb] *= ifqstep2;
                    scalefact_l[ch][gr][sfb]++;
                    start = scalefac_band_long[sfb];
                    end   = scalefac_band_long[sfb + 1];

                    for (l = start; l < end; l++)
                    {
                        xr[l] *= ifqstep;
                    }
                }
            }

            for (i = 0; i < 3; i++)
            {
                for (sfb = l3_side.TT[ch, gr].SfbSmax; sfb < 12; sfb++)
                {
                    if (xfsf[i + 1, sfb] > xmin_s[ch, gr, sfb, i])
                    {
                        over++;
                        xmin_s[ch, gr, sfb, i] *= ifqstep2;
                        scalefact_s[ch][gr][sfb][i]++;
                        start = scalefac_band_short[sfb];
                        end   = scalefac_band_short[sfb + 1];

                        for (l = start; l < end; l++)
                        {
                            xr[i + l * 3] *= ifqstep;
                        }
                    }
                }
            }
            return(over);
        }
Beispiel #36
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="mat"/> class.
 /// </summary>
 ///
 public mat(double[,] matrix)
 {
     this.matrix = matrix;
 }
        public static AudioToSonogramResult GenerateSpectrogramImages(FileInfo sourceRecording, Dictionary <string, string> configDict, DirectoryInfo opDir)
        {
            string sourceName = configDict[ConfigKeys.Recording.Key_RecordingFileName];

            sourceName = Path.GetFileNameWithoutExtension(sourceName);

            var result = new AudioToSonogramResult();

            // init the image stack
            var list = new List <Image>();

            // 1) draw amplitude spectrogram
            AudioRecording recordingSegment = new AudioRecording(sourceRecording.FullName);
            var            sonoConfig       =
                new SonogramConfig(configDict)
            {
                NoiseReductionType = NoiseReductionType.None,
            };     // default values config

            // disable noise removal for first two spectrograms

            BaseSonogram sonogram = new AmplitudeSonogram(sonoConfig, recordingSegment.WavReader);

            // remove the DC bin
            sonogram.Data = MatrixTools.Submatrix(sonogram.Data, 0, 1, sonogram.FrameCount - 1, sonogram.Configuration.FreqBinCount);

            //save spectrogram data at this point - prior to noise reduction
            double[,] spectrogramDataBeforeNoiseReduction = sonogram.Data;

            int    lowPercentile        = 20;
            double neighbourhoodSeconds = 0.25;
            int    neighbourhoodFrames  = (int)(sonogram.FramesPerSecond * neighbourhoodSeconds);
            double lcnContrastLevel     = 0.25;

            //LoggedConsole.WriteLine("LCN: FramesPerSecond (Prior to LCN) = {0}", sonogram.FramesPerSecond);
            //LoggedConsole.WriteLine("LCN: Neighbourhood of {0} seconds = {1} frames", neighbourhoodSeconds, neighbourhoodFrames);
            sonogram.Data = NoiseRemoval_Briggs.NoiseReduction_ShortRecordings_SubtractAndLCN(sonogram.Data, lowPercentile, neighbourhoodFrames, lcnContrastLevel);

            // draw amplitude spectrogram unannotated
            FileInfo outputImage1 = new FileInfo(Path.Combine(opDir.FullName, sourceName + ".amplitd.png"));

            ImageTools.DrawReversedMatrix(MatrixTools.MatrixRotate90Anticlockwise(sonogram.Data), outputImage1.FullName);

            // draw amplitude spectrogram annotated
            var image = sonogram.GetImageFullyAnnotated("AMPLITUDE SPECTROGRAM + Bin LCN (Local Contrast Normalisation)");

            list.Add(image);

            //string path2 = @"C:\SensorNetworks\Output\Sonograms\dataInput2.png";
            //Histogram.DrawDistributionsAndSaveImage(sonogram.Data, path2);

            // 2) A FALSE-COLOUR VERSION OF AMPLITUDE SPECTROGRAM
            double ridgeThreshold = 0.20;

            double[,] matrix = ImageTools.WienerFilter(sonogram.Data, 3);
            byte[,] hits     = RidgeDetection.Sobel5X5RidgeDetectionExperiment(matrix, ridgeThreshold);
            hits             = RidgeDetection.JoinDisconnectedRidgesInMatrix(hits, matrix, ridgeThreshold);
            image            = SpectrogramTools.CreateFalseColourAmplitudeSpectrogram(spectrogramDataBeforeNoiseReduction, null, hits);
            image            = sonogram.GetImageAnnotatedWithLinearHerzScale(image, "AMPLITUDE SPECTROGRAM + LCN + ridge detection");
            list.Add(image);

            Image envelopeImage = ImageTrack.DrawWaveEnvelopeTrack(recordingSegment, image.Width);

            list.Add(envelopeImage);

            // 3) now draw the standard decibel spectrogram
            sonogram = new SpectrogramStandard(sonoConfig, recordingSegment.WavReader);

            // draw decibel spectrogram unannotated
            FileInfo outputImage2 = new FileInfo(Path.Combine(opDir.FullName, sourceName + ".deciBel.png"));

            ImageTools.DrawReversedMatrix(MatrixTools.MatrixRotate90Anticlockwise(sonogram.Data), outputImage2.FullName);

            image = sonogram.GetImageFullyAnnotated("DECIBEL SPECTROGRAM");
            list.Add(image);

            Image segmentationImage = ImageTrack.DrawSegmentationTrack(
                sonogram,
                EndpointDetectionConfiguration.K1Threshold,
                EndpointDetectionConfiguration.K2Threshold,
                image.Width);

            list.Add(segmentationImage);

            // keep the sonogram data (NOT noise reduced) for later use
            double[,] dbSpectrogramData = (double[, ])sonogram.Data.Clone();

            // 4) now draw the noise reduced decibel spectrogram
            sonoConfig.NoiseReductionType      = NoiseReductionType.Standard;
            sonoConfig.NoiseReductionParameter = 3;

            //sonoConfig.NoiseReductionType = NoiseReductionType.SHORT_RECORDING;
            //sonoConfig.NoiseReductionParameter = 50;

            sonogram = new SpectrogramStandard(sonoConfig, recordingSegment.WavReader);

            // draw decibel spectrogram unannotated
            FileInfo outputImage3 = new FileInfo(Path.Combine(opDir.FullName, sourceName + ".noNoise_dB.png"));

            ImageTools.DrawReversedMatrix(MatrixTools.MatrixRotate90Anticlockwise(sonogram.Data), outputImage3.FullName);
            image = sonogram.GetImageFullyAnnotated("DECIBEL SPECTROGRAM + Lamel noise subtraction");
            list.Add(image);

            // keep the sonogram data for later use
            double[,] nrSpectrogramData = sonogram.Data;

            // 5) A FALSE-COLOUR VERSION OF DECIBEL SPECTROGRAM
            ridgeThreshold = 2.5;
            matrix         = ImageTools.WienerFilter(dbSpectrogramData, 3);
            hits           = RidgeDetection.Sobel5X5RidgeDetectionExperiment(matrix, ridgeThreshold);

            image = SpectrogramTools.CreateFalseColourDecibelSpectrogram(dbSpectrogramData, nrSpectrogramData, hits);
            image = sonogram.GetImageAnnotatedWithLinearHerzScale(image, "DECIBEL SPECTROGRAM - Colour annotated");
            list.Add(image);

            // 6) COMBINE THE SPECTROGRAM IMAGES
            Image    compositeImage = ImageTools.CombineImagesVertically(list);
            FileInfo outputImage    = new FileInfo(Path.Combine(opDir.FullName, sourceName + ".5spectro.png"));

            compositeImage.Save(outputImage.FullName, ImageFormat.Png);
            result.SpectrogramFile = outputImage;

            // 7) Generate the FREQUENCY x OSCILLATIONS Graphs and csv data
            //bool saveData = true;
            //bool saveImage = true;
            //double[] oscillationsSpectrum = Oscillations2014.GenerateOscillationDataAndImages(sourceRecording, configDict, saveData, saveImage);
            return(result);
        }
Beispiel #38
0
        public Martix Inverse(double[,] Array)
        {
            //引用自:https://www.cnblogs.com/renge-blogs/p/6308912.html
            int m = 0;
            int n = 0;

            m = Array.GetLength(0);
            n = Array.GetLength(1);
            double[,] array = new double[2 * m + 1, 2 * n + 1];
            for (int k = 0; k < 2 * m + 1; k++)  //初始化数组
            {
                for (int t = 0; t < 2 * n + 1; t++)
                {
                    array[k, t] = 0.00000000;
                }
            }
            for (int i = 0; i < m; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    array[i, j] = Array[i, j];
                }
            }

            for (int k = 0; k < m; k++)
            {
                for (int t = n; t <= 2 * n; t++)
                {
                    if ((t - k) == m)
                    {
                        array[k, t] = 1.0;
                    }
                    else
                    {
                        array[k, t] = 0;
                    }
                }
            }
            //得到逆矩阵
            for (int k = 0; k < m; k++)
            {
                if (array[k, k] != 1)
                {
                    double bs = array[k, k];
                    array[k, k] = 1;
                    for (int p = k + 1; p < 2 * n; p++)
                    {
                        array[k, p] /= bs;
                    }
                }
                for (int q = 0; q < m; q++)
                {
                    if (q != k)
                    {
                        double bs = array[q, k];
                        for (int p = 0; p < 2 * n; p++)
                        {
                            array[q, p] -= bs * array[k, p];
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            double[,] NI = new double[m, n];
            for (int x = 0; x < m; x++)
            {
                for (int y = n; y < 2 * n; y++)
                {
                    NI[x, y - n] = array[x, y];
                }
            }
            return(new Martix(NI));
        }
        } //Analysis()

        public static Image DisplayDebugImage(BaseSonogram sonogram, List <AcousticEvent> events, List <Plot> scores, double[,] hits)
        {
            const bool       doHighlightSubband = false;
            const bool       add1KHzLines       = true;
            Image_MultiTrack image = new Image_MultiTrack(sonogram.GetImage(doHighlightSubband, add1KHzLines, doMelScale: false));

            image.AddTrack(ImageTrack.GetTimeTrack(sonogram.Duration, sonogram.FramesPerSecond));
            if (scores != null)
            {
                foreach (var plot in scores)
                {
                    image.AddTrack(ImageTrack.GetNamedScoreTrack(plot.data, 0.0, 1.0, plot.threshold, plot.title)); //assumes data normalised in 0,1
                }
            }

            if (hits != null)
            {
                image.OverlayRainbowTransparency(hits);
            }

            if (events.Count > 0)
            {
                foreach (var ev in events) // set colour for the events
                {
                    ev.BorderColour = AcousticEvent.DefaultBorderColor;
                    ev.ScoreColour  = AcousticEvent.DefaultScoreColor;
                }

                image.AddEvents(events, sonogram.NyquistFrequency, sonogram.Configuration.FreqBinCount, sonogram.FramesPerSecond);
            }

            return(image.GetImage());
        }
Beispiel #40
0
 /// <summary>
 /// Erstellt eine neue Matrix.
 /// </summary>
 /// <param name="columns">Die Spaltenanzahl der Matrix.</param>
 /// <param name="rows">Die Zeilenanzahl der Matrix.</param>
 public Matrix(int columns, int rows)
 {
     ColumnCount = columns;
     RowCount    = rows;
     values      = new double[columns, rows];
 }
Beispiel #41
0
 // CONSTRUCTORS
 public GaussSole(double[,] aMatrix, double[] bVector)
     : this(aMatrix, bVector, 0.0001)
 {
 }
Beispiel #42
0
 /// <summary>Flooring.</summary>
 protected static double[,] floor(double[,] f)
 {
     return(Matrix.Floor(f));
 }
Beispiel #43
0
        /// <summary>
        /// Nonsymmetric reduction from Hessenberg to real Schur form.
        /// </summary>
        /// <param name="eigenVectors">The eigen vectors to work on.</param>
        /// <param name="matrixH">Array for internal storage of nonsymmetric Hessenberg form.</param>
        /// <param name="d">Arrays for internal storage of real parts of eigenvalues</param>
        /// <param name="e">Arrays for internal storage of imaginary parts of eigenvalues</param>
        /// <param name="order">Order of initial matrix</param>
        /// <remarks>This is derived from the Algol procedure hqr2,
        /// by Martin and Wilkinson, Handbook for Auto. Comp.,
        /// Vol.ii-Linear Algebra, and the corresponding
        /// Fortran subroutine in EISPACK.</remarks>
        static void NonsymmetricReduceHessenberToRealSchur(Matrix <double> eigenVectors, double[,] matrixH, double[] d, double[] e, int order)
        {
            // Initialize
            var    n = order - 1;
            var    eps = Precision.DoublePrecision;
            var    exshift = 0.0;
            double p = 0, q = 0, r = 0, s = 0, z = 0, w, x, y;

            // Store roots isolated by balanc and compute matrix norm
            var norm = 0.0;

            for (var i = 0; i < order; i++)
            {
                for (var j = Math.Max(i - 1, 0); j < order; j++)
                {
                    norm = norm + Math.Abs(matrixH[i, j]);
                }
            }

            // Outer loop over eigenvalue index
            var iter = 0;

            while (n >= 0)
            {
                // Look for single small sub-diagonal element
                var l = n;
                while (l > 0)
                {
                    s = Math.Abs(matrixH[l - 1, l - 1]) + Math.Abs(matrixH[l, l]);

                    if (s == 0.0)
                    {
                        s = norm;
                    }

                    if (Math.Abs(matrixH[l, l - 1]) < eps * s)
                    {
                        break;
                    }

                    l--;
                }

                // Check for convergence
                // One root found
                if (l == n)
                {
                    matrixH[n, n] = matrixH[n, n] + exshift;
                    d[n]          = matrixH[n, n];
                    e[n]          = 0.0;
                    n--;
                    iter = 0;

                    // Two roots found
                }
                else if (l == n - 1)
                {
                    w                     = matrixH[n, n - 1] * matrixH[n - 1, n];
                    p                     = (matrixH[n - 1, n - 1] - matrixH[n, n]) / 2.0;
                    q                     = (p * p) + w;
                    z                     = Math.Sqrt(Math.Abs(q));
                    matrixH[n, n]         = matrixH[n, n] + exshift;
                    matrixH[n - 1, n - 1] = matrixH[n - 1, n - 1] + exshift;
                    x                     = matrixH[n, n];

                    // Real pair
                    if (q >= 0)
                    {
                        if (p >= 0)
                        {
                            z = p + z;
                        }
                        else
                        {
                            z = p - z;
                        }

                        d[n - 1] = x + z;

                        d[n] = d[n - 1];
                        if (z != 0.0)
                        {
                            d[n] = x - (w / z);
                        }

                        e[n - 1] = 0.0;
                        e[n]     = 0.0;
                        x        = matrixH[n, n - 1];
                        s        = Math.Abs(x) + Math.Abs(z);
                        p        = x / s;
                        q        = z / s;
                        r        = Math.Sqrt((p * p) + (q * q));
                        p        = p / r;
                        q        = q / r;

                        // Row modification
                        for (var j = n - 1; j < order; j++)
                        {
                            z = matrixH[n - 1, j];
                            matrixH[n - 1, j] = (q * z) + (p * matrixH[n, j]);
                            matrixH[n, j]     = (q * matrixH[n, j]) - (p * z);
                        }

                        // Column modification
                        for (var i = 0; i <= n; i++)
                        {
                            z = matrixH[i, n - 1];
                            matrixH[i, n - 1] = (q * z) + (p * matrixH[i, n]);
                            matrixH[i, n]     = (q * matrixH[i, n]) - (p * z);
                        }

                        // Accumulate transformations
                        for (var i = 0; i < order; i++)
                        {
                            z = eigenVectors.At(i, n - 1);
                            eigenVectors.At(i, n - 1, (q * z) + (p * eigenVectors.At(i, n)));
                            eigenVectors.At(i, n, (q * eigenVectors.At(i, n)) - (p * z));
                        }

                        // Complex pair
                    }
                    else
                    {
                        d[n - 1] = x + p;
                        d[n]     = x + p;
                        e[n - 1] = z;
                        e[n]     = -z;
                    }

                    n    = n - 2;
                    iter = 0;

                    // No convergence yet
                }
                else
                {
                    // Form shift
                    x = matrixH[n, n];
                    y = 0.0;
                    w = 0.0;
                    if (l < n)
                    {
                        y = matrixH[n - 1, n - 1];
                        w = matrixH[n, n - 1] * matrixH[n - 1, n];
                    }

                    // Wilkinson's original ad hoc shift
                    if (iter == 10)
                    {
                        exshift += x;
                        for (var i = 0; i <= n; i++)
                        {
                            matrixH[i, i] -= x;
                        }

                        s = Math.Abs(matrixH[n, n - 1]) + Math.Abs(matrixH[n - 1, n - 2]);
                        x = y = 0.75 * s;
                        w = (-0.4375) * s * s;
                    }

                    // MATLAB's new ad hoc shift
                    if (iter == 30)
                    {
                        s = (y - x) / 2.0;
                        s = (s * s) + w;
                        if (s > 0)
                        {
                            s = Math.Sqrt(s);
                            if (y < x)
                            {
                                s = -s;
                            }

                            s = x - (w / (((y - x) / 2.0) + s));
                            for (var i = 0; i <= n; i++)
                            {
                                matrixH[i, i] -= s;
                            }

                            exshift += s;
                            x        = y = w = 0.964;
                        }
                    }

                    iter = iter + 1; // (Could check iteration count here.)

                    // Look for two consecutive small sub-diagonal elements
                    var m = n - 2;
                    while (m >= l)
                    {
                        z = matrixH[m, m];
                        r = x - z;
                        s = y - z;
                        p = (((r * s) - w) / matrixH[m + 1, m]) + matrixH[m, m + 1];
                        q = matrixH[m + 1, m + 1] - z - r - s;
                        r = matrixH[m + 2, m + 1];
                        s = Math.Abs(p) + Math.Abs(q) + Math.Abs(r);
                        p = p / s;
                        q = q / s;
                        r = r / s;

                        if (m == l)
                        {
                            break;
                        }

                        if (Math.Abs(matrixH[m, m - 1]) * (Math.Abs(q) + Math.Abs(r)) < eps * (Math.Abs(p) * (Math.Abs(matrixH[m - 1, m - 1]) + Math.Abs(z) + Math.Abs(matrixH[m + 1, m + 1]))))
                        {
                            break;
                        }

                        m--;
                    }

                    for (var i = m + 2; i <= n; i++)
                    {
                        matrixH[i, i - 2] = 0.0;
                        if (i > m + 2)
                        {
                            matrixH[i, i - 3] = 0.0;
                        }
                    }

                    // Double QR step involving rows l:n and columns m:n
                    for (var k = m; k <= n - 1; k++)
                    {
                        bool notlast = k != n - 1;

                        if (k != m)
                        {
                            p = matrixH[k, k - 1];
                            q = matrixH[k + 1, k - 1];
                            r = notlast ? matrixH[k + 2, k - 1] : 0.0;
                            x = Math.Abs(p) + Math.Abs(q) + Math.Abs(r);
                            if (x != 0.0)
                            {
                                p = p / x;
                                q = q / x;
                                r = r / x;
                            }
                        }

                        if (x == 0.0)
                        {
                            break;
                        }

                        s = Math.Sqrt((p * p) + (q * q) + (r * r));
                        if (p < 0)
                        {
                            s = -s;
                        }

                        if (s != 0.0)
                        {
                            if (k != m)
                            {
                                matrixH[k, k - 1] = (-s) * x;
                            }
                            else if (l != m)
                            {
                                matrixH[k, k - 1] = -matrixH[k, k - 1];
                            }

                            p = p + s;
                            x = p / s;
                            y = q / s;
                            z = r / s;
                            q = q / p;
                            r = r / p;

                            // Row modification
                            for (var j = k; j < order; j++)
                            {
                                p = matrixH[k, j] + (q * matrixH[k + 1, j]);

                                if (notlast)
                                {
                                    p = p + (r * matrixH[k + 2, j]);
                                    matrixH[k + 2, j] = matrixH[k + 2, j] - (p * z);
                                }

                                matrixH[k, j]     = matrixH[k, j] - (p * x);
                                matrixH[k + 1, j] = matrixH[k + 1, j] - (p * y);
                            }

                            // Column modification
                            for (var i = 0; i <= Math.Min(n, k + 3); i++)
                            {
                                p = (x * matrixH[i, k]) + (y * matrixH[i, k + 1]);

                                if (notlast)
                                {
                                    p = p + (z * matrixH[i, k + 2]);
                                    matrixH[i, k + 2] = matrixH[i, k + 2] - (p * r);
                                }

                                matrixH[i, k]     = matrixH[i, k] - p;
                                matrixH[i, k + 1] = matrixH[i, k + 1] - (p * q);
                            }

                            // Accumulate transformations
                            for (var i = 0; i < order; i++)
                            {
                                p = (x * eigenVectors.At(i, k)) + (y * eigenVectors.At(i, k + 1));

                                if (notlast)
                                {
                                    p = p + (z * eigenVectors.At(i, k + 2));
                                    eigenVectors.At(i, k + 2, eigenVectors.At(i, k + 2) - (p * r));
                                }

                                eigenVectors.At(i, k, eigenVectors.At(i, k) - p);
                                eigenVectors.At(i, k + 1, eigenVectors.At(i, k + 1) - (p * q));
                            }
                        } // (s != 0)
                    }     // k loop
                }         // check convergence
            }             // while (n >= low)

            // Backsubstitute to find vectors of upper triangular form
            if (norm == 0.0)
            {
                return;
            }

            for (n = order - 1; n >= 0; n--)
            {
                double t;

                p = d[n];
                q = e[n];

                // Real vector
                if (q == 0.0)
                {
                    var l = n;
                    matrixH[n, n] = 1.0;
                    for (var i = n - 1; i >= 0; i--)
                    {
                        w = matrixH[i, i] - p;
                        r = 0.0;
                        for (var j = l; j <= n; j++)
                        {
                            r = r + (matrixH[i, j] * matrixH[j, n]);
                        }

                        if (e[i] < 0.0)
                        {
                            z = w;
                            s = r;
                        }
                        else
                        {
                            l = i;
                            if (e[i] == 0.0)
                            {
                                if (w != 0.0)
                                {
                                    matrixH[i, n] = (-r) / w;
                                }
                                else
                                {
                                    matrixH[i, n] = (-r) / (eps * norm);
                                }

                                // Solve real equations
                            }
                            else
                            {
                                x             = matrixH[i, i + 1];
                                y             = matrixH[i + 1, i];
                                q             = ((d[i] - p) * (d[i] - p)) + (e[i] * e[i]);
                                t             = ((x * s) - (z * r)) / q;
                                matrixH[i, n] = t;
                                if (Math.Abs(x) > Math.Abs(z))
                                {
                                    matrixH[i + 1, n] = (-r - (w * t)) / x;
                                }
                                else
                                {
                                    matrixH[i + 1, n] = (-s - (y * t)) / z;
                                }
                            }

                            // Overflow control
                            t = Math.Abs(matrixH[i, n]);
                            if ((eps * t) * t > 1)
                            {
                                for (var j = i; j <= n; j++)
                                {
                                    matrixH[j, n] = matrixH[j, n] / t;
                                }
                            }
                        }
                    }

                    // Complex vector
                }
                else if (q < 0)
                {
                    var l = n - 1;

                    // Last vector component imaginary so matrix is triangular
                    if (Math.Abs(matrixH[n, n - 1]) > Math.Abs(matrixH[n - 1, n]))
                    {
                        matrixH[n - 1, n - 1] = q / matrixH[n, n - 1];
                        matrixH[n - 1, n]     = (-(matrixH[n, n] - p)) / matrixH[n, n - 1];
                    }
                    else
                    {
                        var res = Cdiv(0.0, -matrixH[n - 1, n], matrixH[n - 1, n - 1] - p, q);
                        matrixH[n - 1, n - 1] = res.Real;
                        matrixH[n - 1, n]     = res.Imaginary;
                    }

                    matrixH[n, n - 1] = 0.0;
                    matrixH[n, n]     = 1.0;
                    for (var i = n - 2; i >= 0; i--)
                    {
                        double ra = 0.0;
                        double sa = 0.0;
                        for (var j = l; j <= n; j++)
                        {
                            ra = ra + (matrixH[i, j] * matrixH[j, n - 1]);
                            sa = sa + (matrixH[i, j] * matrixH[j, n]);
                        }

                        w = matrixH[i, i] - p;

                        if (e[i] < 0.0)
                        {
                            z = w;
                            r = ra;
                            s = sa;
                        }
                        else
                        {
                            l = i;
                            if (e[i] == 0.0)
                            {
                                var res = Cdiv(-ra, -sa, w, q);
                                matrixH[i, n - 1] = res.Real;
                                matrixH[i, n]     = res.Imaginary;
                            }
                            else
                            {
                                // Solve complex equations
                                x = matrixH[i, i + 1];
                                y = matrixH[i + 1, i];

                                double vr = ((d[i] - p) * (d[i] - p)) + (e[i] * e[i]) - (q * q);
                                double vi = (d[i] - p) * 2.0 * q;
                                if ((vr == 0.0) && (vi == 0.0))
                                {
                                    vr = eps * norm * (Math.Abs(w) + Math.Abs(q) + Math.Abs(x) + Math.Abs(y) + Math.Abs(z));
                                }

                                var res = Cdiv((x * r) - (z * ra) + (q * sa), (x * s) - (z * sa) - (q * ra), vr, vi);
                                matrixH[i, n - 1] = res.Real;
                                matrixH[i, n]     = res.Imaginary;
                                if (Math.Abs(x) > (Math.Abs(z) + Math.Abs(q)))
                                {
                                    matrixH[i + 1, n - 1] = (-ra - (w * matrixH[i, n - 1]) + (q * matrixH[i, n])) / x;
                                    matrixH[i + 1, n]     = (-sa - (w * matrixH[i, n]) - (q * matrixH[i, n - 1])) / x;
                                }
                                else
                                {
                                    res = Cdiv(-r - (y * matrixH[i, n - 1]), -s - (y * matrixH[i, n]), z, q);
                                    matrixH[i + 1, n - 1] = res.Real;
                                    matrixH[i + 1, n]     = res.Imaginary;
                                }
                            }

                            // Overflow control
                            t = Math.Max(Math.Abs(matrixH[i, n - 1]), Math.Abs(matrixH[i, n]));
                            if ((eps * t) * t > 1)
                            {
                                for (var j = i; j <= n; j++)
                                {
                                    matrixH[j, n - 1] = matrixH[j, n - 1] / t;
                                    matrixH[j, n]     = matrixH[j, n] / t;
                                }
                            }
                        }
                    }
                }
            }

            // Back transformation to get eigenvectors of original matrix
            for (var j = order - 1; j >= 0; j--)
            {
                for (var i = 0; i < order; i++)
                {
                    z = 0.0;
                    for (var k = 0; k <= j; k++)
                    {
                        z = z + (eigenVectors.At(i, k) * matrixH[k, j]);
                    }

                    eigenVectors.At(i, j, z);
                }
            }
        }
Beispiel #44
0
        /// <summary>Cholesky decomposition.</summary>
        protected static double[,] chol(double[,] a)
        {
            var chol = new CholeskyDecomposition(a);

            return(chol.LeftTriangularFactor);
        }
 // метод розширення для отримання кількості стовпців матриці
 public static int ColumnsCount(this double[,] matrix)
 {
     return(matrix.GetUpperBound(1) + 1);
 }
Beispiel #46
0
    private void Sphere()
    {
        double r, m11, m12, m13, m14, m15;

        double[,] a =
        {
            { ZERO, ZERO, ZERO, ZERO },
            { ZERO, ZERO, ZERO, ZERO },
            { ZERO, ZERO, ZERO, ZERO },
            { ZERO, ZERO, ZERO, ZERO }
        };
        // Find minor 1, 1.
        for (int i = 0; i < 4; i++)
        {
            a[i, 0] = P[i, 0];
            a[i, 1] = P[i, 1];
            a[i, 2] = P[i, 2];
            a[i, 3] = 1;
        }
        m11 = this.Determinant(a, 4);
        // Find minor 1, 2.
        for (int i = 0; i < 4; i++)
        {
            a[i, 0] = P[i, 0] * P[i, 0] + P[i, 1] * P[i, 1] + P[i, 2] * P[i, 2];
            a[i, 1] = P[i, 1];
            a[i, 2] = P[i, 2];
            a[i, 3] = 1;
        }
        m12 = this.Determinant(a, 4);
        // Find minor 1, 3.
        for (int i = 0; i < 4; i++)
        {
            a[i, 0] = P[i, 0] * P[i, 0] + P[i, 1] * P[i, 1] + P[i, 2] * P[i, 2];
            a[i, 1] = P[i, 0];
            a[i, 2] = P[i, 2];
            a[i, 3] = 1;
        }
        m13 = this.Determinant(a, 4);
        // Find minor 1, 4.
        for (int i = 0; i < 4; i++)
        {
            a[i, 0] = P[i, 0] * P[i, 0] + P[i, 1] * P[i, 1] + P[i, 2] * P[i, 2];
            a[i, 1] = P[i, 0];
            a[i, 2] = P[i, 1];
            a[i, 3] = 1;
        }
        m14 = this.Determinant(a, 4);
        // Find minor 1, 5.
        for (int i = 0; i < 4; i++)
        {
            a[i, 0] = P[i, 0] * P[i, 0] + P[i, 1] * P[i, 1] + P[i, 2] * P[i, 2];
            a[i, 1] = P[i, 0];
            a[i, 2] = P[i, 1];
            a[i, 3] = P[i, 2];
        }
        m15 = this.Determinant(a, 4);
        // Calculate result.
        if (m11 == 0)
        {
            this.m_X0     = 0;
            this.m_Y0     = 0;
            this.m_Z0     = 0;
            this.m_Radius = 0;
        }
        else
        {
            this.m_X0     = 0.5 * m12 / m11;
            this.m_Y0     = -0.5 * m13 / m11;
            this.m_Z0     = 0.5 * m14 / m11;
            this.m_Radius = System.Math.Sqrt(this.m_X0 * this.m_X0 + this.m_Y0 * this.m_Y0 + this.m_Z0 * this.m_Z0 - m15 / m11);
        }
    }
Beispiel #47
0
        private double[,] Calc(double[,] _designmatrix, double[] _t)
        {
            double[,] _tT = new double[CONST.N, 1];
            double[] _y      = new double[CONST.N];
            double[] _design = new double[CONST.M];
            double[,] _designmatrixT = new double[CONST.M, CONST.N];
            double[,] _I             = new double[CONST.M, CONST.M];

            for (int j = 0; j < CONST.N; j++)
            {
                for (int i = 0; i < CONST.M; i++)
                {
                    _designmatrixT[i, j] = _designmatrix[j, i];
                }
            }

            for (int i = 0; i < CONST.N; i++)
            {
                _tT[i, 0] = _t[i];
            }

            double[,] _Designsquare = new double[CONST.M, CONST.M];
            double integer;

            for (int i = 0; i < CONST.M; i++)
            {
                for (int j = 0; j < CONST.M; j++)
                {
                    integer = 0;
                    for (int n = 0; n < CONST.N; n++)
                    {
                        integer += _designmatrixT[i, n] * _designmatrix[n, j];
                    }

                    _Designsquare[i, j] = integer;
                }
            }

            double buf;

            for (int i = 0; i < CONST.M; i++)
            {
                for (int j = 0; j < CONST.M; j++)
                {
                    _I[i, j] = 0;
                    if (i == j)
                    {
                        _I[i, j] = 1;
                    }
                }
            }
            for (int i = 0; i < CONST.M; i++)
            {
                buf = 1 / _Designsquare[i, i];
                for (int j = 0; j < CONST.M; j++)
                {
                    _Designsquare[i, j] *= buf;
                    _I[i, j]            *= buf;
                }
                for (int j = 0; j < CONST.M; j++)
                {
                    if (i != j)
                    {
                        buf = _Designsquare[j, i];
                        for (int k = 0; k < CONST.M; k++)
                        {
                            _Designsquare[j, k] -= _Designsquare[i, k] * buf;
                            _I[j, k]            -= _I[i, k] * buf;
                        }
                    }
                }
            }

            double[,] _design_t = new double[CONST.M, 1];
            double _integer2;

            for (int i = 0; i < CONST.M; i++)
            {
                _integer2 = 0;

                for (int j = 0; j < CONST.N; j++)
                {
                    _integer2 += _designmatrixT[i, j] * _tT[j, 0];
                }
                _design_t[i, 0] = _integer2;
            }


            double[,] _weight = new double[CONST.M, 1];

            for (int i = 0; i < CONST.M; i++)
            {
                _integer2 = 0;
                for (int j = 0; j < CONST.M; j++)
                {
                    _integer2 += _I[i, j] * _design_t[j, 0];
                }
                _weight[i, 0] = _integer2;
            }

            return(_weight);
        }
 public SimMatrix(int m, int n)
 {
     matrix = new double[m, n];
     this.m = m;
     this.n = n;
 }
Beispiel #49
0
 public static double Determinant(double [,] matrix)
 {
     return((matrix[0, 0] * matrix[1, 1]) - (matrix[0, 1] * matrix[1, 0]));
 }
        public Bitmap ConvertToKernel(Bitmap bmp, string sel, double[,] persKernel)
        {
            double[,] kernel = { { 0, 0, 0 }, { 0, 1, 0 }, { 0, 0, 0 } };
            if (string.IsNullOrEmpty(sel))
            {
                kernel = persKernel;
            }
            else
            {
                switch (sel)
                {
                case "Difuminar":
                    kernel = new double[3, 3] {
                        { 0.0625, 0.125, 0.0625 }, { 0.125, 0.25, 0.125 }, { 0.0625, 0.125, 0.0625 }
                    };
                    break;

                case "Realzar":
                    kernel = new double[3, 3] {
                        { -2, -1, 0 }, { -1, 1, 1 }, { 0, 1, 2 }
                    };
                    break;

                case "Sobel inferior":
                    kernel = new double[3, 3] {
                        { -1, -2, -1 }, { 0, 0, 0 }, { 1, 2, 1 }
                    };
                    break;

                case "Sobel superior":
                    kernel = new double[3, 3] {
                        { 1, 2, 1 }, { 0, 0, 0 }, { -1, -2, -1 }
                    };
                    break;

                case "Sobel izquierdo":
                    kernel = new double[3, 3] {
                        { 1, 0, -1 }, { 2, 0, -2 }, { 1, 0, -1 }
                    };
                    break;

                case "Soberl derecho":
                    kernel = new double[3, 3] {
                        { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 }
                    };
                    break;

                case "Contorno":
                    kernel = new double[3, 3] {
                        { -1, -1, -1 }, { -1, 8, -1 }, { -1, -1, -1 }
                    };
                    break;

                case "Afilar":
                    kernel = new double[3, 3] {
                        { 0, -1, 0 }, { -1, 5, -1 }, { 0, -1, 0 }
                    };
                    break;

                case "Original":
                    kernel = new double[3, 3] {
                        { 0, 0, 0 }, { 0, 1, 0 }, { 0, 0, 0 }
                    };
                    break;

                default:
                    break;
                }
            }

            Bitmap original = bmp;
            Bitmap clone    = new Bitmap(original);
            double sum      = 0;

            for (int i = 0; i < kernel.GetLength(0); i++)
            {
                for (int j = 0; j < kernel.GetLength(1); j++)
                {
                    sum += kernel[i, j];
                }
            }
            if (sum == 0)
            {
                sum = 1;
            }
            double val;

            for (int i = 0; i < original.Width - 2; i++)
            {
                for (int j = 0; j < original.Height - 2; j++)
                {
                    val = (kernel[0, 0] * original.GetPixel(i, j).R) + (kernel[0, 1] * original.GetPixel(i, j + 1).R) +
                          (kernel[0, 2] * original.GetPixel(i, j + 2).R) + (kernel[1, 0] * original.GetPixel(i + 1, j).R) +
                          (kernel[1, 1] * original.GetPixel(i + 1, j + 1).R) + (kernel[1, 2] * original.GetPixel(i + 1, j + 2).R) +
                          (kernel[2, 0] * original.GetPixel(i + 2, j).R) + (kernel[2, 1] * original.GetPixel(i + 2, j + 1).R) +
                          (kernel[2, 2] * original.GetPixel(i + 2, j + 2).R);

                    val /= sum;
                    if (val < 0)
                    {
                        val = 0;
                    }
                    else if (val > 255)
                    {
                        val = 255;
                    }
                    Color newColor = Color.FromArgb((int)val, (int)val, (int)val);
                    clone.SetPixel(i + 1, j + 1, newColor);
                    if (i == 0 && j == original.Height - 2)
                    {
                        clone.SetPixel(i, j + 1, newColor);
                        clone.SetPixel(i, j + 2, newColor);
                        clone.SetPixel(i + 1, j + 2, newColor);
                        clone.SetPixel(i, j, newColor);
                    }
                    else if (j == 0 && i == original.Width - 2)
                    {
                        clone.SetPixel(i + 1, j, newColor);
                        clone.SetPixel(i + 2, j, newColor);
                        clone.SetPixel(i + 2, j + 1, newColor);
                        clone.SetPixel(i, j, newColor);
                    }
                    else if (i == original.Width - 2 && j == original.Height - 2)
                    {
                        clone.SetPixel(i + 2, j + 1, newColor);
                        clone.SetPixel(i + 1, j + 2, newColor);
                        clone.SetPixel(i + 2, j + 2, newColor);
                    }
                    else if (j == original.Height - 2)
                    {
                        clone.SetPixel(i + 1, j + 2, newColor);
                    }
                    else if (i == original.Width - 2)
                    {
                        clone.SetPixel(i + 2, j + 1, newColor);
                    }
                    else if (j == 0)
                    {
                        clone.SetPixel(i, j, newColor);
                    }
                    else if (i == 0)
                    {
                        clone.SetPixel(i, j, newColor);
                    }
                }
            }
            return(clone);
        }
Beispiel #51
0
 public Matrix(double[,] arr)
 {
     matrixValues = arr;
 }
Beispiel #52
0
        /// <summary>
        /// 1Dヘルムホルツ方程式固有値問題の要素行列を加算する
        /// </summary>
        /// <param name="waveLength">波長(E面の場合のみ使用する)</param>
        /// <param name="element">線要素</param>
        /// <param name="coords">座標リスト</param>
        /// <param name="toSorted">節点番号→ソート済み節点インデックスマップ</param>
        /// <param name="Medias">媒質情報リスト</param>
        /// <param name="WaveModeDv">計算する波のモード区分</param>
        /// <param name="txx_1d">txx行列</param>
        /// <param name="ryy_1d">ryy行列</param>
        /// <param name="uzz_1d">uzz行列</param>
        public static void AddElementMatOf1dEigenValueProblem(
            double waveLength,
            FemLineElement element,
            IList <double> coords,
            Dictionary <int, int> toSorted,
            MediaInfo[] Medias,
            FemSolver.WaveModeDV WaveModeDv,
            ref MyDoubleMatrix txx_1d, ref MyDoubleMatrix ryy_1d, ref MyDoubleMatrix uzz_1d)
        {
            // 定数
            const double pi = Constants.pi;
            const double c0 = Constants.c0;
            // 波数
            double k0 = 2.0 * pi / waveLength;
            // 角周波数
            double omega = k0 * c0;

            // 2次線要素
            const int nno = Constants.LineNodeCnt_SecondOrder; // 3;

            int[] nodeNumbers = element.NodeNumbers;
            System.Diagnostics.Debug.Assert(nno == nodeNumbers.Length);

            // 座標の取得
            double[] elementCoords = new double[nno];
            for (int n = 0; n < nno; n++)
            {
                int nodeIndex = nodeNumbers[n] - 1;
                elementCoords[n] = coords[nodeIndex];
            }
            // 線要素の長さ
            double elen = Math.Abs(elementCoords[1] - elementCoords[0]);
            // 媒質インデックス
            int mediaIndex = element.MediaIndex;
            // 媒質
            MediaInfo media = Medias[mediaIndex];

            double[,] media_P = null;
            double[,] media_Q = null;
            // ヘルムホルツ方程式のパラメータP,Qを取得する
            FemSolver.GetHelmholtzMediaPQ(
                k0,
                media,
                WaveModeDv,
                out media_P,
                out media_Q);

            double[,] integralN = new double[nno, nno]
            {
                { 4.0 / 30.0 * elen, -1.0 / 30.0 * elen, 2.0 / 30.0 * elen },
                { -1.0 / 30.0 * elen, 4.0 / 30.0 * elen, 2.0 / 30.0 * elen },
                { 2.0 / 30.0 * elen, 2.0 / 30.0 * elen, 16.0 / 30.0 * elen },
            };
            double[,] integralDNDY = new double[nno, nno]
            {
                { 7.0 / (3.0 * elen), 1.0 / (3.0 * elen), -8.0 / (3.0 * elen) },
                { 1.0 / (3.0 * elen), 7.0 / (3.0 * elen), -8.0 / (3.0 * elen) },
                { -8.0 / (3.0 * elen), -8.0 / (3.0 * elen), 16.0 / (3.0 * elen) },
            };

            for (int ino = 0; ino < nno; ino++)
            {
                int inoBoundary = nodeNumbers[ino];
                int inoSorted;
                if (!toSorted.ContainsKey(inoBoundary))
                {
                    continue;
                }
                inoSorted = toSorted[inoBoundary];
                for (int jno = 0; jno < nno; jno++)
                {
                    int jnoBoundary = nodeNumbers[jno];
                    int jnoSorted;
                    if (!toSorted.ContainsKey(jnoBoundary))
                    {
                        continue;
                    }
                    jnoSorted = toSorted[jnoBoundary];
                    // 対称バンド行列対応
                    if (ryy_1d is MyDoubleSymmetricBandMatrix && jnoSorted < inoSorted)
                    {
                        continue;
                    }

                    double e_txx_1d_inojno = media_P[0, 0] * integralDNDY[ino, jno];
                    double e_ryy_1d_inojno = media_P[1, 1] * integralN[ino, jno];
                    double e_uzz_1d_inojno = media_Q[2, 2] * integralN[ino, jno];
                    //txx_1d[inoSorted, jnoSorted] += e_txx_1d_inojno;
                    //ryy_1d[inoSorted, jnoSorted] += e_ryy_1d_inojno;
                    //uzz_1d[inoSorted, jnoSorted] += e_uzz_1d_inojno;
                    txx_1d._body[txx_1d.GetBufferIndex(inoSorted, jnoSorted)] += e_txx_1d_inojno;
                    ryy_1d._body[ryy_1d.GetBufferIndex(inoSorted, jnoSorted)] += e_ryy_1d_inojno;
                    uzz_1d._body[uzz_1d.GetBufferIndex(inoSorted, jnoSorted)] += e_uzz_1d_inojno;
                }
            }
        }
Beispiel #53
0
 public GameData(double[,] GrassArray, double[,] SandArray, double[,] TreeArray, double[,] BerryBushArray, double[,] EmptyBushArray
                 , double[,] RockArray)
 {
     grassArray     = GrassArray;
     sandArray      = SandArray;
     treeArray      = TreeArray;
     berryBushArray = BerryBushArray;
     emptyBushArray = EmptyBushArray;
     rockArray      = RockArray;
 }
        /// <summary>
        /// only for debugging and testing; converts the matrix to a full matrix;
        /// when running in parallel, the matrix is collected on process 0.
        /// </summary>
        /// <returns>
        /// null on all MPI processes, except on rank 0;
        /// </returns>
        static public MultidimensionalArray ToFullMatrixOnProc0(this IMutableMatrixEx tis)
        {
            var comm = tis.MPI_Comm;
            int Rank = tis.RowPartitioning.MpiRank;
            int Size = tis.RowPartitioning.MpiSize;

            double[,] ret = null;
            if (Rank == 0)
            {
                ret = new double[tis.NoOfRows, tis.NoOfCols];
            }

            SerialisationMessenger sms = new SerialisationMessenger(comm);

            if (Rank > 0)
            {
                sms.SetCommPath(0);
            }
            sms.CommitCommPaths();

            Tuple <int, int[], double[]>[] data;
            {
                int L = tis.RowPartitioning.LocalLength;
                data = new Tuple <int, int[], double[]> [L];

                int i0 = (int)tis.RowPartitioning.i0;
                for (int i = 0; i < L; i++)
                {
                    double[] val = null; // this mem. must be inside the loop/allocated for every i and cannot be reused because we need all rows later.
                    int[]    col = null;
                    int      Lr  = tis.GetRow(i + i0, ref col, ref val);
                    data[i] = new Tuple <int, int[], double[]>(Lr, col, val);
                }
            }

            if (Rank > 0)
            {
                sms.Transmit(0, data);
            }

            int rcvProc = 0;

            if (Rank == 0)
            {
                do
                {
                    int i0 = (int)tis.RowPartitioning.GetI0Offest(rcvProc);
                    if (data.Length != tis.RowPartitioning.GetLocalLength(rcvProc))
                    {
                        throw new ApplicationException("internal error");
                    }

                    for (int i = 0; i < data.Length; i++)
                    {
                        //foreach (MsrMatrix.MatrixEntry entry in data[i]) {
                        //    if (entry.m_ColIndex >= 0)
                        //        ret[i + i0, entry.m_ColIndex] = entry.Value;
                        //}
                        int      Lr  = data[i].Item1;
                        int[]    col = data[i].Item2;
                        double[] val = data[i].Item3;
                        for (int lr = 0; lr < Lr; lr++)
                        {
                            ret[i + i0, col[lr]] = val[lr];
                        }
                    }
                } while (sms.GetNext(out rcvProc, out data));
            }
            else
            {
                if (sms.GetNext(out rcvProc, out data))
                {
                    throw new ApplicationException("internal error");
                }
            }

            if (Rank == 0)
            {
                var _ret = MultidimensionalArray.Create(ret.GetLength(0), ret.GetLength(1));
                for (int i = 0; i < _ret.NoOfRows; i++)
                {
                    for (int j = 0; j < _ret.NoOfCols; j++)
                    {
                        _ret[i, j] = ret[i, j];
                    }
                }
                return(_ret);
            }
            else
            {
                return(null);
            }
        }
Beispiel #55
0
 /// <summary>Absolute value.</summary>
 protected static mat abs(double[,] d)
 {
     return(Matrix.Apply(d, x => System.Math.Abs(x)));
 }
Beispiel #56
0
        private static double[,] InterpolateResult(double[,] dataNoises,
                                                   Vector3I NoiseSampledSteps,
                                                   Vector3I StepsCount)
        {
            int nbrNoises = dataNoises.GetLength(1);

            //Create a new array with expended size
            double[,] result = new double[StepsCount.X * StepsCount.Y * StepsCount.Z, nbrNoises];

            int dataNoisesXSize = NoiseSampledSteps.X + 1;
            int dataNoisesYSize = NoiseSampledSteps.Y + 1;
            int dataNoisesZSize = NoiseSampledSteps.Z + 1;

            int XPointLerpedCount = StepsCount.X / NoiseSampledSteps.X;
            int ZPointLerpedCount = StepsCount.Z / NoiseSampledSteps.Z;
            int YPointLerpedCount = StepsCount.Y / NoiseSampledSteps.Y;

            //Loop against the generated noise values
            int noiseGeneratedResultIndex = 0;

            for (int noiseId = 0; noiseId < nbrNoises; noiseId++)
            {
                for (int SampledpointX = 0; SampledpointX < NoiseSampledSteps.X; SampledpointX++)
                {
                    for (int SampledpointZ = 0; SampledpointZ < NoiseSampledSteps.Z; SampledpointZ++)
                    {
                        for (int SampledpointY = 0; SampledpointY < NoiseSampledSteps.Y; SampledpointY++)
                        {
                            double NoiseX0Z0Y0 = dataNoises[((SampledpointX + 0) * dataNoisesZSize + (SampledpointZ + 0)) * dataNoisesYSize + (SampledpointY + 0), noiseId];
                            double NoiseX0Z1Y0 = dataNoises[((SampledpointX + 0) * dataNoisesZSize + (SampledpointZ + 1)) * dataNoisesYSize + (SampledpointY + 0), noiseId];
                            double NoiseX1Z0Y0 = dataNoises[((SampledpointX + 1) * dataNoisesZSize + (SampledpointZ + 0)) * dataNoisesYSize + (SampledpointY + 0), noiseId];
                            double NoiseX1Z1Y0 = dataNoises[((SampledpointX + 1) * dataNoisesZSize + (SampledpointZ + 1)) * dataNoisesYSize + (SampledpointY + 0), noiseId];

                            double DeltaX0Z0 = (dataNoises[((SampledpointX + 0) * dataNoisesZSize + (SampledpointZ + 0)) * dataNoisesYSize + (SampledpointY + 1), noiseId] - NoiseX0Z0Y0) / YPointLerpedCount; // 128 / 16 = 8 points need to be lerped 4 times !
                            double DeltaX0Z1 = (dataNoises[((SampledpointX + 0) * dataNoisesZSize + (SampledpointZ + 1)) * dataNoisesYSize + (SampledpointY + 1), noiseId] - NoiseX0Z1Y0) / YPointLerpedCount; // 128 / 16 = 8 points need to be lerped 4 times !
                            double DeltaX1Z0 = (dataNoises[((SampledpointX + 1) * dataNoisesZSize + (SampledpointZ + 0)) * dataNoisesYSize + (SampledpointY + 1), noiseId] - NoiseX1Z0Y0) / YPointLerpedCount; // 128 / 16 = 8 points need to be lerped 4 times !
                            double DeltaX1Z1 = (dataNoises[((SampledpointX + 1) * dataNoisesZSize + (SampledpointZ + 1)) * dataNoisesYSize + (SampledpointY + 1), noiseId] - NoiseX1Z1Y0) / YPointLerpedCount; // 128 / 16 = 8 points need to be lerped 4 times !

                            for (int Y = 0; Y < YPointLerpedCount; Y++)
                            {
                                double NoiseZ0 = NoiseX0Z0Y0;
                                double NoiseZ1 = NoiseX1Z0Y0;
                                double DeltaZ0 = (NoiseX0Z1Y0 - NoiseX0Z0Y0) / ZPointLerpedCount; // Chunk X length = 16 / 4 = 4 points needs to be lerped Twice!
                                double DeltaZ1 = (NoiseX1Z1Y0 - NoiseX1Z0Y0) / ZPointLerpedCount;
                                int    nY      = (SampledpointY * YPointLerpedCount) + Y;

                                for (int Z = 0; Z < ZPointLerpedCount; Z++)
                                {
                                    double NoiseFinalValue = NoiseZ0;
                                    double DeltaX          = (NoiseZ1 - NoiseZ0) / XPointLerpedCount; // Chunk Z length = 16 / 4 = 4 points needs to be lerped Once!
                                    int    nZ = (SampledpointZ * ZPointLerpedCount) + Z;
                                    for (int X = 0; X < XPointLerpedCount; X++)
                                    {
                                        int nX = (SampledpointX * XPointLerpedCount) + X;
                                        result[nX * StepsCount.Z * StepsCount.Y + nZ * StepsCount.Y + nY, noiseId] = NoiseFinalValue;

                                        noiseGeneratedResultIndex++;

                                        NoiseFinalValue += DeltaX;
                                    }
                                    NoiseZ0 += DeltaZ0;
                                    NoiseZ1 += DeltaZ1;
                                }
                                NoiseX0Z0Y0 += DeltaX0Z0;
                                NoiseX0Z1Y0 += DeltaX0Z1;
                                NoiseX1Z0Y0 += DeltaX1Z0;
                                NoiseX1Z1Y0 += DeltaX1Z1;
                            }
                        }
                    }
                }
            }

            return(result);
        }
Beispiel #57
0
 /// <summary>Sin.</summary>
 protected static mat sin(double[,] d)
 {
     return(Matrix.Apply(d, x => System.Math.Sin(x)));
 }
Beispiel #58
0
        public void Loop(double[,] pe, double[][][] xr_org, double[,,,] ratio_s, double[,,] ratio_l, ref SideInfo l3_side, int[][][] l3_enc, int mean_bits, int chn, double[][][] xr_dec, int[][][] scalefact_l, int[][][][] scalefact_s, ref FrameParams fr_ps, int ancillary_pad, int bitsPerFrame)
        {
            int    max_bits;
            int    ch, gr, i, sfb, b, scfsi_band;
            int    mode_gr;
            int    start, end;
            double sum1, sum2, temp, x;
            double log2;


            double[,,] xmin_l  = new double[2, 2, 21];
            double[,,,] xmin_s = new double[2, 2, 12, 3];
            double[] abs_xr   = new double[576];
            double[] energy_l = new double[22];
            double[,] en_tot = new double[2, 2];
            double[,,] en    = new double[2, 2, 21];
            double[,,] xm    = new double[2, 2, 21];
            int[,] xrAllZero = new int[2, 2];



            int en_tot_krit        = 10;
            int en_dif_krit        = 100;
            int en_scfsi_band_krit = 10;
            int xm_scfsi_band_krit = 10;



            log2 = Math.Log(2.0);
            l3_side.ResvDrain = 0;

            if (fInit_iteration_loop == 0)
            {
                l3_side.MainDataBegin = 0;
                fInit_iteration_loop  = 1;
            }
            mode_gr = 2;

            scalefac_band_long  = Tables.SfBandIndex[fr_ps.Header.SamplingFrequency][0];
            scalefac_band_short = Tables.SfBandIndex[fr_ps.Header.SamplingFrequency][1];

            reserv.ResvFrameBegin(ref fr_ps, ref l3_side, mean_bits, bitsPerFrame);

            for (gr = 0; gr < mode_gr; gr++)
            {
                for (ch = 0; ch < chn; ch++)
                {
                    for (i = 0; i < 576; i++)
                    {
                        abs_xr[i] = Math.Abs(xr_org[ch][gr][i]);
                    }

                    if (l3_side.TT[ch, gr].WindowSwitchingFlag != 0 && l3_side.TT[ch, gr].BlockType == 2)
                    {
                        if (l3_side.TT[ch, gr].MixedBlockFlag != 0)
                        {
                            l3_side.TT[ch, gr].SfbLmax = 8;
                            l3_side.TT[ch, gr].SfbSmax = 3;
                        }
                        else
                        {
                            l3_side.TT[ch, gr].SfbLmax = 0;
                            l3_side.TT[ch, gr].SfbSmax = 0;
                        }
                    }
                    else
                    {
                        l3_side.TT[ch, gr].SfbLmax = 21;
                        l3_side.TT[ch, gr].SfbSmax = 12;
                    }

                    sum1 = 0;
                    sum2 = 0;
                    for (sfb = 0; sfb < 22; sfb++)
                    {
                        start = scalefac_band_long[sfb];
                        end   = scalefac_band_long[sfb + 1];
                        temp  = 0;
                        for (i = start; i < end; i++)
                        {
                            if ((x = abs_xr[i]) != 0)
                            {
                                temp += x * x;
                                sum1 += Math.Log(x);
                            }
                        }

                        sum2 += energy_l[sfb] = temp;

                        if (sfb < l3_side.TT[ch, gr].SfbLmax)
                        {
                            xmin_l[ch, gr, sfb] = ratio_l[ch, gr, sfb] * temp / (end - start);
                        }
                    }

                    for (sfb = l3_side.TT[ch, gr].SfbSmax; sfb < 12; sfb++)
                    {
                        start = scalefac_band_short[sfb];
                        end   = scalefac_band_short[sfb + 1];
                        for (b = 0; b < 3; b++)
                        {
                            temp = 0.0;
                            for (i = start; i < end; i++)
                            {
                                temp += abs_xr[i * 3 + b] * abs_xr[i * 3 + b];
                            }
                            xmin_s[ch, gr, sfb, b] = ratio_s[ch, gr, sfb, b] * temp / (end - start);
                        }
                    }

                    xrAllZero[ch, gr] = 1;

                    if (l3_side.TT[ch, gr].WindowSwitchingFlag == 0 || (l3_side.TT[ch, gr].BlockType != 2))
                    {
                        for (sfb = 0; sfb < 21; sfb++)
                        {
                            if (xmin_l[ch, gr, sfb] == 0)
                            {
                                xm[ch, gr, sfb] = 0;
                            }
                            else
                            {
                                xm[ch, gr, sfb] = Math.Log(xmin_l[ch, gr, sfb]) / log2;
                            }
                        }

                        if (gr == 1)
                        {
                            for (scfsi_band = 0; scfsi_band < 4; scfsi_band++)
                            {
                                l3_side.Scfsi[ch, scfsi_band] = 0;
                            }

                            if (xrAllZero[ch, 0] == 0 || xrAllZero[ch, 1] == 0)
                            {
                                if (Math.Abs(en_tot[ch, 0] - en_tot[ch, 1]) < en_tot_krit)
                                {
                                    temp = 0.0;
                                    for (sfb = 0; sfb < 21; sfb++)
                                    {
                                        temp += Math.Abs(en[ch, 0, sfb] - en[ch, 1, sfb]);
                                    }
                                    if (temp < en_dif_krit)
                                    {
                                        for (scfsi_band = 0; scfsi_band < 4; scfsi_band++)
                                        {
                                            sum1 = 0;
                                            sum2 = 0;

                                            start = scfsi_band_long[scfsi_band];
                                            end   = scfsi_band_long[scfsi_band + 1];
                                            for (sfb = start; sfb < end; sfb++)
                                            {
                                                sum1 += Math.Abs(en[ch, 0, sfb] - en[ch, 1, sfb]);
                                                sum2 += Math.Abs(xm[ch, 0, sfb] - xm[ch, 1, sfb]);
                                            }

                                            if (sum1 < en_scfsi_band_krit && sum2 < xm_scfsi_band_krit)
                                            {
                                                l3_side.Scfsi[ch, scfsi_band] = 1;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    max_bits = reserv.ResvMaxBits(ref fr_ps, ref l3_side, ref pe[ch, gr], mean_bits);

                    for (sfb = 0; sfb < 21; sfb++)
                    {
                        scalefact_l[ch][gr][sfb] = 0;
                    }
                    for (sfb = 0; sfb < 12; sfb++)
                    {
                        for (b = 0; b < 3; b++)
                        {
                            scalefact_s[ch][gr][sfb][b] = 0;
                        }
                    }

                    for (scfsi_band = 0; scfsi_band < 4; scfsi_band++)
                    {
                        l3_side.TT[ch, gr].Slen[scfsi_band] = 0;
                    }

                    l3_side.TT[ch, gr].SfbPartitionTable = nr_of_sfb_block;
                    l3_side.TT[ch, gr].Part23Length      = 0;
                    l3_side.TT[ch, gr].BigValues         = 0;
                    l3_side.TT[ch, gr].Count1            = 0;
                    l3_side.TT[ch, gr].ScalefacCompress  = 0;
                    l3_side.TT[ch, gr].TableSelect[0]    = 0;
                    l3_side.TT[ch, gr].TableSelect[1]    = 0;
                    l3_side.TT[ch, gr].TableSelect[2]    = 0;
                    l3_side.TT[ch, gr].SubblockGain[0]   = 0;
                    l3_side.TT[ch, gr].SubblockGain[1]   = 0;
                    l3_side.TT[ch, gr].SubblockGain[2]   = 0;
                    l3_side.TT[ch, gr].Region0Count      = 0;
                    l3_side.TT[ch, gr].Region1Count      = 0;
                    l3_side.TT[ch, gr].Part2Length       = 0;
                    l3_side.TT[ch, gr].Preflag           = 0;
                    l3_side.TT[ch, gr].ScalefacScale     = 0;
                    l3_side.TT[ch, gr].QuantizerStepSize = 0;
                    l3_side.TT[ch, gr].Count1tableSelect = 0;

                    int system_const = 8;
                    int minlimit     = -100;

                    if (sum2 != 0)
                    {
                        temp = Nint(system_const * (sum1 / 288 - Math.Log(sum2 / 576)));
                        if (temp < minlimit)
                        {
                            temp = minlimit;
                        }

                        temp -= 70;
                        l3_side.TT[ch, gr].QuantizerStepSize = temp;
                        l3_side.TT[ch, gr].Part23Length      = OuterLoop(abs_xr, max_bits, xmin_l, xmin_s, l3_enc[ch][gr], ref fr_ps, scalefact_l, scalefact_s, gr, ch, ref l3_side);
                    }

                    reserv.ResvAdjust(ref fr_ps, ref l3_side.TT[ch, gr], ref l3_side, mean_bits);

                    l3_side.TT[ch, gr].GlobalGain = Nint(l3_side.TT[ch, gr].QuantizerStepSize + 210.0);
                }
            }
            reserv.ResvFrameEnd(ref fr_ps, ref l3_side, mean_bits);
        }
        /// <summary>
        /// THE KEY ANALYSIS METHOD.
        /// </summary>
        public static Tuple <BaseSonogram, double[, ], double[], List <AcousticEvent>, Image> Analysis(
            AudioRecording recording,
            SonogramConfig sonoConfig,
            LitoriaBicolorConfig lbConfig,
            bool drawDebugImage,
            TimeSpan segmentStartOffset)
        {
            double decibelThreshold   = lbConfig.DecibelThreshold; //dB
            double intensityThreshold = lbConfig.IntensityThreshold;

            //double eventThreshold = lbConfig.EventThreshold; //in 0-1

            if (recording == null)
            {
                LoggedConsole.WriteLine("AudioRecording == null. Analysis not possible.");
                return(null);
            }

            //i: MAKE SONOGRAM
            //TimeSpan tsRecordingtDuration = recording.Duration();
            int    sr              = recording.SampleRate;
            double freqBinWidth    = sr / (double)sonoConfig.WindowSize;
            double framesPerSecond = freqBinWidth;

            // duration of DCT in seconds - want it to be about 3X or 4X the expected maximum period
            double dctDuration = 3 * lbConfig.MaxPeriod;

            // duration of DCT in frames
            int dctLength = (int)Math.Round(framesPerSecond * dctDuration);

            // set up the cosine coefficients
            double[,] cosines = MFCCStuff.Cosines(dctLength, dctLength);

            int upperBandMinBin = (int)Math.Round(lbConfig.UpperBandMinHz / freqBinWidth) + 1;
            int upperBandMaxBin = (int)Math.Round(lbConfig.UpperBandMaxHz / freqBinWidth) + 1;
            int lowerBandMinBin = (int)Math.Round(lbConfig.LowerBandMinHz / freqBinWidth) + 1;
            int lowerBandMaxBin = (int)Math.Round(lbConfig.LowerBandMaxHz / freqBinWidth) + 1;

            BaseSonogram sonogram = new SpectrogramStandard(sonoConfig, recording.WavReader);
            int          rowCount = sonogram.Data.GetLength(0);
            int          colCount = sonogram.Data.GetLength(1);

            double[] lowerArray = MatrixTools.GetRowAveragesOfSubmatrix(sonogram.Data, 0, lowerBandMinBin, rowCount - 1, lowerBandMaxBin);
            double[] upperArray = MatrixTools.GetRowAveragesOfSubmatrix(sonogram.Data, 0, upperBandMinBin, rowCount - 1, upperBandMaxBin);

            //lowerArray = DataTools.filterMovingAverage(lowerArray, 3);
            //upperArray = DataTools.filterMovingAverage(upperArray, 3);

            double[] amplitudeScores  = DataTools.SumMinusDifference(lowerArray, upperArray);
            double[] differenceScores = DspFilters.PreEmphasis(amplitudeScores, 1.0);

            // Could smooth here rather than above. Above seemed slightly better?
            amplitudeScores  = DataTools.filterMovingAverage(amplitudeScores, 7);
            differenceScores = DataTools.filterMovingAverage(differenceScores, 7);

            //iii: CONVERT decibel sum-diff SCORES TO ACOUSTIC EVENTS
            var predictedEvents = AcousticEvent.ConvertScoreArray2Events(
                amplitudeScores,
                lbConfig.LowerBandMinHz,
                lbConfig.UpperBandMaxHz,
                sonogram.FramesPerSecond,
                freqBinWidth,
                decibelThreshold,
                lbConfig.MinDuration,
                lbConfig.MaxDuration,
                segmentStartOffset);

            for (int i = 0; i < differenceScores.Length; i++)
            {
                if (differenceScores[i] < 1.0)
                {
                    differenceScores[i] = 0.0;
                }
            }

            // init the score array
            double[] scores = new double[rowCount];

            //iii: CONVERT SCORES TO ACOUSTIC EVENTS
            // var hits = new double[rowCount, colCount];
            double[,] hits = null;

            // init confirmed events
            var confirmedEvents = new List <AcousticEvent>();

            // add names into the returned events
            foreach (var ae in predictedEvents)
            {
                //rowtop,  rowWidth
                int    eventStart       = ae.Oblong.RowTop;
                int    eventWidth       = ae.Oblong.RowWidth;
                int    step             = 2;
                double maximumIntensity = 0.0;

                // scan the event to get oscillation period and intensity
                for (int i = eventStart - (dctLength / 2); i < eventStart + eventWidth - (dctLength / 2); i += step)
                {
                    // Look for oscillations in the difference array
                    double[] differenceArray = DataTools.Subarray(differenceScores, i, dctLength);
                    Oscillations2014.GetOscillationUsingDct(differenceArray, framesPerSecond, cosines, out var oscilFreq, out var period, out var intensity);

                    bool periodWithinBounds = period > lbConfig.MinPeriod && period < lbConfig.MaxPeriod;

                    //Console.WriteLine($"step={i}    period={period:f4}");

                    if (!periodWithinBounds)
                    {
                        continue;
                    }

                    // lay down score for sample length
                    for (int j = 0; j < dctLength; j++)
                    {
                        if (scores[i + j] < intensity)
                        {
                            scores[i + j] = intensity;
                        }
                    }

                    if (maximumIntensity < intensity)
                    {
                        maximumIntensity = intensity;
                    }
                }

                // add abbreviatedSpeciesName into event
                if (maximumIntensity >= intensityThreshold)
                {
                    ae.Name             = "L.b";
                    ae.Score_MaxInEvent = maximumIntensity;
                    confirmedEvents.Add(ae);
                }
            }

            //######################################################################

            // calculate the cosine similarity scores
            var scorePlot = new Plot(lbConfig.SpeciesName, scores, intensityThreshold);

            //DEBUG IMAGE this recognizer only. MUST set false for deployment.
            Image debugImage = null;

            if (drawDebugImage)
            {
                // display a variety of debug score arrays

                //DataTools.Normalise(scores, eventDecibelThreshold, out normalisedScores, out normalisedThreshold);
                //var debugPlot = new Plot("Score", normalisedScores, normalisedThreshold);
                //DataTools.Normalise(upperArray, eventDecibelThreshold, out normalisedScores, out normalisedThreshold);
                //var upperPlot = new Plot("Upper", normalisedScores, normalisedThreshold);
                //DataTools.Normalise(lowerArray, eventDecibelThreshold, out normalisedScores, out normalisedThreshold);
                //var lowerPlot = new Plot("Lower", normalisedScores, normalisedThreshold);
                DataTools.Normalise(amplitudeScores, decibelThreshold, out var normalisedScores, out var normalisedThreshold);
                var sumDiffPlot = new Plot("SumMinusDifference", normalisedScores, normalisedThreshold);
                DataTools.Normalise(differenceScores, 3.0, out normalisedScores, out normalisedThreshold);
                var differencePlot = new Plot("Difference", normalisedScores, normalisedThreshold);

                var debugPlots = new List <Plot> {
                    scorePlot, sumDiffPlot, differencePlot
                };

                // other debug plots
                //var debugPlots = new List<Plot> { scorePlot, upperPlot, lowerPlot, sumDiffPlot, differencePlot };
                debugImage = DisplayDebugImage(sonogram, confirmedEvents, debugPlots, hits);
            }

            // return new sonogram because it makes for more easy interpretation of the image
            var returnSonoConfig = new SonogramConfig
            {
                SourceFName   = recording.BaseName,
                WindowSize    = 512,
                WindowOverlap = 0,

                // the default window is HAMMING
                //WindowFunction = WindowFunctions.HANNING.ToString(),
                //WindowFunction = WindowFunctions.NONE.ToString(),
                // if do not use noise reduction can get a more sensitive recogniser.
                //NoiseReductionType = NoiseReductionType.NONE,
                NoiseReductionType = SNR.KeyToNoiseReductionType("STANDARD"),
            };
            BaseSonogram returnSonogram = new SpectrogramStandard(returnSonoConfig, recording.WavReader);

            return(Tuple.Create(returnSonogram, hits, scores, confirmedEvents, debugImage));
        } //Analysis()
Beispiel #60
0
        /// <summary>
        /// Nonsymmetric reduction to Hessenberg form.
        /// </summary>
        /// <param name="eigenVectors">The eigen vectors to work on.</param>
        /// <param name="matrixH">Array for internal storage of nonsymmetric Hessenberg form.</param>
        /// <param name="order">Order of initial matrix</param>
        /// <remarks>This is derived from the Algol procedures orthes and ortran,
        /// by Martin and Wilkinson, Handbook for Auto. Comp.,
        /// Vol.ii-Linear Algebra, and the corresponding
        /// Fortran subroutines in EISPACK.</remarks>
        static void NonsymmetricReduceToHessenberg(Matrix <double> eigenVectors, double[,] matrixH, int order)
        {
            var ort = new double[order];

            for (var m = 1; m < order - 1; m++)
            {
                // Scale column.
                var scale = 0.0;
                for (var i = m; i < order; i++)
                {
                    scale = scale + Math.Abs(matrixH[i, m - 1]);
                }

                if (scale != 0.0)
                {
                    // Compute Householder transformation.
                    var h = 0.0;
                    for (var i = order - 1; i >= m; i--)
                    {
                        ort[i] = matrixH[i, m - 1] / scale;
                        h     += ort[i] * ort[i];
                    }

                    var g = Math.Sqrt(h);
                    if (ort[m] > 0)
                    {
                        g = -g;
                    }

                    h      = h - (ort[m] * g);
                    ort[m] = ort[m] - g;

                    // Apply Householder similarity transformation
                    // H = (I-u*u'/h)*H*(I-u*u')/h)
                    for (var j = m; j < order; j++)
                    {
                        var f = 0.0;
                        for (var i = order - 1; i >= m; i--)
                        {
                            f += ort[i] * matrixH[i, j];
                        }

                        f = f / h;
                        for (var i = m; i < order; i++)
                        {
                            matrixH[i, j] -= f * ort[i];
                        }
                    }

                    for (var i = 0; i < order; i++)
                    {
                        var f = 0.0;
                        for (var j = order - 1; j >= m; j--)
                        {
                            f += ort[j] * matrixH[i, j];
                        }

                        f = f / h;
                        for (var j = m; j < order; j++)
                        {
                            matrixH[i, j] -= f * ort[j];
                        }
                    }

                    ort[m]            = scale * ort[m];
                    matrixH[m, m - 1] = scale * g;
                }
            }

            // Accumulate transformations (Algol's ortran).
            for (var i = 0; i < order; i++)
            {
                for (var j = 0; j < order; j++)
                {
                    eigenVectors.At(i, j, i == j ? 1.0 : 0.0);
                }
            }

            for (var m = order - 2; m >= 1; m--)
            {
                if (matrixH[m, m - 1] != 0.0)
                {
                    for (var i = m + 1; i < order; i++)
                    {
                        ort[i] = matrixH[i, m - 1];
                    }

                    for (var j = m; j < order; j++)
                    {
                        var g = 0.0;
                        for (var i = m; i < order; i++)
                        {
                            g += ort[i] * eigenVectors.At(i, j);
                        }

                        // Double division avoids possible underflow
                        g = (g / ort[m]) / matrixH[m, m - 1];
                        for (var i = m; i < order; i++)
                        {
                            eigenVectors.At(i, j, eigenVectors.At(i, j) + g * ort[i]);
                        }
                    }
                }
            }
        }