Exemplo n.º 1
0
        public void WriteCell()
        {
            List <ArchiveEntity> tree = codesHelp.Values.OrderBy(prob => prob.Frequency).ToList();

            for (int i = 0; i < codesHelp.Count - 1; i++)
            {
                var o = tree[0];
                var t = tree[1];
                foreach (var c in o.Char)
                {
                    codesHelp[c].Code.Add(true);
                }
                foreach (var c in t.Char)
                {
                    codesHelp[c].Code.Add(false);
                }
                tree.Add(new ArchiveEntity()
                {
                    Char = o.Char + t.Char, Frequency = o.Frequency + t.Frequency
                });
                tree = tree.Skip(2).OrderBy(prob => prob.Frequency).ToList();
            }
            foreach (var archiveEntity in codesHelp)
            {
                codes.Add(archiveEntity.Key, archiveEntity.Value.Code.Cast <bool>().Reverse().ToArray());
            }

            object[][] objects = codes.Select(pair => new object[] { pair.Key, pair.Value.Cast <object>().ToArray() })
                                 .ToArray();
            codesCell.Fill2(objects);
        }
Exemplo n.º 2
0
 public void Load(IEnumerable <object[]> rec_flow)
 {
     acell.Clear();
     acell.Fill(new object[0]);
     foreach (object[] rec in rec_flow)
     {
         acell.Root.AppendElement(new object[] { rec[0], rec[1], false });
     }
     acell.Flush();
     xcell.Clear();
     xcell.Fill2(acell.Root.Get());
     xcell.Flush();
     xcell.Root.Sort((PxEntry entry) => (string)entry.Field(0).Get()); // Это надо привести в соответствие с типом ключа
 }
Exemplo n.º 3
0
        public void Create()
        {
            icell.Clear();

            object[] ivalue = table.Root.Elements().Select(rec =>
            {
                return(new object[] { ((object[])rec.Get())[field_numb], rec.offset });
            }).ToArray();
            icell.Fill2(ivalue);
            icell.Flush();
            icell.Root.Sort(entry => (string)entry.Field(0).Get());
            //icell.Root.SortComparison((e1, e2) => ((string)((object[])e1.Get().Value)[0]).CompareTo((string)((object[])e2.Get().Value)[0]));
            Console.WriteLine(icell.Root.Count());
        }
Exemplo n.º 4
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();
        }
Exemplo n.º 5
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);
        }
Exemplo n.º 6
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;
        }
Exemplo n.º 7
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");
        }