コード例 #1
1
        public Matrix compress(int k)
        {
            //Setting up compression matrix
            int rows = matrix.RowCount;
            int cols = matrix.ColumnCount;
            Matrix VK = new Matrix(cols, k);
            Matrix UK = new Matrix(rows, k);
            double SK;
            Matrix Ak = new Matrix(rows, cols);

            //Begin compressing matrix according to algorithm
            Console.WriteLine("Compressing matrix... K = " + k);
            for (int i = 0; i < k; i++)
            {
                //Making V, U, and S for compressed matrix
                VK = v.GetColumnVector(i).ToColumnMatrix();
                UK = u.GetColumnVector(i).ToColumnMatrix();
                SK = d[i, i];

                //Performing operations on V, U, S
                VK.Transpose();
                UK = UK.Multiply(VK);
                UK.Multiply(SK);
                Ak.Add(UK);
            }

            //Returning data
            SV1 = d[0, 0];

            SVK1 = d[k + 1, k + 1];

            Console.WriteLine("SV1: " + d[0, 0] + " SVK1: " + d[k + 1, k + 1]);

            return Ak;
        }
コード例 #2
0
 public Regression(double[] xdata, double[] ydata, int degree)
 {
     int numberOfSamples = xdata.Length;
     //Define the results
     coefficients = new double[degree + 1];
     predicted = new double[numberOfSamples];
     //Set up X and Y Matricies
     Matrix YMatrix = new Matrix(ydata, numberOfSamples);
     Matrix XMatrix = new Matrix(numberOfSamples, degree + 1);
     XMatrix.SetColumnVector(new Vector(numberOfSamples, 1.0), 0);
     for (int i = 0; i < degree; i++)
     {
         XMatrix.SetColumnVector(new Vector(RaisePower(xdata, i + 1)), i + 1);
     }
     //Do the calcs
     Matrix XTranspose = Matrix.Transpose(XMatrix);
     Matrix Temp = (XTranspose * XMatrix).Inverse();
     Matrix hat = XMatrix.Multiply(Temp).Multiply(XTranspose);
     Matrix result = Temp.Multiply(XTranspose * YMatrix);
     //Get the coefficients
     coefficients = result.GetColumnVector(0);
     //Calculate the predicted values
     Matrix Y = new Matrix(ydata, ydata.Count());
     predicted = hat.Multiply(Y).GetColumnVector(0);
 }
コード例 #3
0
ファイル: Vertex.cs プロジェクト: SpectralCoding/3d-cube
        public void calc2DCoords()
        {
            // From http://en.wikipedia.org/wiki/3D_projection#Perspective_projection :
            //
            // Point(X|Y|X)			a{x,y,z}	The point in 3D space that is to be projected.
            // Cube.Camera(X|Y|X)	c{x,y,z}	The location of the camera.
            // Cube.Theta(X|Y|X)	0{x,y,z}	The rotation of the camera. When c{x,y,z}=<0,0,0>, and 0{x,y,z}=<0,0,0>, the 3D vector <1,2,0> is projected to the 2D vector <1,2>.
            // Cube.Viewer(X|Y|X)	e{x,y,z}	The viewer's position relative to the display surface.
            // Bsub(X|Y)			b{x,y}		The 2D projection of a.
            //

            double BsubX, BsubY;
            Matrix convMat1, convMat2, convMat3, convMat4, convMat41, convMat42, DsubXYZ;
            double CosThetaX = Math.Cos(Cube.ThetaX); double SinThetaX = Math.Sin(Cube.ThetaX);
            double CosThetaY = Math.Cos(Cube.ThetaY); double SinThetaY = Math.Sin(Cube.ThetaY);
            double CosThetaZ = Math.Cos(Cube.ThetaZ); double SinThetaZ = Math.Sin(Cube.ThetaZ);

            convMat1 = new Matrix(new double[][] {
                new double[] {	1,	0,			0					},
                new double[] {	0,	CosThetaX,	((-1)*(SinThetaX))	},
                new double[] {	0,	SinThetaX,	CosThetaX			}
            });
            convMat2 = new Matrix(new double[][] {
                new double[] {	CosThetaY,				0,	SinThetaY	},
                new double[] {	0,						1,	0			},
                new double[] {	((-1)*(SinThetaY)),		0,	CosThetaY	}
            });
            convMat3 = new Matrix(new double[][] {
                new double[] {	CosThetaZ,	((-1)*(SinThetaZ)),		0	},
                new double[] {	SinThetaZ,	CosThetaZ,				0	},
                new double[] {	0,			0,						1	}
            });
            convMat41 = new Matrix(new double[][] {
                new double[] {	X3	},
                new double[] {	Y3	},
                new double[] {	Z3	}
            });
            convMat42 = new Matrix(new double[][] {
                new double[] {	Cube.CameraX	},
                new double[] {	Cube.CameraY	},
                new double[] {	Cube.CameraZ	}
            });
            convMat4 = convMat41.Clone();
            convMat4.Subtract(convMat42);
            DsubXYZ = ((convMat1.Multiply(convMat2)).Multiply(convMat3)).Multiply(convMat4);
            BsubX = (DsubXYZ[0, 0] - Cube.ViewerX) / (Cube.ViewerZ / DsubXYZ[2, 0]);
            BsubY = (DsubXYZ[1, 0] - Cube.ViewerY) / (Cube.ViewerZ / DsubXYZ[2, 0]);
            X2 = (int)((BsubX * 50) + 250);
            Y2 = (int)((BsubY * 50) + 250);
            // Can include Math.Sqrt() here if needed. Math.Sqrt() is slow so its omitted. Doesn't change anything.
            distanceFromViewer = Math.Pow((X3 - Cube.ViewerX), 2) + Math.Pow((Y3 - Cube.ViewerY), 2) + Math.Pow((Z3 - Cube.ViewerZ), 2);
        }
コード例 #4
0
ファイル: Camera.cs プロジェクト: SpectralCoding/3d-cube
 public static double[] cameraTransform(double PointX, double PointY, double PointZ)
 {
     // From http://en.wikipedia.org/wiki/3D_projection#Perspective_projection :
     //
     // Point(X|Y|X)			a{x,y,z}	The point in 3D space that is to be projected.
     // Cube.Camera(X|Y|X)	c{x,y,z}	The location of the camera.
     // Cube.Theta(X|Y|X)	θ{x,y,z}	The rotation of the camera. When c{x,y,z}=<0,0,0>, and 0{x,y,z}=<0,0,0>, the 3D vector <1,2,0> is projected to the 2D vector <1,2>.
     // Cube.Viewer(X|Y|X)	e{x,y,z}	The viewer's position relative to the display surface.
     // Bsub(X|Y)			b{x,y}		The 2D projection of a.
     //
     // "First, we define a point DsubXYZ as a translation of point a{x,y,z} into a coordinate system defined by
     // c{x,y,z}. This is achieved by subtracting c{x,y,z} from a{x,y,z} and then applying a vector rotation matrix
     // using -θ{x,y,z} to the result. This transformation is often called a camera transform (note that these
     // calculations assume a left-handed system of axes)."
     MathNet.Numerics.LinearAlgebra.Matrix convMat1, convMat2, convMat3, convMat4, convMat41, convMat42, DsubXYZ;
     double CosThetaX = Math.Cos(Camera.RotationX); double SinThetaX = Math.Sin(Camera.RotationX);
     double CosThetaY = Math.Cos(Camera.RotationY); double SinThetaY = Math.Sin(Camera.RotationY);
     double CosThetaZ = Math.Cos(Camera.RotationZ); double SinThetaZ = Math.Sin(Camera.RotationZ);
     convMat1 = new MathNet.Numerics.LinearAlgebra.Matrix(new double[][] {
         new double[] {	1,	0,			0					},
         new double[] {	0,	CosThetaX,	((-1)*(SinThetaX))	},
         new double[] {	0,	SinThetaX,	CosThetaX			}
     });
     convMat2 = new MathNet.Numerics.LinearAlgebra.Matrix(new double[][] {
         new double[] {	CosThetaY,				0,	SinThetaY	},
         new double[] {	0,						1,	0			},
         new double[] {	((-1)*(SinThetaY)),		0,	CosThetaY	}
     });
     convMat3 = new MathNet.Numerics.LinearAlgebra.Matrix(new double[][] {
         new double[] {	CosThetaZ,	((-1)*(SinThetaZ)),		0	},
         new double[] {	SinThetaZ,	CosThetaZ,				0	},
         new double[] {	0,			0,						1	}
     });
     convMat41 = new MathNet.Numerics.LinearAlgebra.Matrix(new double[][] {
         new double[] {	PointX	},
         new double[] {	PointY	},
         new double[] {	PointZ	}
     });
     convMat42 = new MathNet.Numerics.LinearAlgebra.Matrix(new double[][] {
         new double[] {	Camera.X	},
         new double[] {	Camera.Y	},
         new double[] {	Camera.Z	}
     });
     convMat4 = convMat41.Clone();
     convMat4.Subtract(convMat42);
     DsubXYZ = ((convMat1.Multiply(convMat2)).Multiply(convMat3)).Multiply(convMat4);
     double[] returnVals = new double[3];
     returnVals[0] = DsubXYZ[0, 0]; returnVals[1] = DsubXYZ[1, 0]; returnVals[2] = DsubXYZ[2, 0];
     return returnVals;
 }
コード例 #5
0
ファイル: NeuralNetwork.cs プロジェクト: stprior/fdgvectors
        public void TrainSet(IEnumerable<Example> testData)
        {
            double lambda = 0.0;
            double m = 1.0;
            var a = new Vector<double>[3];
            var d = new Vector<double>[3];
            Delta0.Clear();
            Delta1.Clear();
            foreach (var sample in testData)
            {
                m = (double)sample.X.Count;
                a[0] = sample.X;
                a[1] = Theta0.Multiply(a[0]).Map(SpecialFunctions.Logistic);
                a[2] = Theta1.Multiply(a[1]).Map(SpecialFunctions.Logistic);
                d[2] = a[2] - sample.Y;
                d[1] = BackPropogate(Theta1, a[1], d[2]);
            //                d[0] = BackPropogate(Theta0, a[0], d[1]);
                Delta1 = Delta1 + d[2].ToColumnMatrix().Multiply(a[1].ToColumnMatrix());
                Delta0 = Delta0 + d[1].ToColumnMatrix().Multiply(a[0].ToColumnMatrix());

            }
            var D0 = Delta0.Multiply(1/m);// ignoring regularisation + Theta0.Multiply(lambda);
            var D1 = Delta1.Multiply(1/m);

            var unrolledTheta0 = (Theta0.RowCount*Theta0.ColumnCount);
            var unrolledTheta1 = (Theta1.RowCount + Theta1.ColumnCount);
            var thetaVec = new double[unrolledTheta0 + unrolledTheta1];
            var DVec = new double[unrolledTheta0 + unrolledTheta1];

            Theta0.ToColumnWiseArray().CopyTo(thetaVec,0);
            Theta1.ToColumnWiseArray().CopyTo(thetaVec, unrolledTheta1);

            D0.ToColumnWiseArray().CopyTo(DVec,0);
            D1.ToColumnWiseArray().CopyTo(DVec,unrolledTheta1);

            //lbfgsb.ComputeMin(BananaFunction, BananaFunctionGradient, initialGuess);
        }
コード例 #6
0
        public ILinearRegressionModel BuildModel(Matrix<double> matrixX, Vector<double> vectorY, ILinearRegressionParams regressionParams)
        {
            var weightsVector = Vector<double>.Build.DenseOfArray(
                Enumerable.Range(0, matrixX.ColumnCount)
                .Select(fIdx => randomizer.NextDoubleInRange(weightsMin, weightsMax))
                .ToArray());
            double previousIterError = double.PositiveInfinity;
            for (int iterNo = 0; iterNo < iterations; iterNo++)
            {
                var vectorYHat = matrixX.Multiply(weightsVector);
                var diffVector = vectorYHat.Subtract(vectorY);
                var currentIterError = diffVector.Select(Math.Abs).Sum();
                if ((currentIterError <= stopLerningError) ||
                    currentIterError.AlmostEqual(previousIterError, 5))
                {
                    break;
                }
                for (int weightIdx = 0; weightIdx < weightsVector.Count; weightIdx++)
                {
                    var diffSums = 0.0;
                    for (int rowIdx = 0; rowIdx < matrixX.RowCount; rowIdx++)
                    {
                        diffSums += diffVector[rowIdx] * matrixX.Row(rowIdx)[weightIdx];
                    }
                    var newWeightValue = CalculateWeightUpdate(
                        matrixX,
                        regressionParams,
                        diffSums,
                        weightsVector[weightIdx]);
                    weightsVector[weightIdx] = newWeightValue;
                }
                previousIterError = currentIterError;
            }

            return new LinearRegressionModel(weightsVector);
        }
コード例 #7
0
ファイル: Circles.cs プロジェクト: sivarajankumar/dentalsmile
    /// <summary>
    /// Count the number of black/white transitions for a single ellipse
    /// </summary>
    /// <param name="e">Ellipse</param>
    /// <param name="matrix">Affine ellipse frame that transforms the ellipse to a circle located at origin</param>
    /// <param name="gray">Binary image</param>
    /// <returns>The number of black/white transitions found</returns>
    private int CountBinaryTransitions(DetectedEllipse e, Matrix matrix, Emgu.CV.Image<Gray, byte> gray) {
      // Generate points on circle
      double r = e.Ellipse.MCvBox2D.size.Height * 0.5;
      double t_step = (2 * Math.PI) / _number_circle_points;

      System.Drawing.Rectangle rect = new System.Drawing.Rectangle(System.Drawing.Point.Empty, gray.Size);

      int count_transitions = 0;
      double last_intensity = 0;
      for (double t = 0; t <= 2 * Math.PI; t += t_step) {
        Vector v = new Vector(new double[] { r * Math.Cos(t), r * Math.Sin(t), 1.0 });
        Vector x = matrix.Multiply(v.ToColumnMatrix()).GetColumnVector(0);
        System.Drawing.Point p = new System.Drawing.Point((int)Math.Round(x[0]), (int)Math.Round(x[1]));
        if (rect.Contains(p)) {
          if (t == 0) {
            last_intensity = gray[p].Intensity;
          } else {
            double i = gray[p].Intensity;
            if (i != last_intensity) {
              count_transitions += 1;
              last_intensity = i;
            }
          }
        }
      }
      return count_transitions;
    }
コード例 #8
0
ファイル: RBM.cs プロジェクト: Gnork/StromaFramework
        private Matrix<float> getHidden(Matrix<float> data, Func<float, float> f)
        {
            // calculate hidden probabilities or states
            Matrix<float> hidden = data.Multiply(this.weights).Map(logistic, Zeros.Include).Map(f);
            // reset bias
            hidden.SetColumn(0, Vector<float>.Build.Dense(hidden.RowCount, 1.0f));

            return hidden;
        }
コード例 #9
0
 public Vector3DHomogeneous TransformBy(Matrix<double> m)
 {
     return new Vector3DHomogeneous(m.Multiply(this.ToVector()));
 }
コード例 #10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Matrix PCmatrix = (Matrix)stream.get("PCmatrix");
            String[] features = (String[])stream.get("selectedFeatures");

            System.Data.DataSet ds = (System.Data.DataSet)registry.GetDataset((string)stream.get("dataSetName"));

            //retrieve dataset table (assume one for now)
            System.Data.DataTable dt = ds.Tables[0];

            //raw data
            double[,] rawData = new double[dt.Rows.Count, features.Count()];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < features.Count(); j++)
                    rawData[i, j] = (double)dt.Rows[i].ItemArray.ElementAt(dt.Columns[features[j]].Ordinal);
            }

            //Create matrix to hold data for PCA
            Matrix X = new Matrix(rawData);

            //Remove mean
            Vector columnVector;
            for (int i = 0; i < X.ColumnCount; i++)
            {
                columnVector = X.GetColumnVector(i);
                X.SetColumnVector(columnVector.Subtract(columnVector.Average()), i);
            }

            //get first two PCs
            Matrix xy = new Matrix(PCmatrix.RowCount,2);
            xy.SetColumnVector(PCmatrix.GetColumnVector(0),0);
            xy.SetColumnVector(PCmatrix.GetColumnVector(1),1);

            
            //project
            Matrix projected = X.Multiply(xy);

            DataPoint point;
            Projection.Series.Clear();
            Projection.Legends.Clear();


            //if a label column is selected
            String LabelColumnName = LabelColumn.Text;

            if (!LabelColumnName.Equals(""))
            {

                //get labels
                int labelColumnIndex = dt.Columns[LabelColumnName].Ordinal;
                List<String> labels = new List<String>();
                String item;
                
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    item = (String)dt.Rows[i].ItemArray.ElementAt(labelColumnIndex);
                    if (!labels.Contains(item))
                        labels.Add(item);
                }
                Projection.Legends.Add(LabelColumnName);
                System.Drawing.Font font = Projection.Legends[LabelColumnName].Font = new System.Drawing.Font(Projection.Legends[LabelColumnName].Font.Name, 14);

                //Configure series
                foreach (String label in labels)
                {
                    Projection.Series.Add(label);
                    Projection.Series[label].LegendText = label;
                    Projection.Series[label].IsXValueIndexed = false;
                    Projection.Series[label].ChartType = SeriesChartType.Point;
                    Projection.Series[label].MarkerSize = 8;
                }

                //Add points
                for (int i = 0; i < projected.RowCount; i++)
                {
                    point = new DataPoint(projected[i, 0], projected[i, 1]);
                    String label = dt.Rows[i].ItemArray[labelColumnIndex].ToString();
                    Projection.Series[label].Points.Add(point);
                }

            }
            else
            {
                //Single plot graph
                Projection.Series.Add("series1");
                Projection.Series[0].IsXValueIndexed = false;
                Projection.Series[0].ChartType = SeriesChartType.Point;
                Projection.Series[0].MarkerSize = 8;

                for (int i = 0; i < projected.RowCount; i++)
                {
                    point = new DataPoint(projected[i, 0], projected[i, 1]);
                    Projection.Series[0].Points.Add(point);
                }
            }
        }
コード例 #11
0
ファイル: PCAnalyzer.cs プロジェクト: tjom/MIRPCADB
        /// <summary>
        /// Returns a DataEntry containing the coordinates of the i-th entry
        /// computed with the eigenvectors as basis vectors.
        /// </summary>
        /// <param name="key">
        /// The index of the entry
        /// </param>
        /// <returns>
        /// A <see cref="DataEntry"/> with the coordinates
        /// </returns>
        public DataEntry GetCoordinate(int key)
        {
            Matrix m = new Matrix(2, num_params);
            m.SetRowVector(base1, 0);
            m.SetRowVector(base2, 1);

            Matrix coord = m.Multiply(vector_map[key].ToColumnMatrix());

            Debug.Assert(coord.RowCount == 2 && coord.ColumnCount == 1);

            return new DataEntry (key, coord[0,0], coord[1,0], null);
        }
コード例 #12
0
        // CONTROL ADDITION -------------------------------------------------------------------------------------------------------------

        Control addcontrol(string[, ,] controlarray, HtmlTableCell cell, HtmlTableRow row, int col_traverse, int row_traverse)
        {
            // Generic return object
            Control returncontrol = new Control();

            // Specific object generation methods
            switch(controlarray[col_traverse, row_traverse, 0])
            {
                case "LABEL":   // Label control
                    {
                        // Create new control
                        Label newlabel = new Label();

                        // Set control properties
                        newlabel.Font.Name = "Arial"; newlabel.Font.Size = 11;
                        newlabel.ID = "control_" + col_traverse + "_" + row_traverse;

                        // Add control
                        cell.Controls.Add(newlabel);
                        returncontrol = newlabel;

                        break;
                    }
                case "TEXTBOX":
                    {
                        // Create new control
                        TextBox newtextbox = new TextBox();
                        Label newlabel = new Label();

                        // Set textbox control properties
                        newtextbox.Font.Name = "Arial"; newtextbox.Font.Size = 11;
                        newtextbox.ID = "control_" + col_traverse + "_" + row_traverse;
                        newtextbox.Width = Unit.Pixel(Convert.ToInt16(cell.Width.Substring(0,cell.Width.Length-2))*cell.ColSpan - 2*(layouttable.Border + layouttable.CellPadding));

                        // Set label control properties
                        newlabel.Font.Name = "Arial"; newlabel.Font.Size = 11;

                        // Add control
                        cell.Controls.Add(newlabel);
                        cell.Controls.Add(new LiteralControl("<br><br>"));
                        cell.Controls.Add(newtextbox);
                        
                        // Return label for text fill
                        //returncontrol = newtextbox;
                        returncontrol = newlabel;
                        break;
                    }
                case "MULTISELECT":
                    {
                        // Create new control
                        ListBox newlistbox = new ListBox();
                        Label newlabel = new Label();

                        // Set listbox control properties
                        newlistbox.Font.Name = "Arial"; newlistbox.Font.Size = 11;
                        newlistbox.ID = "control_" + col_traverse + "_" + row_traverse;
                        newlistbox.Width = Unit.Pixel(Convert.ToInt16(cell.Width.Substring(0, cell.Width.Length - 2)) * cell.ColSpan - 2 * (layouttable.Border + layouttable.CellPadding));
                        newlistbox.SelectionMode = ListSelectionMode.Multiple;

                        // Set label control properties
                        newlabel.Font.Name = "Arial"; newlabel.Font.Size = 11;
                        newlabel.ID = "control_" + col_traverse + "_" + row_traverse + "_label";

                        // Add control
                        cell.Controls.Add(newlabel);
                        cell.Controls.Add(new LiteralControl("<br><br>"));
                        cell.Controls.Add(newlistbox);

                        // Return label for text fill
                        //returncontrol = newtextbox;
                        returncontrol = newlistbox;
                        break;
                    }
                case "IMAGE":
                    {
                        // Create new control
                        Image newimage = new Image();

                        // Set control properties
                        newimage.ID = "control_" + col_traverse + "_" + row_traverse;
                        newimage.Width = Unit.Pixel(Convert.ToInt16(cell.Width.Substring(0, cell.Width.Length - 2)) * cell.ColSpan - 2 * (layouttable.Border + layouttable.CellPadding));
                        newimage.Height = Unit.Pixel(Convert.ToInt16(row.Height.Substring(0, row.Height.Length - 2)) * cell.RowSpan - 2 * (layouttable.Border + layouttable.CellPadding));

                        // Add control
                        cell.Controls.Add(newimage);
                        returncontrol = newimage;

                        break;
                    }
                case "TABLE":
                    {
                        // Enclose table in panel
                        Panel tablepanel = new Panel();
                        tablepanel.ScrollBars = ScrollBars.Both;
                        tablepanel.Width = Unit.Pixel(Convert.ToInt16(cell.Width.Substring(0, cell.Width.Length - 2)) * cell.ColSpan - (layouttable.Border + layouttable.CellPadding));
                        tablepanel.Height = Unit.Pixel(Convert.ToInt16(row.Height.Substring(0, row.Height.Length - 2)) * cell.RowSpan - (layouttable.Border + layouttable.CellPadding));
                        
                        // Create new control
                        GridView newtable = new GridView();

                        // Set control properties
                        newtable.ID = "control_" + col_traverse + "_" + row_traverse;
                        newtable.Width = Unit.Pixel((int)(tablepanel.Width.Value - 17));
                        newtable.Height = Unit.Pixel((int)(tablepanel.Height.Value - 17));
                        newtable.Font.Name = "Arial"; newtable.Font.Size = 11;
                        newtable.HeaderStyle.BackColor = System.Drawing.Color.Silver;
                        newtable.RowStyle.BackColor = System.Drawing.Color.White;
                        newtable.RowStyle.HorizontalAlign = HorizontalAlign.Center;

                        // Add control
                        tablepanel.Controls.Add(newtable);
                        cell.Controls.Add(tablepanel);
                        returncontrol = tablepanel;

                        break;
                    }
                case "SCATTERPLOT":
                    {
                        Chart Projection = new Chart();
                        Series newseries = new Series();
                        newseries.ChartType = SeriesChartType.Point;
                        Projection.ChartAreas.Add(new ChartArea());
                        Projection.ChartAreas[0].AxisY.Title = "Second Principal Component";
                        Projection.ChartAreas[0].AxisX.Title = "First Principal Component";

                        Projection.Width = Unit.Pixel(Convert.ToInt16(cell.Width.Substring(0, cell.Width.Length - 2)) * cell.ColSpan - 2 * (layouttable.Border + layouttable.CellPadding));
                        Projection.Height = Unit.Pixel(Convert.ToInt16(row.Height.Substring(0, row.Height.Length - 2)) * cell.RowSpan - 2 * (layouttable.Border + layouttable.CellPadding));

                        DataMiningApp.Analysis.ParameterStream stream;
                        Registry.Registry registry;

                        stream = DataMiningApp.Analysis.ParameterStream.getStream(Session);
                        registry = Registry.Registry.getRegistry(Session);

                        Matrix PCmatrix = (Matrix)stream.get("PCmatrix");
                        String[] features = (String[])stream.get("selectedFeatures");

                        System.Data.DataSet ds = (System.Data.DataSet)registry.GetDataset((string)stream.get("dataSetName"));

                        //retrieve dataset table (assume one for now)
                        System.Data.DataTable dt = ds.Tables[0];

                        //raw data
                        double[,] rawData = new double[dt.Rows.Count, features.Count()];
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            for (int j = 0; j < features.Count(); j++)
                                rawData[i, j] = (double)dt.Rows[i].ItemArray.ElementAt(dt.Columns[features[j]].Ordinal);
                        }

                        //Create matrix to hold data for PCA
                        Matrix X = new Matrix(rawData);

                        //Remove mean
                        Vector columnVector;
                        for (int i = 0; i < X.ColumnCount; i++)
                        {
                            columnVector = X.GetColumnVector(i);
                            X.SetColumnVector(columnVector.Subtract(columnVector.Average()), i);
                        }

                        //get first two PCs
                        Matrix xy = new Matrix(PCmatrix.RowCount, 2);
                        xy.SetColumnVector(PCmatrix.GetColumnVector(0), 0);
                        xy.SetColumnVector(PCmatrix.GetColumnVector(1), 1);

                        //project
                        Matrix projected = X.Multiply(xy);

                        DataPoint point;
                        Projection.Series.Clear();
                        Projection.Legends.Clear();


                        //if a label column is selected
                        String LabelColumnName = "Species";

                        if (!LabelColumnName.Equals(""))
                        {

                            //get labels
                            int labelColumnIndex = dt.Columns[LabelColumnName].Ordinal;
                            List<String> labels = new List<String>();
                            String item;

                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                item = (String)dt.Rows[i].ItemArray.ElementAt(labelColumnIndex);
                                if (!labels.Contains(item))
                                    labels.Add(item);
                            }
                            Legend mylegend = Projection.Legends.Add(LabelColumnName);
                            mylegend.TableStyle = LegendTableStyle.Wide;

                            Projection.Legends[0].Docking = Docking.Bottom;
                            System.Drawing.Font font = Projection.Legends[LabelColumnName].Font = new System.Drawing.Font(Projection.Legends[LabelColumnName].Font.Name, 14);

                            //Configure series
                            foreach (String label in labels)
                            {
                                Projection.Series.Add(label);
                                Projection.Series[label].LegendText = label;
                                Projection.Series[label].IsXValueIndexed = false;
                                Projection.Series[label].ChartType = SeriesChartType.Point;
                                Projection.Series[label].MarkerSize = 8;
                            }

                            //Add points
                            for (int i = 0; i < projected.RowCount; i++)
                            {
                                point = new DataPoint(projected[i, 0], projected[i, 1]);
                                String label = dt.Rows[i].ItemArray[labelColumnIndex].ToString();
                                Projection.Series[label].Points.Add(point);
                            }

                        }
                        else
                        {
                            //Single plot graph
                            Projection.Series.Add("series1");
                            Projection.Series[0].IsXValueIndexed = false;
                            Projection.Series[0].ChartType = SeriesChartType.Point;
                            Projection.Series[0].MarkerSize = 8;

                            for (int i = 0; i < projected.RowCount; i++)
                            {
                                point = new DataPoint(projected[i, 0], projected[i, 1]);
                                Projection.Series[0].Points.Add(point);
                            }
                        }
                        cell.Controls.Add(Projection);
                        returncontrol = Projection;

                        /*
                        // Create new control
                        Chart chartcontrol = new Chart();

                        // Set chart width and height
                        chartcontrol.Width = Unit.Pixel(Convert.ToInt16(cell.Width.Substring(0, cell.Width.Length - 2)) * cell.ColSpan - 2 * (layouttable.Border + layouttable.CellPadding));
                        chartcontrol.Height = Unit.Pixel(Convert.ToInt16(row.Height.Substring(0, row.Height.Length - 2)) * cell.RowSpan - 2 * (layouttable.Border + layouttable.CellPadding));

                        // Needed so server knows where to store temporary image
                        chartcontrol.ImageStorageMode = ImageStorageMode.UseImageLocation;

                        ChartArea mychartarea = new ChartArea();
                        chartcontrol.ChartAreas.Add(mychartarea);

                        Series myseries = new Series();
                        myseries.Name = "Series";
                        chartcontrol.Series.Add(myseries);

                        chartcontrol.Series["Series"].ChartType = SeriesChartType.Point;

                        // Add control
                        cell.Controls.Add(chartcontrol);
                        returncontrol = chartcontrol;
                        */
                        break;
                    }
                case "LINEPLOT":
                    {                           
                        DataMiningApp.Analysis.ParameterStream stream = DataMiningApp.Analysis.ParameterStream.getStream(Session);
                        Vector Weights = (Vector)stream.get("Weights");

                        Chart VariancePlot = new Chart();

                        VariancePlot.Width = Unit.Pixel(Convert.ToInt16(cell.Width.Substring(0, cell.Width.Length - 2)) * cell.ColSpan - 2 * (layouttable.Border + layouttable.CellPadding));
                        VariancePlot.Height = Unit.Pixel(Convert.ToInt16(row.Height.Substring(0, row.Height.Length - 2)) * cell.RowSpan - 2 * (layouttable.Border + layouttable.CellPadding));
                        
                        VariancePlot.Palette = ChartColorPalette.EarthTones;
                        Series dataseries = new Series();
                        dataseries.ChartType = SeriesChartType.Line;
                        dataseries.MarkerColor = System.Drawing.Color.Black;
                        dataseries.MarkerBorderWidth = 3;
                        dataseries.MarkerBorderColor = System.Drawing.Color.Black;
                        VariancePlot.Series.Add(dataseries);
                        VariancePlot.ChartAreas.Add(new ChartArea());
                        VariancePlot.ChartAreas[0].AxisY.Title = "Variance Explained";
                        VariancePlot.ChartAreas[0].AxisX.Title = "Principal Component";

                        for (int i = 0; i < Weights.Length; i++)
                            VariancePlot.Series[0].Points.InsertY(i, Weights[i]);

                        cell.Controls.Add(VariancePlot);
                        returncontrol = VariancePlot;

                        break;
                    }
                case "UPLOAD":
                    {
                        // Create new controls
                        Label uploadlabel = new Label();
                        FileUpload uploadcontrol = new FileUpload();
                        HiddenField savedfile = new HiddenField(); HiddenField savedpath = new HiddenField();
                        Button uploadbutton = new Button();
                        GridView uploadtable = new GridView();

                        // Create panel to enclose table to it can scroll without having to scroll entire window
                        Panel tablepanel = new Panel();
                        tablepanel.ScrollBars = ScrollBars.Both;
                        tablepanel.Width = Unit.Pixel(Convert.ToInt16(cell.Width.Substring(0, cell.Width.Length - 2)) * cell.ColSpan - (layouttable.Border + layouttable.CellPadding));
                        tablepanel.Height = Unit.Pixel(Convert.ToInt16(row.Height.Substring(0, row.Height.Length - 2)) * cell.RowSpan - (layouttable.Border + layouttable.CellPadding));

                        // Set IDs for all controls (necessary to get information after postback on upload)
                        uploadlabel.ID = "control_" + col_traverse + "_" + row_traverse + "_label";
                        savedfile.ID = "control_" + col_traverse + "_" + row_traverse + "_savedfile";
                        savedpath.ID = "control_" + col_traverse + "_" + row_traverse + "_savedpath";
                        uploadcontrol.ID = "control_" + col_traverse + "_" + row_traverse;
                        uploadtable.ID = "control_" + col_traverse + "_" + row_traverse + "_table";
                        uploadbutton.ID = "control_" + col_traverse + "_" + row_traverse + "_button";

                        // Set control properties
                        uploadbutton.Text = "Load File";
                        uploadbutton.Font.Name = "Arial"; uploadbutton.Font.Size = 10;
                        uploadbutton.Width = 100;
                        uploadbutton.Click += new System.EventHandler(uploadbutton_Click);
                        uploadlabel.Font.Name = "Arial"; uploadlabel.Font.Size = 11;
                        uploadlabel.ForeColor = System.Drawing.Color.Black;
                        uploadcontrol.Width = Unit.Pixel((int)(tablepanel.Width.Value - 17) - (int)uploadbutton.Width.Value);
                        uploadtable.Width = Unit.Pixel((int)(tablepanel.Width.Value - 17));
                        uploadtable.Height = Unit.Pixel((int)(tablepanel.Height.Value - 17));
                        uploadtable.Font.Name = "Arial"; uploadtable.Font.Size = 11;
                        uploadtable.HeaderStyle.BackColor = System.Drawing.Color.Silver;
                        uploadtable.RowStyle.BackColor = System.Drawing.Color.White;
                        uploadtable.RowStyle.HorizontalAlign = HorizontalAlign.Center;

                        // Add controls to form and format
                        tablepanel.Controls.Add(uploadlabel);
                        tablepanel.Controls.Add(new LiteralControl("<br><br>"));
                        tablepanel.Controls.Add(uploadcontrol);
                        tablepanel.Controls.Add(uploadbutton);
                        tablepanel.Controls.Add(new LiteralControl("<br><br>"));
                        tablepanel.Controls.Add(uploadtable);

                        // Add controls to scrollable panel
                        cell.Controls.Add(tablepanel);
                        
                        // Return uploadcontrol, even though this control itself does not need to be filled (need control type)
                        returncontrol = uploadcontrol;

                        break;
                    }

            }
            return returncontrol;

        }
コード例 #13
0
ファイル: Core_Prohl.cs プロジェクト: byzod/C-Sharp
        /// <summary>
        /// Impeller vibration frequency calculater with Prohl method
        /// </summary>
        /// <param name="impeller">Input impeller</param>
        /// <param name="state">State object</param>
        private void ProhlCalculator(Impeller impeller, ProhlState state)
        {
            #if TRACER
            watch.Start();
            #endif
            // the non-zero numbers of root state vector
            const int ROOT_STATE_VECTOR_SIZE = 2;
            var transferMatrix = new Matrix(4, 4);
            var residualMatrix = new Matrix(2, 2);
            //vibration frequency order
            var rootStateVector = new Matrix[2]{
                new Matrix(
                    new double[][]{
                        new double[] {0},
                        new double[] {0},
                        new double[] {1},
                        new double[] {0}
                    }
                ),
                new Matrix(
                    new double[][]{
                        new double[] {0},
                        new double[] {0},
                        new double[] {0},
                        new double[] {1}
                    }
                )
            };
            //section transfer matrix and hole transfer matrix(from root to end)
            var sectionTransferMatrix = new Matrix(
                new double[][]{
                    new double[] {1,1,1,1},
                    new double[] {0,1,1,1},
                    new double[] {0,0,1,1},
                    new double[] {1,1,1,1}
                }
            );

            #if TRACER
            long step1 = watch.ElapsedTicks;
            #endif
            double freq2 = state.Omega * state.Omega;
            for (var j = 0; j < ROOT_STATE_VECTOR_SIZE; j++)
            {
                for (var i = 0; i < impeller.MSections.Count; i++)
                {
                    double L = (i == 0 ? impeller.MSections[0].Position
                        : impeller.MSections[i].Position - impeller.MSections[i - 1].Position);
                    //L_EJ = L / EJ
                    double L_EJ = L / (impeller.E * impeller.MSections[i].InertiaMoment);
                    double m = impeller.MSections[i].Mass;
                    //freq2xm = freq2
                    double freq2xm = freq2 * m;

                    sectionTransferMatrix[3, 0] = freq2xm;

                    sectionTransferMatrix[0, 1] = L;
                    sectionTransferMatrix[3, 1] = freq2xm * L;

                    sectionTransferMatrix[0, 2] = L * L_EJ / 2;
                    sectionTransferMatrix[1, 2] = L_EJ;
                    sectionTransferMatrix[3, 2] = freq2xm * L * L_EJ / 2;

                    sectionTransferMatrix[0, 3] = L * L * L_EJ / 6;
                    sectionTransferMatrix[1, 3] = L * L_EJ / 2;
                    sectionTransferMatrix[2, 3] = L;
                    sectionTransferMatrix[3, 3] = 1 + freq2xm * L * L * L_EJ / 6;

                    transferMatrix = (i == 0 ? sectionTransferMatrix.Clone()
                        : sectionTransferMatrix.Multiply(transferMatrix));
                }

                state.TransferMatrix = transferMatrix;
                state.StateVector = transferMatrix.Multiply(rootStateVector[j]);

                for (var i = 0; i < state.EndStateVector.RowCount; i++)
                {
                    if (state.EndStateVector[i, 0] == 0 )
                    {
                        if (residualMatrix[0, j] == 0)
                        {
                            residualMatrix[0, j] = state.StateVector[i, 0];
                            continue;
                        }
                        residualMatrix[1, j] = state.StateVector[i, 0];
                        break;
                    }
                }
            }
            #if TRACER
            long step2 = watch.ElapsedTicks;
            watch.Reset();
            System.Windows.MessageBox.Show(
                "Run time" +
                "\nstep1: " + step1 +
                "\nstep2: " + (step2 - step1)
            );
            #endif
            state.residualMoment = residualMatrix.Determinant();
        }