Esempio n. 1
0
    int Iterate(string input, int iterations)
    {
        var mtx     = Mtx.FromString(".#./..#/###");
        var ruleset = new RuleSet(input);

        for (var i = 0; i < iterations; i++)
        {
            mtx = ruleset.Apply(mtx);
        }
        return(mtx.Count());
    }
Esempio n. 2
0
    public static Mtx FromString(string st)
    {
        st = st.Replace("/", "");
        var size = (int)Math.Sqrt(st.Length);
        var res  = new Mtx(size);

        for (int i = 0; i < st.Length; i++)
        {
            res[i / size, i % size] = st[i] == '#';
        }
        return(res);
    }
Esempio n. 3
0
    IEnumerable <Mtx> Variations(Mtx mtx)
    {
        for (int j = 0; j < 2; j++)
        {
            for (int i = 0; i < 4; i++)
            {
                yield return(mtx);

                mtx = mtx.Rotate();
            }
            mtx = mtx.Flip();
        }
    }
Esempio n. 4
0
    public Mtx Rotate()
    {
        var res = new Mtx(this.Size);

        for (int i = 0; i < Size; i++)
        {
            for (int j = 0; j < Size; j++)
            {
                res[i, j] = this[j, Size - i - 1];
            }
        }
        return(res);
    }
Esempio n. 5
0
    public Mtx Flip()
    {
        var res = new Mtx(this.Size);

        for (int irow = 0; irow < Size; irow++)
        {
            for (int icol = 0; icol < Size; icol++)
            {
                res[irow, Size - icol - 1] = this[irow, icol];
            }
        }
        return(res);
    }
Esempio n. 6
0
        public static Mtx FromMatrix4(Matrix4 m4)
        {
            Mtx ret = new Mtx();

            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    int v = (int)(m4[i, j] * 0x10000);
                    ret.intPart[i, j]  = (short)(v >> 16);
                    ret.fracPart[i, j] = (ushort)(v & 0xFFFF);
                }
            }

            return(ret);
        }
Esempio n. 7
0
        public void SearchAutomorphism()
        {
            SubsCollection.Clear();
            SubsCollection.IterationStats.Clear();

            uint[] t1substitution = new uint[Mtx.SizeMtx];
            for (int i = 0; i < t1substitution.Length; ++i)
            {
                t1substitution[i] = (uint)i;
            }
            TaskScheduler ts = TaskScheduler.FromCurrentSynchronizationContext();
            Task          t  = mtx.SearchAutomorph(1, t1substitution);

            t.ContinueWith((state) =>
            {
                uint count = mtx.GetSubstitutionsCount();
                string s   = "";
                for (uint i = 0; i < count; i++)
                {
                    Substitution sub = new Substitution((int)mtx.SizeMtx);
                    sub.Position     = mtx.GetSubstitutions(i);
                    sub.Partitions   = (int)mtx.GetSubstitutionsParts(i);
                    sub.Sign         = mtx.GetSigns(i);
                    subsCollection.Add(sub);
                }
                uint cnt = 0;
                foreach (var elem in subsCollection)
                {
                    cnt += (uint)elem.Partitions;
                }
                uint[] a = mtx.GetSubstitutions(0);
                for (uint i = 0; i < Mtx.SizeMtx; i++)
                {
                    SubsCollection.IterationStats.Add(Mtx.GetIterationDepthValue(i));
                }
                s += String.Join(",", a) + "\n";
                s  = "AutomorphMatrix Test:"
                     + GetInfo()
                     + "\nВсего найдено: " + count
                     + "\nВсего перебрано: " + cnt;
                // + "\nПервый Вектор: " + s;
                MessageBox.Show(s);
                ResultInfo = s;
            }, ts);
        }
Esempio n. 8
0
    public RuleSet(string input)
    {
        rules2 = new Dictionary <int, Mtx>();
        rules3 = new Dictionary <int, Mtx>();

        foreach (var line in input.Split('\n'))
        {
            var parts = Regex.Split(line, " => ");
            var left  = parts[0];
            var right = parts[1];
            var rules =
                left.Length == 5 ? rules2 :
                left.Length == 11 ? rules3 :
                throw new Exception();
            foreach (var mtx in Variations(Mtx.FromString(left)))
            {
                rules[mtx.CodeNumber] = Mtx.FromString(right);
            }
        }
    }
Esempio n. 9
0
    public static Mtx Join(Mtx[] rgmtx)
    {
        var mtxPerRow = (int)Math.Sqrt(rgmtx.Length);
        var res       = new Mtx(mtxPerRow * rgmtx[0].Size);

        for (int imtx = 0; imtx < rgmtx.Length; imtx++)
        {
            var mtx = rgmtx[imtx];
            for (int irow = 0; irow < mtx.Size; irow++)
            {
                for (int icol = 0; icol < mtx.Size; icol++)
                {
                    var irowRes = (imtx / mtxPerRow) * mtx.Size + irow;
                    var icolRes = (imtx % mtxPerRow) * mtx.Size + icol;
                    res[irowRes, icolRes] = mtx[irow, icol];
                }
            }
        }

        return(res);
    }
Esempio n. 10
0
    public IEnumerable <Mtx> Split()
    {
        var blockSize =
            Size % 2 == 0 ? 2 :
            Size % 3 == 0 ? 3 :
            throw new Exception();

        for (int irow = 0; irow < Size; irow += blockSize)
        {
            for (int icol = 0; icol < Size; icol += blockSize)
            {
                var mtx = new Mtx(blockSize);
                for (int drow = 0; drow < blockSize; drow++)
                {
                    for (int dcol = 0; dcol < blockSize; dcol++)
                    {
                        mtx[drow, dcol] = this[irow + drow, icol + dcol];
                    }
                }
                yield return(mtx);
            }
        }
    }
Esempio n. 11
0
        int UpdateMatrixBuf(BinaryStream bw, int limbIdx, int dlistIdx, Matrix4 src)
        {
            Matrix4 mtx = CalcMatrix(src, limbIdx);

            if (_limbDlists[limbIdx] != null)
            {
                bw.Seek(dlistIdx++ *Mtx.SIZE, SeekOrigin.Begin);
                Mtx.FromMatrix4(mtx).Write(bw);
            }


            if (_limbs[limbIdx].Child != 0xFF)
            {
                dlistIdx = UpdateMatrixBuf(bw, _limbs[limbIdx].Child, dlistIdx, mtx);
            }

            if (_limbs[limbIdx].Sibling != 0xFF)
            {
                dlistIdx = UpdateMatrixBuf(bw, _limbs[limbIdx].Sibling, dlistIdx, src);
            }

            return(dlistIdx);
        }
Esempio n. 12
0
        private static int[] ComputeChangeOfBasisBlock(
            int[] BlockLen,
            MultidimensionalArray In_MassMatrixBlock, MultidimensionalArray In_OperatorMatrixBlock,
            MultidimensionalArray OUT_LeftPC, MultidimensionalArray OUT_rightPC, Mode PCMode, out int Rank,
            MultidimensionalArray work) //
        {
            Rank = In_MassMatrixBlock.NoOfCols;

            int[] IndefRows = null;

            switch (PCMode)
            {
            case Mode.Eye: {
                OUT_LeftPC.AccEye(1.0);
                OUT_rightPC.AccEye(1.0);
                break;
            }

            case Mode.DiagBlockEquilib: {
                double symmErr = In_OperatorMatrixBlock.SymmetryError();
                double infNorm = In_OperatorMatrixBlock.InfNorm();

                if (symmErr / infNorm > 1.0e-8)
                {
                    throw new ArithmeticException(string.Format("LDL_DiagBlock is not supported on unsymmetric matrices (Symm-Err: {0:0.####E-00}, Inf-Norm: {1:0.####E-00}, Quotient {2:0.####E-00}).", symmErr, infNorm, symmErr / infNorm));
                }
                SymmInv(In_OperatorMatrixBlock, OUT_LeftPC, OUT_rightPC);
                //In_OperatorMatrixBlock.SymmetricLDLInversion(OUT_rightPC, null);
                //OUT_rightPC.TransposeTo(OUT_LeftPC);
                break;
            }

            case Mode.SymPart_DiagBlockEquilib: {
                var SymmPart = work;
                In_OperatorMatrixBlock.TransposeTo(SymmPart);
                SymmPart.Acc(1.0, In_OperatorMatrixBlock);
                SymmPart.Scale(0.5);

                SymmInv(SymmPart, OUT_LeftPC, OUT_rightPC);
                break;
            }

            case Mode.IdMass: {
                In_MassMatrixBlock.SymmetricLDLInversion(OUT_rightPC, default(double[]));
                OUT_rightPC.TransposeTo(OUT_LeftPC);
                break;
            }

            case Mode.LeftInverse_DiagBlock: {
                In_OperatorMatrixBlock.InvertTo(OUT_LeftPC);
                OUT_rightPC.AccEye(1.0);
                break;
            }

            case Mode.LeftInverse_Mass: {
                In_MassMatrixBlock.InvertTo(OUT_LeftPC);
                OUT_rightPC.AccEye(1.0);
                break;
            }

            case Mode.IdMass_DropIndefinite: {
                int[] ZerosEntries = ModifiedInverseChol(In_MassMatrixBlock, OUT_rightPC, 1.0e-12, false);
                int   NoOfZeros    = ZerosEntries == null ? 0 : ZerosEntries.Length;
                IndefRows = ZerosEntries;
                Rank      = OUT_LeftPC.NoOfCols - NoOfZeros;
                OUT_rightPC.TransposeTo(OUT_LeftPC);
                break;
            }

            case Mode.SymPart_DiagBlockEquilib_DropIndefinite: {
                (Rank, IndefRows) = SymPart_DiagBlockEquilib_DropIndefinite(In_MassMatrixBlock, In_OperatorMatrixBlock, OUT_LeftPC, OUT_rightPC, work);

                break;
            }

            case Mode.SchurComplement: {
                //throw new NotImplementedException("todo");

                int NoVars = BlockLen.Length;
                if (NoVars <= 1)
                {
                    throw new NotSupportedException("The Schur complement requires at least 2 variables, moron!");
                }
                int N1 = BlockLen.Take(NoVars - 1).Sum();
                int N2 = BlockLen.Last();
                int N  = N1 + N2;

                //string TestPath = @"C:\Users\flori\OneDrive\MATLAB\Schur";
                //In_OperatorMatrixBlock.SaveToTextFile(Path.Combine(TestPath, "Opm.txt"));

                Debug.Assert(N == In_OperatorMatrixBlock.NoOfRows);
                Debug.Assert(N == In_OperatorMatrixBlock.NoOfCols);

                (MultidimensionalArray M11, MultidimensionalArray M12, MultidimensionalArray M21, MultidimensionalArray M22) GetSubblox(MultidimensionalArray Mtx)
                {
                    return(
                        Mtx.ExtractSubArrayShallow(new[] { 0, 0 }, new[] { N1 - 1, N1 - 1 }),
                        Mtx.ExtractSubArrayShallow(new[] { 0, N1 }, new[] { N1 - 1, N - 1 }),
                        Mtx.ExtractSubArrayShallow(new[] { N1, 0 }, new[] { N - 1, N1 - 1 }),
                        Mtx.ExtractSubArrayShallow(new[] { N1, N1 }, new[] { N - 1, N - 1 })
                        );
                }

                var OpMtxSub = GetSubblox(In_OperatorMatrixBlock);
                var MamaSub  = GetSubblox(In_MassMatrixBlock);
                var workSub  = GetSubblox(work);
                var lpcSub   = GetSubblox(OUT_LeftPC);
                var rpcSub   = GetSubblox(OUT_rightPC);

                (int Rank11, int[] IndefRows11) = SymPart_DiagBlockEquilib_DropIndefinite(MamaSub.M11, OpMtxSub.M11, lpcSub.M11, rpcSub.M11, workSub.M11);

                // compute lpcSub.M11*OpMtxSub.M11*rpcSub.M11
                // (without additional mem-alloc, yeah!)
                var Diag11 = workSub.M11;
                Diag11.GEMM(1.0, lpcSub.M11, OpMtxSub.M11, 0.0);
                OpMtxSub.M11.GEMM(1.0, Diag11, rpcSub.M11, 0.0);

                // invert diag
                if (Rank11 == N1)
                {
                    OpMtxSub.M11.InvertTo(workSub.M11);
                }
                else
                {
                    RankDefInvert(OpMtxSub.M11, workSub.M11);
                }

                //
                OpMtxSub.M11.GEMM(1.0, rpcSub.M11, OpMtxSub.M11, 0.0);
                workSub.M11.GEMM(1.0, OpMtxSub.M11, lpcSub.M11, 0.0);
                var Q = workSub.M11;

                //
                workSub.M21.GEMM(-1.0, OpMtxSub.M21, Q, 0.0);
                workSub.M12.GEMM(-1.0, Q, OpMtxSub.M12, 0.0);

                //rpcSub.M12.SetMatrix(workSub.M12); rpcSub.M22.AccEye(1.0);
                //lpcSub.M21.SetMatrix(workSub.M21); lpcSub.M22.AccEye(1.0);
                //OUT_LeftPC.SaveToTextFile(Path.Combine(TestPath, "Lpc.txt"));
                //OUT_rightPC.SaveToTextFile(Path.Combine(TestPath, "Rpc.txt"));


                rpcSub.M12.GEMM(1.0, Q, OpMtxSub.M12, 0.0);
                OpMtxSub.M22.GEMM(-1.0, OpMtxSub.M21, rpcSub.M12, 1.0);


                (int Rank22, int[] IndefRows22) = SymPart_DiagBlockEquilib_DropIndefinite(MamaSub.M22, OpMtxSub.M22, lpcSub.M22, rpcSub.M22, workSub.M22);

                lpcSub.M21.GEMM(1.0, lpcSub.M22, workSub.M21, 0.0);
                rpcSub.M12.GEMM(1.0, workSub.M12, rpcSub.M22, 0.0);

                //OUT_LeftPC.SaveToTextFile(Path.Combine(TestPath, "Lpc.txt"));
                //OUT_rightPC.SaveToTextFile(Path.Combine(TestPath, "Rpc.txt"));

                if (IndefRows11 != null && IndefRows22 != null)
                {
                    IndefRows = ArrayTools.Cat(IndefRows11, IndefRows22);
                }
                else if (IndefRows11 != null)
                {
                    IndefRows = IndefRows11;
                }
                else if (IndefRows22 != null)
                {
                    IndefRows = IndefRows22;
                }
                else
                {
                    IndefRows = null;
                }

                Rank = Rank11 + Rank22;
                break;
            }

            /*
             * case Mode.LDL_DiagBlock_DropIndefinite: {
             *      if(In_OperatorMatrixBlock.SymmetryError() / In_OperatorMatrixBlock.InfNorm() > 1.0e-8)
             *          throw new NotSupportedException("LDL_DiagBlock is not supported on unsymmetric matrices");
             *      int N = OUT_LeftPC.NoOfCols;
             *
             *      MultidimensionalArray PL = MultidimensionalArray.Create(N, N);
             *      MultidimensionalArray PR = MultidimensionalArray.Create(N, N);
             *
             *      int zeros1 = CRM114(In_MassMatrixBlock, PR, 1.0e-12);
             *      Rank = N - zeros1;
             *      PR.TransposeTo(PL);
             *
             *      var OpTr = (PL * In_OperatorMatrixBlock) * PR;
             *
             *      MultidimensionalArray QL = MultidimensionalArray.Create(N, N);
             *      MultidimensionalArray QR =  MultidimensionalArray.Create(N, N);
             *      int zeros2 = CRM114(OpTr, QR, 1.0e-12);
             *      QR.TransposeTo(QL);
             *
             *      if(zeros1 != zeros2)
             *          // I want this to fire also in Release mode, therfore i don't use Debug.Assert(...)
             *          throw new ApplicationException();
             *
             *
             *      OUT_LeftPC.GEMM(1.0, QL, PL, 0.0);
             *      OUT_rightPC.GEMM(1.0, PR, QR, 0.0);
             *
             *      //if (zeros1 > 0 || zeros2 > 0) {
             *      //    Console.WriteLine("zeros introduced: " + zeros1 + ", " + zeros2);
             *      //}
             *
             *      break;
             *  }
             */
            default:
                throw new NotImplementedException("Unknown option: " + PCMode);
            }

            return(IndefRows);
        }
Esempio n. 13
0
 /// <summary>
 /// Создание QR кода
 /// </summary>
 /// <param name="Bytes">Кодируемая последовательность</param>
 /// <param name="Version">Номер версии (определяет размер)</param>
 /// <param name="Level">Уровень коррекции</param>
 /// <param name="MaskCode">Код маски ("-1" - оптимальная)</param>
 /// <param name="Zoom">Размер квадратиков в пикселах</param>
 /// <returns>QR код</returns>
 public static Bitmap CreateQR(byte[] Bytes, int Version, CorrectionLevel Level, int MaskCode, int Zoom)
 {
     #region Проверка параметров
     if (Bytes == null)
     {
         throw new ArgumentNullException(ErrorNullData);
     }
     if ((Version < 1) || (Version > 40))
     {
         throw new Exception(ErrorBadVersion);
     }
     if (((int)Level < 0) || ((int)Level > 3))
     {
         throw new Exception(ErrorBadLevel);
     }
     if ((MaskCode < -1) || (MaskCode > 7))
     {
         throw new Exception(ErrorBadMask);
     }
     if (Zoom < 1)
     {
         throw new Exception(ErrorZoom);
     }
     #endregion
     #region Получение конечного потока данных (byte[] Data)
     byte[]   cBytes = CodingByte(Bytes, Version, Level);
     byte[][] bData  = BlockCreate(cBytes, Version, Level);
     byte[]   Data   = DataStream(bData, Version, Level);
     #endregion
     #region Выбор маски
     bool[,] Mtx;
     if (MaskCode == -1)
     {
         Mtx = CreateMatrix(Data, Version, Level, 0);
         int r = RateMatrix(Mtx);
         for (int i = 1; i < 8; i++)
         {
             bool[,] m = CreateMatrix(Data, Version, Level, i);
             int n = RateMatrix(m);
             if (n < r)
             {
                 Mtx = m;
                 r   = n;
             }
         }
     }
     else
     {
         Mtx = CreateMatrix(Data, Version, Level, MaskCode);
     }
     #endregion
     #region Формирование рисунка
     int      BarSize = Mtx.GetLength(0);
     Bitmap   Result  = new Bitmap((BarSize + 8) * Zoom, (BarSize + 8) * Zoom);
     Graphics g       = Graphics.FromImage(Result);
     g.Clear(Color.White);
     for (int x = 0; x < BarSize; x++)
     {
         for (int y = 0; y < BarSize; y++)
         {
             g.FillRectangle((Mtx[x, y] ? Brushes.Black : Brushes.White), (4 + x) * Zoom, (4 + y) * Zoom, Zoom, Zoom);
         }
     }
     #endregion
     return(Result);
 }