Esempio n. 1
0
        public SemiIndex(string indexName, PType field_type)
        {
            PType tp_index = new PTypeSequence(new PTypeRecord(
                                                   new NamedType("key", field_type),
                                                   new NamedType("value", new PType(PTypeEnumeration.longinteger)),
                                                   new NamedType("deleted", new PType(PTypeEnumeration.boolean))));

            acell = new PaCell(tp_index, indexName + ".pac", false);
            xcell = new PxCell(tp_index, indexName + ".pxc", false);
        }
Esempio n. 2
0
 // Конструктор
 public TGraph(string path)
 {
     LoadTypes();
     this.path = path;
     otriples  = new PaCell(tp_otriples, path + "otriples.pac", false);
     literals  = new PaCell(tp_rliteral_seq, path + "literals.pac", false);
     dtriples  = new PaCell(tp_dtriples, path + "dtriples.pac", false);
     tree_fix  = new PxCell(tp_entitiesTree, path + "tree_fix.pxc", false);
     FillDictionary();
 }
Esempio n. 3
0
 private void InitCells()
 {
     if (!File.Exists(path + "triplets.pac") ||
         !File.Exists(path + "graph_x.pxc"))
     {
         return;
     }
     triplets    = new PaCell(tp_triplets, path + "triplets.pac");
     any_triplet = triplets.Root.Element(0);
     graph_x     = new PxCell(tp_graph, path + "graph_x.pxc");
 }
Esempio n. 4
0
        private static void Write(PxCell xcell, FileStream fs)
        {
            xcell.Root.Set(new object[] { 99, new object[0] });
            xcell.Root.Field(1).SetRepeat(fs.Length);
            PxEntry zel = xcell.Root.Field(1).Element(0);

            fs.Position = 0L;
            xcell.BasicStream.Position = zel.offset;
            fs.CopyTo(xcell.BasicStream);
            xcell.BasicStream.Flush();
        }
Esempio n. 5
0
 public Archive(string path)
 {
     this.path = path;
     if (!Directory.Exists(path))
     {
         Directory.CreateDirectory(path);
     }
     codesCell  = new PxCell(_pTypeSequence, path + "/codes.pxc", false);
     decodeTree = new BinaryTree <char>(null, null);
     ReadCell();
 }
Esempio n. 6
0
        public PIndex(string ind_path, PaCell table, int field_numb)
        {
            this.table      = table;
            this.field_numb = field_numb;
            PTypeSequence table_type = (PTypeSequence)table.Type;
            PType         field_type = ((PTypeRecord)table_type.ElementType).Fields[field_numb].Type;
            PType         tp_index   = new PTypeSequence(new PTypeRecord(
                                                             new NamedType("key", field_type),
                                                             new NamedType("value", new PType(PTypeEnumeration.longinteger))));

            icell = new PxCell(tp_index, ind_path + "index.pxc", false);
        }
Esempio n. 7
0
        public SGraph(string path, Uri uri)
        {
            this.path    = path;
            Uri          = uri;
            otriples     = new PaCell(tp_otriple_seq, path + "otriples.pac", false);
            dtriples     = new PaCell(tp_dtriple_spf, path + "dtriples.pac", false); // Временно выведена в переменные класса, открывается при инициализации
            dataCell     = new PaCell(tp_data_seq, path + "data.pac", false);
            entitiesTree = new PxCell(tp_entitiesTree, path + "entitiesTree.pxc", false);

            namespaceMaper = new NamespaceMapCoding(new StringIntMD5RAMUnsafe(path));
            scale          = new ScaleCell(path);
        }
Esempio n. 8
0
 public override void WarmUp()
 {
     entitiesTree.Close();
     using (FileStream reader = new FileStream(entitiesTreePath, FileMode.Open))
     {
         int read = 1;
         while (read > 0)
         {
             byte[] temp = new byte[500];
             read = reader.Read(temp, 0, 500);
         }
     }
     entitiesTree = new PxCell(tp_entitiesTree, entitiesTreePath);
     base.WarmUp();
 }
Esempio n. 9
0
        /// <summary>
        /// Конструктор
        /// </summary>
        /// <param name="path">директория базы данных с (обратным) слешем</param>
        /// <param name="literalStore"></param>
        /// <param name="entityCoding"></param>
        /// <param name="nameSpaceStore"></param>
        /// <param name="predicatesCoding"></param>
        public RdfTrees(string path, IStringIntCoding entityCoding, PredicatesCoding predicatesCoding, NameSpaceStore nameSpaceStore, LiteralStoreAbstract literalStore)
            : base(path, entityCoding, predicatesCoding, nameSpaceStore, literalStore)
        {
            // Построим типы
            InitTypes();
            // Создадим или откроем ячейки
            this.entitiesTree = new PxCell(tp_entitiesTree, entitiesTreePath = path + "entitiesTree.pxc", false);
            //this.literalsTree = new PxCell(tp_literalsTree, path + "literalsTree.pxc", false);
            //  this.dtriples = new PaCell(tp_dtriple_spf, path + "dtriples.pac", false); // Это вместо не работающего дерева литералов       }


            otriples = new PaCell(tp_otriple_seq, path + "otriples.pac", File.Exists(path + "otriples.pac"));

            otriples.Close();
        }
Esempio n. 10
0
 private void InitCells()
 {
     if (!File.Exists(path + "triplets.pac") ||
         !File.Exists(path + "graph_x.pxc"))
     {
         return;
     }
     triplets = new PaCell(tp_triplets, path + "triplets.pac");
     if (triplets.Root.Count() == 0)
     {
         triplets.Close(); File.Delete(path + "triplets.pac"); throw new Exception("Error in data: no triples loaded, file removed");
     }
     any_triplet = triplets.Root.Element(0);
     graph_x     = new PxCell(tp_graph, path + "graph_x.pxc");
     n4          = new PaCell(tp_n4, path + "n4.pac");
 }
Esempio n. 11
0
        public void Load(string[] rdf_files)
        {
            DateTime tt0 = DateTime.Now;

            // Закроем использование
            if (triplets != null)
            {
                triplets.Close(); triplets = null;
            }
            if (graph_x != null)
            {
                graph_x.Close(); graph_x = null;
            }
            // Создадим ячейки
            triplets = new PaCell(tp_triplets, path + "triplets.pac", false);
            triplets.Clear();
            quads   = new PaCell(tp_quads, path + "quads.pac", false);
            graph_a = new PaCell(tp_graph, path + "graph_a.pac", false);
            graph_x = new PxCell(tp_graph, path + "graph_x.pxc", false); graph_x.Clear();
            n4      = new PaCell(tp_n4, path + "n4.pac", false); n4.Clear();
            Console.WriteLine("cells initiated duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            TripletSerialInput(triplets, rdf_files);
            Console.WriteLine("After TripletSerialInput. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;


            LoadQuadsAndSort();
            Console.WriteLine("After LoadQuadsAndSort(). duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            FormingSerialGraph(new SerialBuffer(graph_a, 3));
            Console.WriteLine("Forming serial graph ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // произвести объектное представление
            object g_value = graph_a.Root.Get().Value;

            graph_x.Fill2(g_value);
            Console.WriteLine("Forming fixed graph ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // ========= Завершение загрузки =========
            // Закроем файлы и уничтожим ненужные
            triplets.Close();
            quads.Close(); File.Delete(path + "quads.pac");
            graph_a.Close(); File.Delete(path + "graph_a.pac");
            graph_x.Close();
            // Откроем для использования
            InitCells();
        }
Esempio n. 12
0
 // Конструктор
 public RdfGraph(string path)
 {
     LoadTypes();
     this.path = path;
     otriples  = new PaCell(tp_otriples, path + "otriples.pac", false);
     literals  = new PaCell(tp_rliteral_seq, path + "literals.pac", false);
     dtriples  = new PaCell(tp_dtriples, path + "dtriples.pac", false);
     tree_fix  = new PxCell(tp_entitiesTree, path + "tree_fix.pxc", false);
     if (!tree_fix.IsEmpty) // Возможно, не требуется проверять
     {
         for (int i = 0; i < tree_fix.Root.Count(); i++)
         {
             object[] rec = (object[])tree_fix.Root.Element(i).Get();
             int      key = (int)rec[0];
             //codeNumb.Add(key, i);
             var f = ((object[])rec[1])
                     .Cast <object[]>()
                     .Select(ob2 => new KeyValuePair <int, long>((int)ob2[0], (long)ob2[1]))
                     .ToArray();
             var d = ((object[])rec[2])
                     .Cast <object[]>()
                     .Select(ob2 => new KeyValuePair <int, int>((int)ob2[0], (int)ob2[1]))
                     .ToArray();
             var inverse = ((object[])rec[3])
                           .Cast <object[]>()
                           .Select(ob2 => new KeyValuePair <int, int[]>((int)ob2[0], ((object[])ob2[1]).Cast <int>().ToArray()))
                           .ToArray();
             codeRec.Add(key,
                         new record()
             {
                 fields  = f,
                 direct  = d,
                 inverse = inverse
             });
         }
         //codeNumb
     }
 }
Esempio n. 13
0
        private static BTree TestBTreeFill(IEnumerable <object[]> query, PTypeRecord ptElement, string path,
                                           Func <object, PxEntry, int> edepth)
        {
            PxCell elementsCell = new PxCell(new PTypeSequence(ptElement), path + "elements", false);

            elementsCell.Fill2(query);
            var tt0 = DateTime.Now;

            var treeFromQuery = new BTree(ptElement, edepth, path + "TreeFromEntree.pxc", readOnly: false);

            treeFromQuery.Fill(elementsCell.Root, o => ((object[])o)[0], false);
            Console.WriteLine("tree fill reading entry createtd,duration={0}", (DateTime.Now - tt0).Ticks / 10000L);
            tt0 = DateTime.Now;
            // Иcпытание на "предельные" характеристики по скорости ввода данных. Данные сортируются, а потом выстраивается в
            // оперативной памяти структурный объект, соответствующий синтаксису и семантике введенного бинарного дерева.
            // Потом объект вводится в ячейку и испытывается.
            // На моем домашнем компьютере - 130 мс.
            TestSearch(treeFromQuery, "Марчук Александр Гурьевич");
            Console.WriteLine("======TestSearch ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L);
            Console.WriteLine();
            elementsCell.Close();
            return(treeFromQuery);
        }
Esempio n. 14
0
        private static void Create(string sarc2path)
        {
            Stream stream = new FileStream(sarc2path, FileMode.Open, FileAccess.Read);

            long offset = 0L;

            for (int i = 0; i < 16; i++)
            {
                int b = stream.ReadByte();
                if (b != 0)
                {
                    offset = offset * 10 + (b - '0');
                }
            }

            byte[] catalog_bytes = new byte[offset - 16];

            stream.Read(catalog_bytes, 0, (int)(offset - 16));
            int width  = 0;
            int height = 0;

            var levels = XElement.Load(new XmlTextReader(new MemoryStream(catalog_bytes))).Elements("file")
                         .Select(xfile =>
            {
                string r_path = xfile.Element("path").Value;
                var regex     = new Regex(@"(?<level>[0-9]+)/(?<x>[0-9]+)_(?<y>[0-9]+)\.jpg$");

                var match = regex.Match(r_path);
                if (!match.Success)
                {
                    if (Path.GetExtension(r_path) == ".xml")
                    {
                        stream.Seek(long.Parse(xfile.Element("start").Value) + offset, SeekOrigin.Begin);
                        var dataxml = new byte[long.Parse(xfile.Element("length").Value)];
                        stream.Read(dataxml, 0, dataxml.Length);
                        XElement xDzi = XElement.Load(XmlReader.Create(new MemoryStream(dataxml)));
                        var xElement  =
                            xDzi.Element(XNamespace.Get("http://schemas.microsoft.com/deepzoom/2009") + "Size");

                        width  = int.Parse(xElement.Attribute("Width").Value);
                        height = int.Parse(xElement.Attribute("Height").Value);

                        return(null);
                    }
                    else
                    {
                        throw new Exception();
                    }
                }
                int level = Convert.ToInt32(match.Groups["level"].Value);
                int x     = Convert.ToInt32(match.Groups["x"].Value);
                int y     = Convert.ToInt32(match.Groups["y"].Value);
                stream.Seek(long.Parse(xfile.Element("start").Value) + offset, SeekOrigin.Begin);
                var data = new byte[long.Parse(xfile.Element("length").Value)];
                stream.Read(data, 0, data.Length);
                return(new { level, x, y, data = data.Cast <object>().ToArray() });
            })
                         .Where(arg => arg != null)
                         .GroupBy(arg => arg.level)
                         .OrderBy(level => level.Key)
                         .Select(gl =>
                                 gl.GroupBy(arg => arg.x)
                                 .OrderBy(xs => xs.Key)
                                 .Select(gx =>
                                         gx.OrderBy(arg => arg.y)
                                         .Select(arg => arg.data)
                                         .ToArray())
                                 .ToArray())
                         .ToArray();

            stream.Close();

            if (width == 0 || height == 0)
            {
                throw new Exception();
            }

            cell =
                new PxCell(
                    new PTypeRecord(new NamedType("width", new PType(PTypeEnumeration.integer)),
                                    new NamedType("height", new PType(PTypeEnumeration.integer)),
                                    new NamedType("images",
                                                  new PTypeSequence(         //by level
                                                      new PTypeSequence(     //by x
                                                          new PTypeSequence( //by y
                                                              new PTypeSequence(new PType(PTypeEnumeration.@byte))))))),
                    Path.ChangeExtension(sarc2path, ".dz_px"), false);


            cell.Fill(new object[] { width, height, levels });
        }
Esempio n. 15
0
        // Проверка эффективности работы последовательностей фиксированного формата
        static void Main(string[] args)
        {
            string   path  = @"..\..\..\Databases\";
            DateTime tt0   = DateTime.Now;
            Random   rnd   = new Random(7777777);
            PaCell   icell = new PaCell(new PTypeSequence(new PType(PTypeEnumeration.integer)), path + "icell.pac", false);
            PxCell   xcell = new PxCell(new PTypeSequence(new PType(PTypeEnumeration.integer)), path + "xcell.pac", false);

            bool toload  = false;
            int  nvalues = 10000000;

            if (toload)
            {
                icell.Clear();
                icell.Fill(new object[0]);
                for (int i = 0; i < nvalues; i++)
                {
                    icell.Root.AppendElement(rnd.Next());
                }
                icell.Flush();
                Console.WriteLine("Load1 ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;
                PaEntry.bufferBytes = 200000000;
                icell.Root.SortByKey <int>(ob => (int)ob);;
                Console.WriteLine("Sort ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;
            }
            bool toload2 = false;

            if (toload2)
            {
                xcell.Clear();
                //xcell.Root.SetRepeat(nvalues);
                //for (int i = 0; i < nvalues; i++)
                //{
                //    xcell.Root.Element(i).Set(icell.Root.Element(i).Get());
                //}
                //xcell.Flush();
                //xcell.Fill(icell.Root.Get());
                xcell.Root.Set(icell.Root.Get());
                Console.WriteLine("Load2 ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;
                xcell.Flush();
            }

            //foreach (var v in icell.Root.ElementValues()) ;
            //var ooo = xcell.Root.Get();
            foreach (var xent in xcell.Root.Elements())
            {
                var xxx = xent.Get();
            }
            Console.WriteLine("WarmUp ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            rnd = new Random(7777777);
            int start = nvalues / 2;

            for (int i = 0; i < start; i++)
            {
                int r0 = rnd.Next();
            }
            for (int i = start; i < start + 10000; i++)
            {
                int r = rnd.Next(nvalues - 1);
                int v = (int)icell.Root.Element(r).Get();
                //int v = (int)xcell.Root.Element(r).Get();
            }
            Console.WriteLine("ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;
            rnd = new Random(7777777);
            for (int i = 0; i < start; i++)
            {
                int r0 = rnd.Next();
            }                                                        // Пропустили половину чисел
            int found = 0;

            for (int i = start; i < start + 10000; i++)
            {
                int     r     = rnd.Next();
                PaEntry entry = icell.Root.BinarySearchFirst(en => ((int)en.Get()).CompareTo(r));
                //PxEntry entry = xcell.Root.BinarySearchFirst(en => ((int)en.Get()).CompareTo(r));
                if (entry.IsEmpty)
                {
                    continue;
                }
                int v = (int)entry.Get();
                //int v = (int)xcell.Root.Element(r).Get();
                found++;
            }
            Console.WriteLine("found {0} ok. duration={1}", found, (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;
        }
Esempio n. 16
0
        public int MakeTreeFix()
        {
            DateTime tt0 = DateTime.Now;
            // Служебная часть. Она не нужна, если параметрами будут PaCell otriples, PaCell otriples_op, PaCell dtriples_sp
            PType tp_entity      = new PType(PTypeEnumeration.integer);
            PType tp_otriple_seq = new PTypeSequence(new PTypeRecord(
                                                         new NamedType("subject", tp_entity),
                                                         new NamedType("predicate", tp_entity),
                                                         new NamedType("object", tp_entity)));
            //PType tp_dtriple_seq = new PTypeSequence(new PTypeRecord(
            //    new NamedType("subject", tp_entity),
            //    new NamedType("predicate", tp_entity),
            //    new NamedType("data", tp_literal)));
            PType tp_dtriple_spf = new PTypeSequence(new PTypeRecord(
                                                         new NamedType("subject", tp_entity),
                                                         new NamedType("predicate", tp_entity),
                                                         new NamedType("offset", new PType(PTypeEnumeration.longinteger))));

            otriples = new PaCell(tp_otriple_seq, path + "otriples.pac", true);
            PaCell otriples_op = new PaCell(tp_otriple_seq, path + "otriples_op.pac", true);
            PaCell dtriples_sp = new PaCell(tp_dtriple_spf, path + "dtriples.pac", true);

            // ==== Определение количества сущностей ====
            // Делаю три упрощенных сканера
            DiapasonScanner <int> i_fields = new DiapasonScanner <int>(dtriples_sp, ent =>
            {
                object[] v = (object[])ent.Get();
                return((int)v[0]);
            });
            DiapasonScanner <int> i_direct = new DiapasonScanner <int>(otriples, ent =>
            {
                object[] v = (object[])ent.Get();
                return((int)v[0]);
            });
            DiapasonScanner <int> i_inverse = new DiapasonScanner <int>(otriples_op, ent =>
            {
                object[] v = (object[])ent.Get();
                return((int)v[2]);
            });
            int n_entities = 0;

            i_fields.Start();
            i_direct.Start();
            i_inverse.Start();
            while (i_fields.HasValue || i_direct.HasValue || i_inverse.HasValue)
            {
                n_entities++;
                int id0 = i_fields.HasValue ? i_fields.KeyCurrent : Int32.MaxValue;
                int id1 = i_direct.HasValue ? i_direct.KeyCurrent : Int32.MaxValue;
                int id2 = i_inverse.HasValue ? i_inverse.KeyCurrent : Int32.MaxValue;
                // Минимальное значение кода идентификатора
                int id = Math.Min(id0, Math.Min(id1, id2));

                if (id0 == id)
                {
                    i_fields.Next();
                }
                if (id1 == id)
                {
                    i_direct.Next();
                }
                if (id2 == id)
                {
                    i_inverse.Next();
                }
            }
            Console.WriteLine("Scan3count ok. Duration={0} msec. cnt_e={1} ", (DateTime.Now - tt0).Ticks / 10000L, n_entities); tt0 = DateTime.Now;

            // ==== Построение дерева слиянием отрех ячеек ====
            // Делаю три сканера из трех ячеек
            DiapasonElementsScanner <SubjPredInt> fields = new DiapasonElementsScanner <SubjPredInt>(dtriples_sp, ob =>
            {
                object[] v = (object[])ob;
                return(new SubjPredInt()
                {
                    subj = (int)v[0], pred = (int)v[1]
                });
            });
            DiapasonElementsScanner <SubjPredInt> direct = new DiapasonElementsScanner <SubjPredInt>(otriples, ob =>
            {
                object[] v = (object[])ob;
                return(new SubjPredInt()
                {
                    subj = (int)v[0], pred = (int)v[1]
                });
            });
            DiapasonElementsScanner <SubjPredInt> inverse = new DiapasonElementsScanner <SubjPredInt>(otriples_op, ob =>
            {
                object[] v = (object[])ob;
                return(new SubjPredInt()
                {
                    subj = (int)v[2], pred = (int)v[1]
                });
            });

            // Стартуем сканеры
            fields.Start(); direct.Start(); inverse.Start();

            // Заведем ячейку для результата сканирования
            PxCell tree_fix = this.entitiesTree; //new PxCell(tp_entitiesTree, path + "tree_fix.pxc", false);

            tree_fix.Clear();
            tree_fix.Root.SetRepeat(namespaceMaper.coding.Count);
            Console.WriteLine("tree_fix length={0}", tree_fix.Root.Count());


            int  cnt_e = 0;              // для отладки
            long c1 = 0, c2 = 0, c3 = 0; // для отладки

            //PaEntry ent_dtriples = dtriples.Root.Element(0); // вход для доступа к литералам
            // Начинаем тройное сканирование
            while (fields.HasValue || direct.HasValue || inverse.HasValue)
            {
                // Здесь у нас НОВОЕ значение идентификатора
                cnt_e++;
                if (cnt_e % 10000000 == 0)
                {
                    Console.Write("{0} ", cnt_e / 10000000);
                }
                int id0 = fields.HasValue ? fields.KeyCurrent.subj : Int32.MaxValue;
                int id1 = direct.HasValue ? direct.KeyCurrent.subj : Int32.MaxValue;
                int id2 = inverse.HasValue ? inverse.KeyCurrent.subj : Int32.MaxValue;
                // Минимальное значение кода идентификатора
                int id = Math.Min(id0, Math.Min(id1, id2));
                // массив для получения "однородных" элементов из сканнеров
                object[] elements;

                List <object[]> list_fields = new List <object[]>();
                while (fields.HasValue && fields.KeyCurrent.subj == id)
                {
                    int su   = fields.KeyCurrent.subj;
                    int pr   = fields.KeyCurrent.pred;
                    var diap = fields.Next(out elements);

                    c3 += diap.numb;
                    list_fields.AddRange(elements.Cast <object[]>().Select(e3 => new object[] { e3[1], e3[2] }));
                }
                List <object[]> list_direct = new List <object[]>();
                while (direct.HasValue && direct.KeyCurrent.subj == id)
                {
                    int su   = direct.KeyCurrent.subj;
                    int pr   = direct.KeyCurrent.pred;
                    var diap = direct.Next(out elements);

                    c1 += diap.numb;
                    list_direct.AddRange(elements.Cast <object[]>().Select(e3 => new object[] { e3[1], e3[2] }));
                }
                List <object[]> list_inverse = new List <object[]>();
                while (inverse.HasValue && inverse.KeyCurrent.subj == id)
                {
                    int su   = inverse.KeyCurrent.subj;
                    int pr   = inverse.KeyCurrent.pred;
                    var diap = inverse.Next(out elements);

                    c2 += diap.numb;
                    object[] pr_sources_pair = new object[2];
                    pr_sources_pair[0] = pr;
                    pr_sources_pair[1] = elements.Cast <object[]>().Select(e3 => e3[0]).ToArray();
                    list_inverse.Add(pr_sources_pair);
                }
                //Собираем полную запись
                object[] record = new object[] { id, list_fields.ToArray(), list_direct.ToArray(), list_inverse.ToArray() };
                // Записываем в качестве элемента последовательности

                if (id == 0)
                {
                    Console.WriteLine("sfgh");
                }
                tree_fix.Root.Element(id).Set(record);
            }
            tree_fix.Close();
            this.entitiesTree = new PxCell(tp_entitiesTree, path + "entitiesTree.pxc", false);
            Console.WriteLine("Scan3fix ok. Duration={0} msec. cnt_e={1} ", (DateTime.Now - tt0).Ticks / 10000L, cnt_e); tt0 = DateTime.Now;
            return(cnt_e);
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            string path = @"..\..\..\Databases\";

            InitTypes();
            DateTime tt0 = DateTime.Now;

            // Проверка объекта
            object[] testdb = new object[] {
                new object[] { 1, new object[] { "a", "b", "c" } },
                new object[] { 1, new object[] { "a1", "b1", "c1" } },
                new object[] { 2, new object[] { "da", "db", "dc", "lang" } }
            };
            Console.WriteLine(seqtriplets.Interpret(testdb));

            // Создание ячейки плавающего формата
            string testpacfilename = path + "test.pac";

            if (System.IO.File.Exists(testpacfilename))
            {
                System.IO.File.Delete(testpacfilename);
            }
            PaCell cell = new PaCell(seqtriplets, testpacfilename, false); // false - чтобы заполнять

            // Заполнение ячейки данными из объекта
            cell.Fill(testdb);
            // Проверка того, что имеется в ячейке
            var cell_pvalue = cell.Root.GetValue();

            Console.WriteLine(cell_pvalue.Type.Interpret(cell_pvalue.Value));

            PTypeUnion tp_u = new PTypeUnion();

            tp_u.Variants = new[] {
                new NamedType("empty", new PType(PTypeEnumeration.none)),
                new NamedType("node", new PTypeRecord(
                                  new NamedType("f0", new PType(PTypeEnumeration.boolean)),
                                  new NamedType("f1", new PTypeSequence(tp_u))))
            };
            object[] vv = new object[] { 1,
                                         new object[] {
                                             true,
                                             new object[] {
                                                 new object[] { 1,
                                                                new object[] {
                                                                    false,
                                                                    new object[0]
                                                                } }
                                             }
                                         } };
            PxCell xcell = new PxCell(tp_u, path + "xcell.pxc", false);

            xcell.Fill(vv);
            PxEntry e1 = xcell.Root.UElement().Field(1);
            PxEntry e2 = e1.Element(0);
            var     v  = e2.GetValue();

            Console.WriteLine(v.Type.Interpret(v.Value));

            return;

            //cell.Clear();
            //cell.Fill(testtriplets); // проверка на то, что при неочищенной ячейке, записать в нее нельзя
            //cell.Close();
            //cell.Clear();
            //cell.Fill(testtriplets); // проверка на то, что при очищении, записать можно

            //// Проверка серийного буфера, в него загружаются данные из XML-файла, в ячейку ничего не помещается
            //// Этот тест, для начала, можно пропустить.
            //tt0 = DateTime.Now;
            //SerialBuffer buff = new SerialBuffer(new SerialFlowReceiverStub(seqtriplets));
            //TestSerialInput(buff, path);
            //Console.WriteLine("Число элементов в объекте:" + ((object[])buff.Result).LongLength);
            //Console.WriteLine("Forming buffer ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // Проверка ввода из серийного скобочного потока для ячейки свободного формата
            // В данном случае, поток порождается при сканировании XML-документа
            tt0 = DateTime.Now;
            cell.Clear();
            TestSerialInput(cell, path);
            Console.WriteLine("Число элементов в объекте:" + cell.Root.Count());
            Console.WriteLine("Serial input ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;
            cell.Close(); // Ячейка закрыта, теперь ее нельзя использовать

            // Проверка создания ячейки в режиме чтения
            PaCell cell2pac = new PaCell(seqtriplets, testpacfilename);
            long   cnt2     = cell2pac.Root.Count();
            var    pval2    = cell2pac.Root.Element(100000).GetValue();

            Console.WriteLine("cnt2=" + cnt2 + " Element(100000).Get()=" + pval2.Type.Interpret(pval2.Value));
            Console.WriteLine("ReadObly cell ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // Создание ячейки фиксированного формата
            xcell.Clear();
            xcell = new PxCell(seqtriplets, path + "test.pxc", false);
            var pv = cell2pac.Root.Get();

            tt0 = DateTime.Now;
            xcell.Fill2(pv); // Плохой метод, заменю на хороший
            Console.WriteLine("xcell Fill ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // Проверка наполнения
            PxEntry rxt = xcell.Root;
            var     ele = rxt.Element(400000).GetValue();

            Console.WriteLine(ele.Type.Interpret(ele.Value));
            Console.WriteLine("ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;
        }
Esempio n. 18
0
        // Из XML базы данных, выбирается множество RDF-дуг (DatatypeProperty) с предикатом http://fogid.net/o/name и формируется
        // последовательность пар (записей) имя-сущности - идентификатор сущности. Задача заключается в том, чтобы по частичному
        // имени, определить множество идентификаторов сущностей, для которых имеется похожее имя

        public static void Main(string[] args)
        {
            string path = @"..\..\..\Databases\";

            // Тестирование сортировки по ключу со слиянием
            PaEntry.bufferBytes = 40;
            PaCell cell_simple = new PaCell(new PTypeSequence(new PType(PTypeEnumeration.integer)), path + "cimple.pac", false);

            cell_simple.Clear();
            object[] arr = { 97, 1, 3, 2, 4, 9, 8, 7, 6, 0, 5, 99, 98 };
            cell_simple.Fill(arr);
            cell_simple.Flush();
            Console.WriteLine(cell_simple.Type.Interpret(cell_simple.Root.Get()));
            cell_simple.Root.SortByKey <int>(i_key => (int)i_key);
            Console.WriteLine(cell_simple.Type.Interpret(cell_simple.Root.Get()));
            return;

            PType tp_seq = new PTypeSequence(new PTypeRecord(
                                                 new NamedType("name", new PType(PTypeEnumeration.sstring)),
                                                 new NamedType("id", new PType(PTypeEnumeration.sstring))));

            DateTime tt0 = DateTime.Now;

            Console.WriteLine("Start");

            PaCell cella = new PaCell(tp_seq, path + "cella.pac", false);

            cella.Clear();

            // Заполним ячейку данными
            XElement db = XElement.Load(path + "0001.xml");

            cella.StartSerialFlow();
            cella.S();
            foreach (XElement rec in db.Elements())
            {
                XAttribute about_att = rec.Attribute(sema2012m.ONames.rdfabout);
                if (about_att == null)
                {
                    continue;
                }
                foreach (XElement prop in rec.Elements().Where(pr => pr.Name.LocalName == "name"))
                {
                    cella.V(new object[] { prop.Value, about_att.Value });
                }
            }
            cella.Se();
            cella.EndSerialFlow();
            // Проверим, что данные прочитались (должно получится 40361 пар имя-идентификатор)
            Console.WriteLine(cella.Root.Count());

            // Надо перевести данные в фиксированный формат
            PxCell cell_seqnameid = new PxCell(tp_seq, path + "seqnameid.pxc", false);

            // очистим и перекинем данные
            cell_seqnameid.Clear();
            cell_seqnameid.Fill2(cella.Root.Get());

            Console.WriteLine("======Fill ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            //// Теперь сортируем пары по первому (нулевому) полю
            //cell_seqnameid.Root.SortComparison((e1, e2) =>
            //{
            //    string s1 = (string)e1.Field(0).Get();
            //    string s2 = (string)e2.Field(0).Get();
            //    return s1.CompareTo(s2);
            //});
            //Console.WriteLine("======Sort ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // Сортируем по-другому
            cell_seqnameid.Root.Sort(e =>
            {
                return((string)e.Field(0).Get());
            });
            Console.WriteLine("======Sort2 ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // Посмотрим первые 100
            var qu = cell_seqnameid.Root.Elements().Skip(100).Take(10);

            foreach (var c in qu)
            {
                var v = c.GetValue();
                Console.WriteLine(v.Type.Interpret(v.Value));
            }
            Console.WriteLine("======First 10 after 100. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // поищем чего-нибудь
            string name  = "Марчук Александр Гурьевич";
            var    found = cell_seqnameid.Root.BinarySearchFirst(e =>
            {
                string nm = (string)e.Field(0).Get();
                return(nm.CompareTo(name));
            });
            var f = found.GetValue();

            Console.WriteLine(f.Type.Interpret(f.Value));
            Console.WriteLine("======BinarySearchFirst. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // поищем  по-другому
            string name2  = "марчук";
            var    found2 = cell_seqnameid.Root.BinarySearchFirst(e =>
            {
                string nm = ((string)e.Field(0).Get()).ToLower();
                if (nm.StartsWith(name2))
                {
                    return(0);
                }
                return(nm.CompareTo(name));
            });
            var f2 = found.GetValue();

            Console.WriteLine(f2.Type.Interpret(f2.Value));
            Console.WriteLine("======BinarySearchFirst variant 2. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // Поиск всех, удовлетворяющих условию
            string name3  = "белинский";
            var    found3 = cell_seqnameid.Root.BinarySearchAll(e =>
            {
                string nm = ((string)e.Field(0).Get()).ToLower();
                if (nm.StartsWith(name3))
                {
                    return(0);
                }
                return(nm.CompareTo(name3));
            });

            foreach (var ff in found3)
            {
                var f3 = ff.GetValue();
                Console.WriteLine(f3.Type.Interpret(f3.Value));
            }
            Console.WriteLine("======BinarySearchAll ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // Проверка "вручную" правильности поиска всех
            var query = cell_seqnameid.Root.Elements();

            foreach (var rec in query)
            {
                object[] value = (object[])rec.Get();
                string   nam   = ((string)value[0]).ToLower();
                if (nam.StartsWith(name3))
                {
                    Console.WriteLine("{0} {1}", value[0], value[1]);
                }
            }

            Console.WriteLine("======Fin. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;
            cella.Close();
            cell_seqnameid.Close();
            System.IO.File.Delete(path + "cella.pac");
            System.IO.File.Delete(path + "seqnameid.pxc");
        }