Esempio n. 1
0
        public static void DeleteAll <TLink>(this ILinks <TLink> links)
        {
            var equalityComparer = EqualityComparer <TLink> .Default;
            var comparer         = Comparer <TLink> .Default;

            for (var i = links.Count(); comparer.Compare(i, default) > 0; i = Arithmetic.Decrement(i))
            {
                links.Delete(i);
                if (!equalityComparer.Equals(links.Count(), Arithmetic.Decrement(i)))
                {
                    i = links.Count();
                }
            }
        }
 public static void TestMultipleRandomCreationsAndDeletions<TLink>(this ILinks<TLink> links, int maximumOperationsPerCycle)
 {
     var comparer = Comparer<TLink>.Default;
     var addressToUInt64Converter = CheckedConverter<TLink, ulong>.Default;
     var uInt64ToAddressConverter = CheckedConverter<ulong, TLink>.Default;
     for (var N = 1; N < maximumOperationsPerCycle; N++)
     {
         var random = new System.Random(N);
         var created = 0UL;
         var deleted = 0UL;
         for (var i = 0; i < N; i++)
         {
             var linksCount = addressToUInt64Converter.Convert(links.Count());
             var createPoint = random.NextBoolean();
             if (linksCount >= 2 && createPoint)
             {
                 var linksAddressRange = new Range<ulong>(1, linksCount);
                 TLink source = uInt64ToAddressConverter.Convert(random.NextUInt64(linksAddressRange));
                 TLink target = uInt64ToAddressConverter.Convert(random.NextUInt64(linksAddressRange)); //-V3086
                 var resultLink = links.GetOrCreate(source, target);
                 if (comparer.Compare(resultLink, uInt64ToAddressConverter.Convert(linksCount)) > 0)
                 {
                     created++;
                 }
             }
             else
             {
                 links.Create();
                 created++;
             }
         }
         Assert.True(created == addressToUInt64Converter.Convert(links.Count()));
         for (var i = 0; i < N; i++)
         {
             TLink link = uInt64ToAddressConverter.Convert((ulong)i + 1UL);
             if (links.Exists(link))
             {
                 links.Delete(link);
                 deleted++;
             }
         }
         Assert.True(addressToUInt64Converter.Convert(links.Count()) == 0L);
     }
 }
Esempio n. 3
0
        public static TLink CountUsages <TLink>(this ILinks <TLink> links, TLink link)
        {
            var   constants        = links.Constants;
            var   values           = links.GetLink(link);
            TLink usagesAsSource   = links.Count(new Link <TLink>(constants.Any, link, constants.Any));
            var   equalityComparer = EqualityComparer <TLink> .Default;

            if (equalityComparer.Equals(values[constants.SourcePart], link))
            {
                usagesAsSource = Arithmetic <TLink> .Decrement(usagesAsSource);
            }
            TLink usagesAsTarget = links.Count(new Link <TLink>(constants.Any, constants.Any, link));

            if (equalityComparer.Equals(values[constants.TargetPart], link))
            {
                usagesAsTarget = Arithmetic <TLink> .Decrement(usagesAsTarget);
            }
            return(Arithmetic <TLink> .Add(usagesAsSource, usagesAsTarget));
        }
Esempio n. 4
0
        public static void RunRandomDeletions <TLink>(this ILinks <TLink> links, ulong amountOfDeletions)
        {
            var random = RandomHelpers.Default;
            var addressToUInt64Converter = UncheckedConverter <TLink, ulong> .Default;
            var uInt64ToAddressConverter = UncheckedConverter <ulong, TLink> .Default;
            var linksCount = addressToUInt64Converter.Convert(links.Count());
            var min        = amountOfDeletions > linksCount ? 0UL : linksCount - amountOfDeletions;

            for (var i = 0UL; i < amountOfDeletions; i++)
            {
                linksCount = addressToUInt64Converter.Convert(links.Count());
                if (linksCount <= min)
                {
                    break;
                }
                var linksAddressRange = new Range <ulong>(min, linksCount);
                var link = uInt64ToAddressConverter.Convert(random.NextUInt64(linksAddressRange));
                links.Delete(link);
            }
        }
Esempio n. 5
0
        private void CountCore(TLink link)
        {
            var any = _links.Constants.Any;

            if (_equalityComparer.Equals(_links.Count(any, link), default))
            {
                CountSequenceSymbolFrequency(link);
            }
            else
            {
                _links.Each(EachElementHandler, any, link);
            }
        }
Esempio n. 6
0
        public static IList <TLink> AllIndices <TLink>(this ILinks <TLink> links, params TLink[] restrictions)
        {
            var arraySize = CheckedConverter <TLink, ulong> .Default.Convert(links.Count(restrictions));

            if (arraySize > 0)
            {
                var array  = new TLink[arraySize];
                var filler = new ArrayFiller <TLink, TLink>(array, links.Constants.Continue);
                links.Each(filler.AddFirstAndReturnConstant, restrictions);
                return(array);
            }
            else
            {
                return(Array.Empty <TLink>());
            }
        }
        private static void TestNonexistentReferences(this ILinks <ulong> memoryAdapter)
        {
            var link = memoryAdapter.Create();

            memoryAdapter.Update(link, ulong.MaxValue, ulong.MaxValue);
            var resultLink = _constants.Null;

            memoryAdapter.Each(foundLink =>
            {
                resultLink = foundLink[_constants.IndexPart];
                return(_constants.Break);
            }, _constants.Any, ulong.MaxValue, ulong.MaxValue);
            Assert.True(resultLink == link);
            Assert.True(memoryAdapter.Count(ulong.MaxValue) == 0);
            memoryAdapter.Delete(link);
        }
        public void GenerateData(long maximumObjects, long maximumTags, long maximumTagsPerObject)
        {
            // Objects
            //  (object1: object1 object)
            // Tags
            //  (tag1: tag1 tag)
            // Objects to Tags
            //  (object1 tag1)
            //  (object1 tag2)
            //  (object2 tag1)
            //  (object2 tag2)

            var any = _links.Constants.Any;

            if (_links.Count(any, any, _object) == 0 && _links.Count(any, any, _tag) == 0)
            {
                // No data yet
                var itself = _links.Constants.Itself;
                // Generating Objects
                var objectsRangeStart = _links.Count() + 1;
                for (var i = 0L; i < maximumObjects; i++)
                {
                    _links.CreateAndUpdate(itself, _object);
                }
                var objectsRangeEnd = _links.Count() + 1;
                _objectsRange = new Range <uint>(objectsRangeStart, objectsRangeEnd);
                // Generating Tags
                var tagsRangeStart = _links.Count() + 1;
                for (var i = 0L; i < maximumTags; i++)
                {
                    _links.CreateAndUpdate(itself, _tag);
                }
                var tagsRangeEnd = _links.Count() + 1;
                _tagsRange = new Range <uint>(tagsRangeStart, tagsRangeEnd);
                // Generation Objects to Tags relationships
                var random = new Random();
                for (var i = 0L; i < maximumObjects; i++)
                {
                    var @object = (uint)(objectsRangeStart + i);
                    for (var j = 0L; j < maximumTagsPerObject; j++)
                    {
                        var tag = (uint)random.Next((int)tagsRangeStart, (int)tagsRangeEnd);
                        _links.GetOrCreate(@object, tag);
                    }
                }
            }
            else
            {
                var cursor = 4U;
                _objectsRange = new Range <uint>(cursor, cursor += (uint)maximumObjects);
                _tagsRange    = new Range <uint>(cursor, cursor += (uint)maximumTags);
            }
        }
Esempio n. 9
0
        public static TLink First <TLink>(this ILinks <TLink> links)
        {
            TLink firstLink        = default;
            var   equalityComparer = EqualityComparer <TLink> .Default;

            if (equalityComparer.Equals(links.Count(), default))
            {
                throw new InvalidOperationException("В хранилище нет связей.");
            }
            links.Each(links.Constants.Any, links.Constants.Any, link =>
            {
                firstLink = link[links.Constants.IndexPart];
                return(links.Constants.Break);
            });
            if (equalityComparer.Equals(firstLink, default))
            {
                throw new InvalidOperationException("В процессе поиска по хранилищу не было найдено связей.");
            }
            return(firstLink);
        }
Esempio n. 10
0
        public static void RunRandomSearches <TLink>(this ILinks <TLink> links, ulong amountOfSearches)
        {
            var random = RandomHelpers.Default;
            var addressToUInt64Converter = UncheckedConverter <TLink, ulong> .Default;
            var uInt64ToAddressConverter = UncheckedConverter <ulong, TLink> .Default;

            for (var i = 0UL; i < amountOfSearches; i++)
            {
                var linksAddressRange = new Range <ulong>(0, addressToUInt64Converter.Convert(links.Count()));
                var source            = uInt64ToAddressConverter.Convert(random.NextUInt64(linksAddressRange));
                var target            = uInt64ToAddressConverter.Convert(random.NextUInt64(linksAddressRange));
                links.SearchOrDefault(source, target);
            }
        }
Esempio n. 11
0
 public static bool Exists <TLink>(this ILinks <TLink> links, TLink source, TLink target) => Comparer <TLink> .Default.Compare(links.Count(links.Constants.Any, source, target), default) > 0;
        public static void TestCRUDOperations<T>(this ILinks<T> links)
        {
            var constants = links.Constants;

            var equalityComparer = EqualityComparer<T>.Default;

            var zero = default(T);
            var one = Arithmetic.Increment(zero);

            // Create Link
            Assert.True(equalityComparer.Equals(links.Count(), zero));

            var setter = new Setter<T>(constants.Null);
            links.Each(constants.Any, constants.Any, setter.SetAndReturnTrue);

            Assert.True(equalityComparer.Equals(setter.Result, constants.Null));

            var linkAddress = links.Create();

            var link = new Link<T>(links.GetLink(linkAddress));

            Assert.True(link.Count == 3);
            Assert.True(equalityComparer.Equals(link.Index, linkAddress));
            Assert.True(equalityComparer.Equals(link.Source, constants.Null));
            Assert.True(equalityComparer.Equals(link.Target, constants.Null));

            Assert.True(equalityComparer.Equals(links.Count(), one));

            // Get first link
            setter = new Setter<T>(constants.Null);
            links.Each(constants.Any, constants.Any, setter.SetAndReturnFalse);

            Assert.True(equalityComparer.Equals(setter.Result, linkAddress));

            // Update link to reference itself
            links.Update(linkAddress, linkAddress, linkAddress);

            link = new Link<T>(links.GetLink(linkAddress));

            Assert.True(equalityComparer.Equals(link.Source, linkAddress));
            Assert.True(equalityComparer.Equals(link.Target, linkAddress));

            // Update link to reference null (prepare for delete)
            var updated = links.Update(linkAddress, constants.Null, constants.Null);

            Assert.True(equalityComparer.Equals(updated, linkAddress));

            link = new Link<T>(links.GetLink(linkAddress));

            Assert.True(equalityComparer.Equals(link.Source, constants.Null));
            Assert.True(equalityComparer.Equals(link.Target, constants.Null));

            // Delete link
            links.Delete(linkAddress);

            Assert.True(equalityComparer.Equals(links.Count(), zero));

            setter = new Setter<T>(constants.Null);
            links.Each(constants.Any, constants.Any, setter.SetAndReturnTrue);

            Assert.True(equalityComparer.Equals(setter.Result, constants.Null));
        }
        public static void TestRawNumbersCRUDOperations<T>(this ILinks<T> links)
        {
            // Constants
            var constants = links.Constants;
            var equalityComparer = EqualityComparer<T>.Default;

            var zero = default(T);
            var one = Arithmetic.Increment(zero);
            var two = Arithmetic.Increment(one);

            var h106E = new Hybrid<T>(106L, isExternal: true);
            var h107E = new Hybrid<T>(-char.ConvertFromUtf32(107)[0]);
            var h108E = new Hybrid<T>(-108L);

            Assert.Equal(106L, h106E.AbsoluteValue);
            Assert.Equal(107L, h107E.AbsoluteValue);
            Assert.Equal(108L, h108E.AbsoluteValue);

            // Create Link (External -> External)
            var linkAddress1 = links.Create();

            links.Update(linkAddress1, h106E, h108E);

            var link1 = new Link<T>(links.GetLink(linkAddress1));

            Assert.True(equalityComparer.Equals(link1.Source, h106E));
            Assert.True(equalityComparer.Equals(link1.Target, h108E));

            // Create Link (Internal -> External)
            var linkAddress2 = links.Create();

            links.Update(linkAddress2, linkAddress1, h108E);

            var link2 = new Link<T>(links.GetLink(linkAddress2));

            Assert.True(equalityComparer.Equals(link2.Source, linkAddress1));
            Assert.True(equalityComparer.Equals(link2.Target, h108E));

            // Create Link (Internal -> Internal)
            var linkAddress3 = links.Create();

            links.Update(linkAddress3, linkAddress1, linkAddress2);

            var link3 = new Link<T>(links.GetLink(linkAddress3));

            Assert.True(equalityComparer.Equals(link3.Source, linkAddress1));
            Assert.True(equalityComparer.Equals(link3.Target, linkAddress2));

            // Search for created link
            var setter1 = new Setter<T>(constants.Null);
            links.Each(h106E, h108E, setter1.SetAndReturnFalse);

            Assert.True(equalityComparer.Equals(setter1.Result, linkAddress1));

            // Search for nonexistent link
            var setter2 = new Setter<T>(constants.Null);
            links.Each(h106E, h107E, setter2.SetAndReturnFalse);

            Assert.True(equalityComparer.Equals(setter2.Result, constants.Null));

            // Update link to reference null (prepare for delete)
            var updated = links.Update(linkAddress3, constants.Null, constants.Null);

            Assert.True(equalityComparer.Equals(updated, linkAddress3));

            link3 = new Link<T>(links.GetLink(linkAddress3));

            Assert.True(equalityComparer.Equals(link3.Source, constants.Null));
            Assert.True(equalityComparer.Equals(link3.Target, constants.Null));

            // Delete link
            links.Delete(linkAddress3);

            Assert.True(equalityComparer.Equals(links.Count(), two));

            var setter3 = new Setter<T>(constants.Null);
            links.Each(constants.Any, constants.Any, setter3.SetAndReturnTrue);

            Assert.True(equalityComparer.Equals(setter3.Result, linkAddress2));
        }
Esempio n. 14
0
        public void Recognize()
        {
            var width  = _image.Width;
            var height = _image.Height;

            KeyValuePair <ulong[], ulong[]>[,] matrix = new KeyValuePair <ulong[], ulong[]> [width, height];

            for (var y = 0; y < height; y++)
            {
                IndexRow(y, width);
            }
            for (int x = 0; x < width; x++)
            {
                IndexColumn(x, height);
            }
            for (var y = 0; y < height; y++)
            {
                if (y == 574)
                {
                    var roww    = GetRow(y, width);
                    var levelss = _sequenceToItsLocalElementLevelsConverter.Convert(roww);
                    var l276    = levelss[276];
                    var l277    = levelss[277];
                    var l278    = levelss[278];
                }

                var row = SaveRow(y, width);

                var x     = 0;
                var stack = new Stack <ulong>();
                StopableSequenceWalker.WalkRight(row, _links.GetSource, _links.GetTarget, _links.IsPartialPoint,
                                                 enteredElement =>
                {
                    stack.Push(enteredElement);
                },
                                                 exitedElement =>
                {
                    stack.Pop();
                },
                                                 checkedElement => true,
                                                 element =>
                {
                    stack.Push(element);
                    var pair = new KeyValuePair <ulong[], ulong[]>(stack.ToArray(), default);
                    stack.Pop();
                    matrix[x++, y] = pair;
                    return(true);
                });
            }
            for (int x = 0; x < width; x++)
            {
                var column = SaveColumn(x, height);

                var y     = 0;
                var stack = new Stack <ulong>();
                StopableSequenceWalker.WalkRight(column, _links.GetSource, _links.GetTarget, _links.IsPartialPoint,
                                                 enteredElement =>
                {
                    stack.Push(enteredElement);
                },
                                                 exitedElement =>
                {
                    stack.Pop();
                },
                                                 checkedElement => true,
                                                 element =>
                {
                    var pair = matrix[x, y];
                    stack.Push(element);
                    pair = new KeyValuePair <ulong[], ulong[]>(pair.Key, stack.ToArray());
                    stack.Pop();
                    matrix[x, y++] = pair;
                    return(true);
                });
            }

            // Sort sequences by usages and frequency

            var linksByUsages    = new SortedDictionary <ulong, List <ulong> >();
            var linksByFrequency = new SortedDictionary <ulong, List <ulong> >();

            var any       = _links.Constants.Any;
            var @continue = _links.Constants.Continue;
            var query     = new Link <ulong>(any, any, any);

            _links.Each(link =>
            {
                var linkIndex = _links.GetIndex(link);
                var usages    = _links.Count(new ulong[] { any, linkIndex });
                if (!linksByUsages.TryGetValue(usages, out List <ulong> linksByUsageList))
                {
                    linksByUsageList = new List <ulong>();
                    linksByUsages.Add(usages, linksByUsageList);
                }
                linksByUsageList.Add(linkIndex);
                ulong frequency = GetFrequency(link);
                if (!linksByFrequency.TryGetValue(frequency, out List <ulong> linksByFrequencyList))
                {
                    linksByFrequencyList = new List <ulong>();
                    linksByFrequency.Add(frequency, linksByFrequencyList);
                }
                linksByFrequencyList.Add(linkIndex);
                return(@continue);
            }, query);

            // Build matrix of levels on 2D plane (as in optimal variant algorithm)

            var levels = new ulong[width, height];

            var topBottom = 0UL;
            var leftRight = 0UL;
            var bottomTop = 0UL;
            var rightLeft = 0UL;

            var lastX = width - 1;
            var lastY = height - 1;

            // We do not calculate edges to simplify the algorithm
            for (int y = 1; y < lastY; y++)
            {
                for (int x = 1; x < lastX; x++)
                {
                    topBottom = GetFrequency(matrix[x, y - 1].Key[0], matrix[x, y].Key[0]);
                    leftRight = GetFrequency(matrix[x - 1, y].Key[0], matrix[x, y].Key[0]);
                    bottomTop = GetFrequency(matrix[x, y].Key[0], matrix[x, y + 1].Key[0]);
                    rightLeft = GetFrequency(matrix[x, y].Key[0], matrix[x + 1, y].Key[0]);

                    levels[x, y] = Math.Max(Math.Max(topBottom, leftRight), Math.Max(bottomTop, rightLeft));
                }
            }

            // Print levels matrix

            //for (int y = 1; y < lastY; y++)
            //{
            //    for (int x = 1; x < lastX; x++)
            //    {
            //        Console.Write("{0:0000}", levels[x, y]);
            //        Console.Write(' ');
            //    }
            //    Console.WriteLine();
            //}

            // Black and white (split to two colors)

            var contrastedLevels = new ulong[width, height];

            var minimum = ulong.MaxValue;
            var maximum = ulong.MinValue;

            for (int y = 1; y < lastY; y++)
            {
                for (int x = 1; x < lastX; x++)
                {
                    var level = levels[x, y];
                    minimum = minimum > level ? level : minimum;
                }
            }

            for (int y = 1; y < lastY; y++)
            {
                for (int x = 1; x < lastX; x++)
                {
                    var level = levels[x, y];
                    maximum = maximum < level ? level : maximum;
                }
            }

            var middle = (maximum + minimum) / 2;

            for (int y = 1; y < lastY; y++)
            {
                for (int x = 1; x < lastX; x++)
                {
                    contrastedLevels[x, y] = levels[x, y] > middle ? 0UL : 1UL; // the most frequent should be background (zero)
                }
            }

            // Print contrasted levels matrix

            //for (int y = 1; y < lastY; y++)
            //{
            //    for (int x = 1; x < lastX; x++)
            //    {
            //        Console.Write("{0:0}", contrastedLevels[x, y]);
            //    }
            //    Console.WriteLine();
            //}

            var outputImagePath = Path.ChangeExtension(_sourceImagePath, ".bf.png");

            using (var outputImage = new MagickImage(MagickColor.FromRgba(0, 0, 0, 255), width, height))
            {
                var pixels = outputImage.GetPixels();
                for (int y = 1; y < lastY; y++)
                {
                    for (int x = 1; x < lastX; x++)
                    {
                        if (contrastedLevels[x, y] > 0)
                        {
                            pixels.SetPixel(x, y, new byte[] { 255, 255, 255, 255 });
                        }
                    }
                    Console.WriteLine();
                }
                outputImage.Write(outputImagePath);
            }

            // Get the largest repeated patterns with lowest frequency (level)
        }
Esempio n. 15
0
        public static bool Exists <TLinkAddress, TConstants>(this ILinks <TLinkAddress, TConstants> links, TLinkAddress link)
            where TConstants : LinksConstants <TLinkAddress>
        {
            var constants = links.Constants;

            return(constants.IsExternalReference(link) || (constants.IsInternalReference(link) && Comparer <TLinkAddress> .Default.Compare(links.Count(new LinkAddress <TLinkAddress>(link)), default) > 0));
        }
Esempio n. 16
0
 public static TLinkAddress Count <TLinkAddress, TConstants>(this ILinks <TLinkAddress, TConstants> links, params TLinkAddress[] restrictions)
     where TConstants : LinksConstants <TLinkAddress>
 => links.Count(restrictions);