Exemple #1
0
 public static Vector PageRank(MathNet.Numerics.LinearAlgebra.Matrix<double> A, MathNet.Numerics.LinearAlgebra.Vector<double> z)
 {
     Vector pi;
     var inversematrix = (SparseMatrix.CreateIdentity(z.Count) - beta * A).Inverse();
     pi = (Vector)(inversematrix * (1 - beta) * z);
     return pi;
 }
        public static void cudaTranspose(ref MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dm)
        {
            GPGPU gpu = CudafyHost.GetDevice(eGPUType.Cuda);

            GPGPUBLAS blas = GPGPUBLAS.Create(gpu);

            int cols = dm.ColumnCount, rows = dm.RowCount;
            int restRows = rows - cols;
            //double[] a = dm.Storage.ToColumnMajorArray();
            double[] a = dm.SubMatrix(0, cols, 0, cols).Storage.ToColumnMajorArray();
            double[] b = dm.SubMatrix(cols, restRows, 0, cols).Storage.ToColumnMajorArray();
            dm = null;

            double[] a_d = gpu.CopyToDevice<double>(a);
            a = null;
            double[] c_d = gpu.Allocate<double>(cols * cols);
            double[] x_d = gpu.CopyToDevice<double>(new double[] { 1 });
            blas.GEMV(cols, cols, 1, c_d, x_d, 0, x_d, Cudafy.Maths.BLAS.Types.cublasOperation.T);
            a = new double[cols * rows];
            gpu.CopyFromDevice<double>(c_d, 0, a, 0, cols * cols);
            gpu.FreeAll();
            a_d = gpu.CopyToDevice<double>(b);
            b = null;
            c_d = gpu.Allocate<double>(restRows * cols);
            x_d = gpu.CopyToDevice<double>(new double[] { 1 });
            blas.GEMV(restRows, cols, 1, c_d, x_d, 0, x_d, Cudafy.Maths.BLAS.Types.cublasOperation.T);
            gpu.CopyFromDevice<double>(c_d, 0, a, cols * cols, restRows * cols);
            gpu.FreeAll();
            dm = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(cols, rows, a);
        }
 public double Intersect(MathNet.Numerics.LinearAlgebra.Generic.Vector<double> p0,
     MathNet.Numerics.LinearAlgebra.Generic.Vector<double> l0,
     MathNet.Numerics.LinearAlgebra.Generic.Vector<double> n,
     MathNet.Numerics.LinearAlgebra.Generic.Vector<double> l)
 {
     return (p0 - l0).DotProduct(n) / l.DotProduct(n);
 }
 public static string matrixToString(MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dm, ReferenceSystem rs)
 {
     StringBuilder sb = new StringBuilder();
     int index = 0;
     for (int i = 0; i < 21; i++)
     {
         sb.AppendLine();
     }
     for (int i = 2; i <= rs.maxDegree; i++)
     {
         for (int j = 0; j <= i; j++)
         {
             if (j != 0)
             {
                 sb.AppendLine(string.Format("{0}\t{1}\t{2:0.000000000000e+00}\t{3:0.000000000000e+00}", i, j, dm.Values[index], dm.Values[index + 1]));
                 index += 2;
             }
             else {
                 sb.AppendLine(string.Format("{0}\t{1}\t{2:0.000000000000e+00}\t{3:0.000000000000e+00}", i, j, dm.Values[index], 0));
                 index += 1;
             }
         }
     }
     return sb.ToString();
 }
 public float[][] InverseTransform(PointF[] points, MathNet.Numerics.LinearAlgebra.Generic.Matrix<float> irt)
 {
     var undistorted = Intrinsic.Undistort(points, null, null);
     var ids = new int[undistorted.Length];
     for (var i = 0; i < ids.Length; i++) ids[i] = i;
     var threes = ids.Select(i => new MathNet.Numerics.LinearAlgebra.Single.DenseVector(new float[] { undistorted[i].X, undistorted[i].Y, 1, 1 })).ToArray();
     var tt = threes.Select(v => irt.Multiply(v)).ToArray();
     return tt.Select(v => new float[] { (v[0] / v[3]), (v[1] / v[3]), (v[2] / v[3]) }).ToArray();
 }
    /// <summary>
    /// Transforms the given 3D vector point using the given transformation matrix.
    /// </summary>
    /// <param name="TMatrix"> The 4x4 transformation matrix containing rotational and translational matrix. </param>
    /// <param name="w"> Determines the scaling parameter for the translation: 0... neglect translation; 1... include translation. </param>
    /// <param name="PointVector"> The IEnumerable object of type Vector (e.g. List, array,... of 3D point vectors). </param>
    /// <returns> Transformed Points as IEnumerable of type Vector. </returns>
    public static IEnumerable<MathNet.Numerics.LinearAlgebra.Vector> TransformVectorToVector(MathNet.Numerics.LinearAlgebra.Matrix TMatrix, double w,
                                                                                      IEnumerable<MathNet.Numerics.LinearAlgebra.Vector> PointVector)
    {
      foreach(MathNet.Numerics.LinearAlgebra.Vector v in PointVector)
      {
        //convert vector to a column matrix
        MathNet.Numerics.LinearAlgebra.Matrix colMatrix = new MathNet.Numerics.LinearAlgebra.Matrix(4, 1);
        colMatrix[3, 0] = w;
        colMatrix.SetMatrix(0, 2, 0, 0, v.ToColumnMatrix());

        //perform transformation of the point - column vector is extracted after the multiplication
        yield return (TMatrix.Multiply(colMatrix)).GetColumnVector(0).ToNonHomogeneous();
      }
    }
    /// <summary>
    /// Transforms the given 3D vector point using the given transformation matrix.
    /// </summary>
    /// <param name="TMatrix"> The 4x4 transformation matrix containing rotational and translational matrix. </param>
    /// <param name="w"> Determines the scaling parameter for the translation: 0... neglect translation; 1... include translation.</param>
    /// <param name="PointVector"> The IEnumerable object of type Vector (e.g. List, array,... of 3D point vectors). </param>
    /// <returns> Transformed Points as IEnumerable of Emgu type MCvPoint3D32f. </returns>
    public static IEnumerable<Emgu.CV.Structure.MCvPoint3D32f> TransformVectorToEmgu(MathNet.Numerics.LinearAlgebra.Matrix TMatrix, double w,
                                                                                IEnumerable<MathNet.Numerics.LinearAlgebra.Vector> PointVector)
    {
      foreach (MathNet.Numerics.LinearAlgebra.Vector v in PointVector)
      {
        //convert vector to a column matrix
        MathNet.Numerics.LinearAlgebra.Matrix colMatrix = new MathNet.Numerics.LinearAlgebra.Matrix(4, 1);
        colMatrix[3, 0] = w;
        colMatrix.SetMatrix(0, 2, 0, 0, v.ToColumnMatrix());

        //perform transformation of the point - column vector is extracted after the multiplication
        //the resulting vector is converted to the Emgu type MCvPoint3D32f using ToEmguF().
        yield return (TMatrix.Multiply(colMatrix)).GetColumnVector(0).ToNonHomogeneous().ToEmguF();
      }
    }
 public override MathNet.Numerics.Complex32 voltage(Node referenceNode, MathNet.Numerics.Complex32? W = null)
 {
     Complex32 v = InputNodes[0].Voltage;
     if (InputNodes.Count > 1)
     {
         //si no esta una entrada a tierra hay que hacer la diferencia
         v -= InputNodes[1].Voltage;
     }
     v = v * new Complex32((float)gain, 0);
     if (referenceNode == Nodes[0])
         return v;
     else if (referenceNode == Nodes[1])
         return -v;
     else
         return Complex32.NaN;
 }
 public static void cudaTransposeAndMultiply(ref MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dm)
 {
     Cudafy.CudafyModule km = Cudafy.Translator.CudafyTranslator.Cudafy();
     km.Serialize();
     GPGPU gpu = CudafyHost.GetDevice(eGPUType.Cuda);
     int cols = dm.ColumnCount, rows = dm.RowCount;
     dm.Storage.ToColumnMajorArray();
     double[] a = dm.ToColumnWiseArray();
     dm = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(1, 1);
     double[] dev_a = gpu.Allocate<double>(a.Length);
     GPGPUBLAS blas = GPGPUBLAS.Create(gpu);
     double[] a_d = gpu.CopyToDevice<double>(a);
     double[] c_d = gpu.Allocate<double>(cols * cols);
     gpu.StartTimer();
     blas.GEMM(cols, rows, cols, 1, a_d, a_d, 0, c_d, Cudafy.Maths.BLAS.Types.cublasOperation.T);
     a = new double[cols * cols];
     gpu.CopyFromDevice<double>(c_d, a);
     gpu.FreeAll();
     dm = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(cols, cols, a);
 }
 public double DistanceTo(MathNet.Numerics.LinearAlgebra.Vector x) {
   return Math.Abs(_plane.SignedDistanceTo(x));
 }
Exemple #11
0
 public static void writeMatrixToMatLabFile(MathNet.Numerics.LinearAlgebra.Generic.Matrix<double> matrix, string file,string name)
 {
     MathNet.Numerics.LinearAlgebra.IO.MatlabMatrixWriter wr = new MathNet.Numerics.LinearAlgebra.IO.MatlabMatrixWriter(file);
     wr.WriteMatrix(matrix, name);
     wr.Close();
 }
 protected override MathNet.Symbolics.Signal SubtractSignalCore(MathNet.Symbolics.Signal subtrahend)
 {
     return Std.Subtract(this, subtrahend);
 }
        internal void PrintTriangles(Vector<double> x,
            List<int[]> triangles,
            MathNet.Spatial.Euclidean.Point3D oRoot,
            MathNet.Spatial.Euclidean.UnitVector3D vDir1,
            MathNet.Spatial.Euclidean.UnitVector3D vDir2,
            int iTrans,
            MathNet.Spatial.Euclidean.Point3D oTrans,
            bool just2D= false)
        {
            Part oPart = oPartDoc.Part;
            HybridShapeFactory hsf = (HybridShapeFactory)oPart.HybridShapeFactory;
            HybridBody hb1;
            try {
                hb1=(HybridBody)oPart.HybridBodies.GetItem("Blank Calculator Result");
                hb1.get_Name();
                oSel.Clear();
                oSel.Add(hb1);
                oSel.Delete();
            } catch (Exception) {}

            hb1 = (HybridBody)oPart.HybridBodies.Add();
            hb1.set_Name("Blank Calculator Result");

            //CATIA.RefreshDisplay = false;
            //CATIA.Interactive = false;
            List<Reference> RsltPoints = new List<Reference>();
            MathNet.Spatial.Euclidean.CoordinateSystem Axis = new MathNet.Spatial.Euclidean.CoordinateSystem(oRoot, vDir1, vDir2, vDir1.CrossProduct(vDir2));
            if (just2D) {
                for (int i = 0; i < x.Count / 2; i++) {
                    MathNet.Spatial.Euclidean.Point3D  PtMath = new MathNet.Spatial.Euclidean.Point3D(new double[] { x[i * 2], x[i * 2 + 1], 0 });
                    Point PTCat = hsf.AddNewPointCoord(PtMath.X, PtMath.Y, PtMath.Z);
                    PTCat.Compute();
                    RsltPoints.Add(oPart.CreateReferenceFromObject(PTCat));
                }
            } else {
                MathNet.Spatial.Euclidean.Point3D PtMath = new MathNet.Spatial.Euclidean.Point3D(new double[] { x[iTrans * 2], x[iTrans * 2 + 1], 0 });
                PtMath = Axis.TransformToCoordSys(PtMath);
                double[] vecTranslation = new double[] { oTrans.X - PtMath.X, oTrans.Y - PtMath.Y, oTrans.Z - PtMath.Z };
                for (int i = 0; i < x.Count / 2; i++) {
                    PtMath = new MathNet.Spatial.Euclidean.Point3D(new double[] { x[i * 2], x[i * 2 + 1], 0 });
                    PtMath = Axis.TransformToCoordSys(PtMath);
                    Point PTCat = hsf.AddNewPointCoord(PtMath.X + vecTranslation[0], PtMath.Y + vecTranslation[1], PtMath.Z + vecTranslation[2]);
                    PTCat.Compute();
                    RsltPoints.Add(oPart.CreateReferenceFromObject(PTCat));
                }
            }

            foreach (int[] item in triangles) {
                Line lUp = hsf.AddNewLinePtPt(RsltPoints[item[0]], RsltPoints[item[1]]);
                lUp.Compute();
                hb1.AppendHybridShape(lUp);
                Line l0 = hsf.AddNewLinePtPt(RsltPoints[item[1]], RsltPoints[item[2]]);
                l0.Compute();
                hb1.AppendHybridShape(l0);
                Line lDown = hsf.AddNewLinePtPt(RsltPoints[item[2]], RsltPoints[item[0]]);
                lDown.Compute();
                hb1.AppendHybridShape(lDown);
            }

            //CATIA.RefreshDisplay = true;
            //CATIA.Interactive = true;
        }
 void CompoundArchitecture_SignalValueChanged(object sender, MathNet.Symbolics.Backend.Events.SignalEventArgs e)
 {
     int idx = inputSignals.IndexOf(e.Signal);
     system.PushInputValue(idx, inputSignals[idx].Value);
 }
 protected override MathNet.Symbolics.Signal MultiplySignalCore(MathNet.Symbolics.Signal multiplier)
 {
     return Std.Multiply(this, multiplier);
 }
 protected abstract void ReregisterArchitecture(MathNet.Symbolics.Port oldPort, MathNet.Symbolics.Port newPort);
Exemple #17
0
 public static void writeVectorToFile(MathNet.Numerics.LinearAlgebra.Double.DenseVector vector, string file, System.Windows.Forms.RichTextBox tb1, MainForm frm)
 {
     System.IO.Stream fileStream = new System.IO.FileStream(file, System.IO.FileMode.Create);
     System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fileStream, System.Text.Encoding.Default);
     double[] arr = vector.Values;
     System.IO.TextWriter tr = new System.IO.StreamWriter(file + ".metainfo");
     tr.WriteLine("Items count");
     tr.WriteLine(vector.Count);
     tr.Flush();
     tr.Close();
     int len = arr.Length;
     vector = null;
     int index = 0;
     byte[] bytes = new byte[arr.Length * 8];
     foreach (double item in arr)
     {
         BitConverter.GetBytes(item).CopyTo(bytes, index);
         if (index / 8 / 500D == Math.Round(index / 8 / 500D)) { tb1.BeginInvoke(new MainForm.setProgressDel(frm.addVal), new object[] { (int)index / 8, len, "Записано" }); }
         index += 8;
     }
     bw.Write(bytes);
     bw.Flush();
     tb1.BeginInvoke(new MainForm.setProgressDel(frm.addVal), new object[] { (int)0, len, "" });
     bw.Flush();
     bw.Close();
     fileStream.Close();
 }
 /// <summary>
 /// True if the signal depends on a specified port.
 /// </summary>
 public override bool DependsOn(MathNet.Symbolics.Port port)
 {
     return Service<IScanner>.Instance.ExistsPort(this, port.Equals, true);
 }
 protected void SetPort(MathNet.Symbolics.Port port)
 {
     if(port == null) throw new ArgumentNullException("port");
     _isInstance = true;
     _port = port;
 }
 /// <summary>
 /// True if the signal depends on a specified signal, and thus posting a new value to the specified signal may influence this signal's value.
 /// </summary>
 public override bool DependsOn(MathNet.Symbolics.Signal signal)
 {
     return Service<IScanner>.Instance.ExistsSignal(this, signal.Equals, true);
 }
 /// <remarks>needs to be called as soon as soon as it becomes connected through its driven port to an output signal -> run with each output signal as source parameter.</remarks>
 public int AddCycles(MathNet.Symbolics.Signal source, int tag)
 {
     if(this == source)
     {
         _cycleCount++;
         return 1;
     }
     if(IsSourceSignal || !IsDriven)
         return 0;
     else
     {
         int ret = 0;
         if(!((IPort_CycleAnalysis)_drivenByPort).TagWasTagged(tag)) //was not tagged with this tag before.
         {
             foreach(Signal item in _drivenByPort.InputSignals)
                 if(item != null)
                     ret += item.AddCycles(source, tag);
             ((IPort_CycleAnalysis)_drivenByPort).DeTag(tag);
         }
         _cycleCount += ret;
         return ret;
     }
 }
 void system_OutputValueChanged(object sender, MathNet.Symbolics.Backend.Events.IndexedSignalEventArgs e)
 {
     outputSignals[e.Index].PostNewValue(e.Signal.Value);
 }
Exemple #23
0
 public static void writeMatrixToTxtFile(MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dm, string file)
 {
     StringBuilder sb = new StringBuilder();
     for (int i = 0; i < dm.RowCount; i++)
     {
         foreach (var item in dm.SubMatrix(i,1,0,dm.ColumnCount).ToColumnWiseArray())
             {
                 sb.AppendFormat("{0,5:0.0000000000000e+00};",item);
             }
         sb.Append("\r\n");
     }
     System.IO.File.WriteAllText(file, sb.ToString());
 }
 protected override MathNet.Symbolics.Signal AddSignalCore(MathNet.Symbolics.Signal summand)
 {
     return Std.Add(this, summand);
 }
Exemple #25
0
 public static void writeModeVectorlToTxtFile(MathNet.Numerics.LinearAlgebra.Double.DenseVector dm, ReferenceSystem rs, string file)
 {
     System.IO.File.WriteAllText(file, matrixToString((MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)dm.ToColumnMatrix(), rs), System.Text.Encoding.Default);
 }
 protected override MathNet.Symbolics.Signal DivideSignalCore(MathNet.Symbolics.Signal divisor)
 {
     return Std.Divide(this, divisor);
 }
Exemple #27
0
        public static void writeVectorToTxtFile(MathNet.Numerics.LinearAlgebra.Double.DenseVector dm, string file)
        {
            StringBuilder sb = new StringBuilder();

                foreach (var item in dm.Values)
                {
                    sb.AppendFormat("{0,5:0.0000000000000e+00}\r\n", item);
                }
            System.IO.File.WriteAllText(file, sb.ToString());
        }
 public bool RebindToPortIfSupported(MathNet.Symbolics.Port newPort)
 {
     if(newPort == null) throw new ArgumentNullException("newPort");
     if(newPort.Equals(_port))
         return true;
     if(SupportsPort(newPort))
     {
         MathNet.Symbolics.Port oldPort = _port;
         UnregisterArchitecture();
         _port = newPort;
         ReregisterArchitecture(oldPort, newPort);
         return true;
     }
     return false;
 }
        void ISignal_Drive.DriveSignal(MathNet.Symbolics.Port source, int outputIndex)
        {
            if(IsDriven)
                Service<IMediator>.Instance.NotifyPortDrivesSignalNoLonger(this, _drivenByPort, _drivenByPort.OutputSignals.IndexOf(this));

            _drivenByPort = source;
            _isSourceSignal = false;
            _properties.ValidatePropertiesAfterDrive(this);

            Service<IMediator>.Instance.NotifyPortDrivesSignal(this, source, outputIndex);
        }
 /// <remarks>needs to be called as soon as soon as it becomes disconnected through its driven port to an output signal -> run with each output signal as source parameter.</remarks>
 public int RemoveCycles(MathNet.Symbolics.Signal source, int tag)
 {
     if(this == source)
     {
         System.Diagnostics.Debug.Assert(_cycleCount >= 1);
         _cycleCount--;
         return 1;
     }
     if(IsSourceSignal || !IsDriven)
         return 0;
     else
     {
         int ret = 0;
         if(!((IPort_CycleAnalysis)_drivenByPort).TagWasTagged(tag)) //was not tagged with this tag before.
         {
             foreach(Signal item in _drivenByPort.InputSignals)
                 ret += item.RemoveCycles(source, tag);
             ((IPort_CycleAnalysis)_drivenByPort).DeTag(tag);
         }
         System.Diagnostics.Debug.Assert(_cycleCount >= ret);
         _cycleCount -= ret;
         return ret;
     }
 }