Beispiel #1
0
 public void Close()
 {
     nc_cell.Close();
     n_index.Close();
     c_index.Close();
     mode = null;
 }
Beispiel #2
0
        private void PrepareArrays()
        {
            // Создание и упорядочивание дополнительных структур

            otriples_op.Close();
            otriples.Close();
            if (File.Exists(otriplets_op_filePath + "tmp"))
            {
                File.Delete(otriplets_op_filePath + "tmp");
            }
            File.Copy(otriples_filePath + "tmp", otriplets_op_filePath + "tmp");
            otriples_op = new PaCell(tp_otriple_seq, otriplets_op_filePath + "tmp", false);
            otriples    = new PaCell(tp_otriple_seq, otriples_filePath + "tmp", false);
            //otriples_op.Clear();
            //otriples_op.Fill(new object[0]);
            //foreach (object v in otriples.Root.ElementValues()) otriples_op.Root.AppendElement(v);
            //otriples_op.Flush();

            //foreach (PaEntry entry in dtriples.Root.Elements())
            //{
            //    int s = (int)entry.Field(0).Get();
            //    int p = (int)entry.Field(1).Get();
            //    dtriples_sp.Root.AppendElement(new object[] { s, p, entry.offset });
            //}
            //       dataCell.Root.Scan((off, pobj) =>
            //{
            //    object[] tri = (object[])pobj;
            //    int s = (int)tri[0];
            //    int p = (int)tri[1];
            //    dtriples_sp.Root.AppendElement(new object[] { s, p, off });
            //    return true;
            //});
            //dtriples_sp.Flush();
        }
        public void Load(int tripletsCountLimit, params string[] filesPaths)
        {
            directCell.Close();
            dataCell.Close();

            File.Delete(dataCellPath);
            File.Delete(directCellPath);

            directCell = new PaCell(ptDirects, directCellPath, false);
            dataCell   = new PaCell(ptData, dataCellPath, false);

            var directSerialFlow = (ISerialFlow)directCell;
            var dataSerialFlow   = (ISerialFlow)dataCell;

            directSerialFlow.StartSerialFlow();
            dataSerialFlow.StartSerialFlow();
            directSerialFlow.S();
            dataSerialFlow.S();
            ReaderRDF.ReaderRDF.ReadFiles(tripletsCountLimit, filesPaths, (id, property, value, isObj, lang) =>
            {
                if (isObj)
                {
                    directSerialFlow.V(new object[] { id, property, value });
                }
                else
                {
                    dataSerialFlow.V(new object[] { id, property, value, lang ?? "" });
                }
            });
            directSerialFlow.Se();
            dataSerialFlow.Se();
            directSerialFlow.EndSerialFlow();
            dataSerialFlow.EndSerialFlow();
        }
Beispiel #4
0
 public void Close()
 {
     FlushPool();
     n_index.Close();
     c_index.Close();
     nc_cell.Close();
 }
Beispiel #5
0
 public void Close()
 {
     nc_cell.Close();
     c_index.Close();
     md5_index.Close();
     openMode = null;
 }
Beispiel #6
0
        public void Close()
        {
            encodedCell.Close();
            c_index.Close();

            openMode = null;
        }
Beispiel #7
0
 public void ConstructGroupedEntities(DiapLinksScanner[] scanners)
 {
     getable.Clear();
     getable.Fill(new object[0]);
     //foreach (var scanner in scanners) scanner.Start();
     while (scanners.Any(dls => dls.HasValue))
     {
         int         key       = scanners.Where(dls => dls.HasValue).Select(dls => dls.KeyCurrent).Min(); //Least(scanners);
         DiapLinks[] diaplinks = new DiapLinks[3];
         object[]    pval      = new object[4];
         pval[0] = key;
         for (int ind = 0; ind < 3; ind++)
         {
             DiapLinks di;
             if (scanners[ind].HasValue && scanners[ind].KeyCurrent == key)
             {
                 di             = scanners[ind].Scan();
                 diaplinks[ind] = di;
             }
             else
             {
                 di = new DiapLinks();
             }
             pval[ind + 1] = di.ToPObject(); //diaplinks[ind].ToPObject();
         }
         getable.Root.AppendElement(pval);
     }
     getable.Close();
 }
Beispiel #8
0
 private void Close()
 {
     // LiteralStore.Literals.dataCell.Close();
     dtriples_sp.Close();
     otriples.Close();
     otriples_op.Close();
     Scale.Cell.Close();
 }
Beispiel #9
0
        //START_SOURCE_CODE
        public void Run()
        {
            Console.WriteLine("Start Task03_PolarDB");
            dbpath = System.IO.Path.GetTempPath();
            PType  tp   = new PType(PTypeEnumeration.sstring);
            PaCell cell = new PaCell(tp, dbpath + "test.pac", false);

            cell.Clear();
            cell.Fill("Привет из ячейки базы данных!");
            Console.WriteLine("Содержимое ячейки: {0}", cell.Root.Get());

            PType tp_rec = new PTypeRecord(
                new NamedType("имя", new PType(PTypeEnumeration.sstring)),
                new NamedType("возраст", new PType(PTypeEnumeration.integer)),
                new NamedType("мужчина", new PType(PTypeEnumeration.boolean)));
            object rec_value = new object[] { "Пупкин", 22, true };
            PaCell cell_rec  = new PaCell(tp_rec, dbpath + "test_rec.pac", false);

            cell_rec.Clear();
            cell_rec.Fill(rec_value);
            object from_rec = cell_rec.Root.Get();

            Console.WriteLine(tp_rec.Interpret(from_rec));

            PType  tp_seq    = new PTypeSequence(tp_rec);
            object seq_value = new object[]
            {
                new object[] { "Иванов", 24, true },
                new object[] { "Петрова", 18, false },
                new object[] { "Пупкин", 22, true }
            };
            PaCell cell_seq = new PaCell(tp_seq, dbpath + "test_seq.pac", false);

            cell_seq.Clear();
            cell_seq.Fill(seq_value);
            object from_seq = cell_seq.Root.Get();

            Console.WriteLine(tp_seq.Interpret(from_seq));

            cell_seq.Root.AppendElement(new object[] { "Сидоров", 23, true });
            Console.WriteLine(tp_seq.Interpret(cell_seq.Root.Get()));

            long v0 = cell_seq.Root.Count();
            var  v1 = cell_seq.Root.Element(2).Field(0).Get();
            var  v2 = cell_seq.Root.Element(3).Field(1).Get();

            Console.WriteLine($"{v0} {v1} {v2}");

            cell_seq.Root.Element(1).Field(1).Set(19);
            cell_seq.Root.Element(1).Field(2).Set(true);
            Console.WriteLine(tp_seq.Interpret(cell_seq.Root.Get()));
            cell_seq.Flush();
            cell_seq.Close();
            cell_rec.Flush();
            cell_rec.Close();
            cell.Flush();
            cell.Close();
        }
Beispiel #10
0
        private void Close()
        {
            // LiteralStore.Literals.dataCell.Close();

            objPredicates.Close();
            objects.Close();
            inversePredicates.Close();
            inverses.Close();
            dataPredicates.Close();
            data.Close();
        }
Beispiel #11
0
        static void SimpleTreeInt(string path)
        {
            int pointsCount = 2, pointsDistance = 1000000;

            int[][] results = { new int[pointsCount], new int[pointsCount], new int[pointsCount] };
            for (int i = 1, j = 0; j < pointsCount; i += pointsDistance, j++)
            {
                if (File.Exists(path + "simple int.pac"))
                {
                    File.Delete(path + "simple int.pac");
                }
                if (File.Exists(path + "simple int tree.pxc"))
                {
                    File.Delete(path + "simple int tree.pxc");
                }
                if (File.Exists(path + "simple int tree add.pxc"))
                {
                    File.Delete(path + "simple int tree add.pxc");
                }

                Thread.Sleep(1);
                var       objects = Enumerable.Range(0, i).Cast <object>().ToArray();
                Stopwatch timer   = new Stopwatch();
                var       ints    = objects.Cast <int>();
                timer.Start();
                var simpleIntCell = new BTreeInt(new PType(PTypeEnumeration.integer),
                                                 path + "simple int tree.pxc", false);
                simpleIntCell.Fill(ints, false);
                //objects.ToBTree(new PType(PTypeEnumeration.integer), path + "simple int tree.pxc",
                //(o, entry) => (int) o - (int) entry.Get(), o => o, false);
                timer.Stop();
                results[0][j] = (int)timer.Elapsed.Ticks;
                Console.WriteLine("simple int tree " + i + "elements created for (ms)" + timer.Elapsed.TotalMilliseconds);
                timer.Restart();
                PaCell paCell = new PaCell(new PTypeSequence(new PType(PTypeEnumeration.integer)),
                                           path + "simple int.pac", false);
                paCell.Fill(objects);
                timer.Stop();
                results[1][j] = (int)timer.Elapsed.Ticks;
                Console.WriteLine("simple int pa " + i + "elements created for (ms)" + timer.Elapsed.TotalMilliseconds);

                // линейное возрастание времени
                // AddTreeAddChart(path, timer, objects, results, j);
                Console.WriteLine();
                TestGetByKey(simpleIntCell, i, paCell);
                Console.WriteLine();
                paCell.Close();
                simpleIntCell.Close();
            }
        }
Beispiel #12
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();
        }
Beispiel #13
0
        private void RemoveColumns(PaCell otriples, PaCell otriples_op, PaCell dtriples_sp)
        {
            objPredicates.Clear();
            objects.Clear();
            inversePredicates.Clear();
            inverses.Clear();
            dataPredicates.Clear();
            data.Clear();


            objPredicates.Fill(new object[0]);
            objects.Fill(new object[0]);
            inversePredicates.Fill(new object[0]);
            inverses.Fill(new object[0]);
            dataPredicates.Fill(new object[0]);
            data.Fill(new object[0]);



            foreach (object[] elementValue in otriples_op.Root.ElementValues())
            {
                inversePredicates.Root.AppendElement(elementValue[1]);
                inverses.Root.AppendElement(elementValue[0]);
            }
            foreach (object[] elementValue in otriples.Root.ElementValues())
            {
                objPredicates.Root.AppendElement(elementValue[1]);
                objects.Root.AppendElement(elementValue[2]);
            }
            foreach (object[] elementValue in dtriples_sp.Root.ElementValues())
            {
                dataPredicates.Root.AppendElement(elementValue[1]);
                data.Root.AppendElement(elementValue[2]);
            }
            objPredicates.Flush();
            objects.Flush();
            inversePredicates.Flush();
            inverses.Flush();
            dataPredicates.Flush();
            data.Flush();

            otriples.Close();
            otriples_op.Close();
            dtriples_sp.Close();
            File.Delete(otriplets_op_filePath + "tmp");
            File.Delete(otriples_filePath + "tmp");
            File.Delete(dtriples_filePath + "tmp");
        }
Beispiel #14
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");
 }
Beispiel #15
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();
        }
Beispiel #16
0
        private void RemoveColumns()
        {
            otriples    = new PaCell(tp_triple_seq_two, otriples_filePath, false);
            otriples_op = new PaCell(tp_triple_seq_two, otriplets_op_filePath, false);
            dtriples_sp = new PaCell(tp_dtriple_spf_two, dtriples_filePath, false);
            otriples.Clear();
            otriples_op.Clear();
            dtriples_sp.Clear();
            otriples.Fill(new object[0]);
            dtriples_sp.Fill(new object[0]);
            otriples_op.Fill(new object[0]);

            var otriples_tmp    = new PaCell(tp_otriple_seq, otriples_filePath + "tmp");
            var otriples_op_tmp = new PaCell(tp_otriple_seq, otriplets_op_filePath + "tmp");
            var dtriples_sp_tmp = new PaCell(tp_dtriple_spf, dtriples_filePath + "tmp");

            foreach (object[] elementValue in otriples_tmp.Root.ElementValues())
            {
                otriples.Root.AppendElement(new[] { elementValue[1], elementValue[2] });
            }
            foreach (object[] elementValue in otriples_op_tmp.Root.ElementValues())
            {
                otriples_op.Root.AppendElement(new[] { elementValue[1], elementValue[0] });
            }
            foreach (object[] elementValue in dtriples_sp_tmp.Root.ElementValues())
            {
                dtriples_sp.Root.AppendElement(new[] { elementValue[1], elementValue[2] });
            }

            otriples_tmp.Close();
            otriples_op_tmp.Close();
            dtriples_sp_tmp.Close();
            File.Delete(otriplets_op_filePath + "tmp");
            File.Delete(otriples_filePath + "tmp");
            File.Delete(dtriples_filePath + "tmp");

            otriples.Close();
            otriples_op.Close();
            dtriples_sp.Close();
        }
Beispiel #17
0
 public StringIntCoding(string path)
 {
     originalCell = path + "original_nt.pac";
     sourceCell   = path + "source_nt.pac";
     niCell       = path + "n_index.pac";
     ciCell       = path + "c_index.pac";
     // Создание ячеек, предполагается, что все либо есть либо их нет и надо создавать
     if (!System.IO.File.Exists(originalCell))
     {
         nc_cell = new PaCell(tp_nc, originalCell, false);
         nc_cell.Fill(new object[0]);
         nc_cell.Close();
         n_index = new PaCell(tp_ind, niCell, false);
         n_index.Fill(new object[0]);
         n_index.Close();
         c_index = new PaCell(tp_ind, ciCell, false);
         c_index.Fill(new object[0]);
         c_index.Close();
     }
     // Открытие ячеек в режиме работы (чтения)
     Open(true);
 }
Beispiel #18
0
        public static void Main(string[] args)
        {
            string path = @"..\..\..\Databases\";

            Console.WriteLine("Start test. Wait appoximately 10 sec. ");
            DateTime tt0 = DateTime.Now;
            // Тестовый тип данных
            PType tp_int     = new PType(PTypeEnumeration.integer);
            PType tp_seq_int = new PTypeSequence(new PType(PTypeEnumeration.integer));
            PType tp_seq_seq = new PTypeSequence(new PTypeSequence(new PType(PTypeEnumeration.integer)));

            // Тестирование буфера. Новый релиз 20130929
            GenerateSerialTestFlow(10, new SerialBuffer(new SerialFlowReceiverConsole(tp_seq_seq), 0));


            return;


            PaCell cell = new PaCell(tp_seq_seq, path + "serbuftest.pac", false);

            cell.Clear();

            ISerialFlow input;

            input = cell; // Ввод без буфера
            GenerateSerialTestFlow(900000, input);
            Console.WriteLine("======Fill without buffer ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            cell.Clear();
            input = new SerialBuffer(cell, 4); // Ввод с буфером
            GenerateSerialTestFlow(900000, input);
            Console.WriteLine("======Fill with buffer ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            cell.Close();
            //System.IO.File.Delete(path + "serbuftest.pac");
        }
Beispiel #19
0
        // =========== Ключевой фрагмент ============
        public Dictionary <string, int> InsertPortion(IEnumerable <string> s_flow)
        {
            HashSet <string> hs = new HashSet <string>();

            foreach (string s in s_flow)
            {
                hs.Add(s);
            }

            //string[] ssa = hs.OrderBy(s => new HashedString() { Str = s }).ToArray(); // Надо сделать более экономно
            string[] ssa = hs.Select(s => new { st = s, hs = new HashedString()
                                                {
                                                    Str = s
                                                } })
                           .OrderBy(pa => pa.hs)
                           .Select(pa => pa.st).ToArray();

            if (ssa.Length == 0)
            {
                return(new Dictionary <string, int>());
            }

            //s_index_array.IndexCell.Close(); // cssequence.Close();
            // Подготовим основную ячейку для работы
            if (System.IO.File.Exists(path + "tmp.pac"))
            {
                System.IO.File.Delete(path + "tmp.pac");
            }
            //System.IO.File.Copy(s_index_array_path + ".pac", path + "tmp.pac");

            // Это по общей логике, но если снаружи изменится, надо изменить и тут
            PType tp_s_index_seq = new PTypeSequence(new PTypeRecord(
                                                         new NamedType("halfkey", new PType(PTypeEnumeration.integer)),
                                                         new NamedType("offset", new PType(PTypeEnumeration.longinteger))));
            PaCell source = new PaCell(tp_s_index_seq, path + "tmp.pac", false);

            source.Fill(new object[0]);
            foreach (var v in s_index_array.IndexCell.Root.ElementValues())
            {
                source.Root.AppendElement(v);
            }
            source.Flush();
            PaCell target = s_index_array.IndexCell;

            target.Clear();
            target.Fill(new object[0]);

            int    ssa_ind      = 0;
            bool   ssa_notempty = true;
            string ssa_current  = ssa_notempty ? ssa[ssa_ind] : null;

            ssa_ind++;

            // Для накопления пар
            List <KeyValuePair <string, int> > accumulator = new List <KeyValuePair <string, int> >(ssa.Length);

            // Очередной (новый) код (индекс)
            int code_new = 0;

            if (!source.IsEmpty && source.Root.Count() > 0)
            {
                code_new = (int)source.Root.Count();
                PaEntry tab_entry = table.Element(0); // не было проверки на наличие хотя бы одного элемента
                // Сканируем индексный массив, элементы являются парами {halfkey, offset}
                foreach (object[] val in source.Root.ElementValues())
                {
                    // Пропускаю элементы из нового потока, которые меньше текущего сканированного элемента
                    int    halfkey = (int)val[0];
                    string s       = null; // Будет запрос если понадобится
                    int    cmp     = 0;
                    while (ssa_notempty)   //  && (cmp = ssa_current.CompareTo(s)) <= 0
                    {
                        int hash_current = ssa_current.GetHashCode();
                        cmp = hash_current.CompareTo(halfkey);
                        if (cmp == 0)
                        { // Дополнительное упрядочивание по строке
                            if (s == null)
                            {
                                tab_entry.offset = (long)val[1];
                                s = (string)tab_entry.Field(1).Field(1).Get();
                            }
                            cmp = ssa_current.CompareTo(s);
                        }
                        if (cmp < 0)
                        { // добавляется новый код
                            // добавляем код в таблицу
                            long offset = table.TableCell.Root.AppendElement(new object[] { false, new object[] { code_new, ssa_current } });
                            // Автоматом добавляем начало строки в offsets
                            offset_array.IndexCell.Root.AppendElement(offset);
                            // добавляем строчку в строковый индекс
                            target.Root.AppendElement(new object[] { hash_current, offset });
                            accumulator.Add(new KeyValuePair <string, int>(ssa_current, code_new));
                            code_new++;
                        }
                        else if (cmp == 0)
                        { // используется существующий код
                            tab_entry.offset = (long)val[1];
                            object[] ob   = (object[])tab_entry.Get();
                            object[] rec  = (object[])ob[1];
                            int      code = (int)rec[0];
                            string   key  = (string)rec[1];
                            accumulator.Add(new KeyValuePair <string, int>(key, code));
                        }
                        else // if (cmp > 0)
                        {
                            break; // Нужно дойти до него на следующем элементе в следующем цикле
                        }
                        if (ssa_ind < ssa.Length)
                        {
                            ssa_current = ssa[ssa_ind++]; //ssa.ElementAt<string>(ssa_ind);
                        }
                        else
                        {
                            ssa_notempty = false;
                        }
                    }
                    target.Root.AppendElement(val); // переписывается тот же объект
                }
            }
            // В массиве ssa могут остаться элементы, их надо просто добавить
            if (ssa_notempty)
            {
                do
                {
                    // добавляем код в таблицу
                    long offset = table.TableCell.Root.AppendElement(new object[] { false, new object[] { code_new, ssa_current } });
                    // Автоматом добавляем начало строки в offsets
                    offset_array.IndexCell.Root.AppendElement(offset);
                    // добавляем строчку в строковый индекс
                    target.Root.AppendElement(new object[] { ssa_current.GetHashCode(), offset });
                    accumulator.Add(new KeyValuePair <string, int>(ssa_current, code_new));
                    code_new++;
                    if (ssa_ind < ssa.Length)
                    {
                        ssa_current = ssa[ssa_ind];
                    }
                    ssa_ind++;
                }while (ssa_ind <= ssa.Length);
            }

            table.TableCell.Flush();
            offset_array.IndexCell.Flush();
            target.Flush();

            source.Close();
            System.IO.File.Delete(path + "tmp.pac");

            // Финальный аккорд: формирование и выдача словаря
            Dictionary <string, int> dic = new Dictionary <string, int>();

            foreach (var keyValuePair in accumulator.Where(keyValuePair => !dic.ContainsKey(keyValuePair.Key)))
            {
                dic.Add(keyValuePair.Key, keyValuePair.Value);
            }

            return(dic);
        }
Beispiel #20
0
        public Dictionary <string, int> InsertPortion(HashSet <string> portion)
        {
            Open(false);
            List <long> ofsets2NC    = new List <long>(portion.Count);
            List <long> checkSumList = new List <long>(portion.Count);

            foreach (var q in nc_cell.Root.ElementValues())
            {
                ;                                             //14гб
            }
            foreach (var q in md5_index.Root.ElementValues())
            {
                ;
            }
            var insertPortion = new Dictionary <string, int>(portion.Count);

            foreach (var name in portion)
            {
                var checkSum = BitConverter.ToInt64(md5.ComputeHash(Encoding.UTF8.GetBytes(name)), 0);
                var code     = GetCode(name, checkSum);
                if (code == Int32.MinValue)
                {
                    checkSumList.Add(checkSum);
                    ofsets2NC.Add(nc_cell.Root.AppendElement(new object[] { code = Count++, name }));
                }

                insertPortion.Add(name, code);
            }
            nc_cell.Flush();

            var offsetsNC = ofsets2NC.ToArray();
            var checkSums = checkSumList.ToArray();

            Array.Sort(checkSums, offsetsNC);
            int portionIndex = 0;

            if (md5_index.Root.Count() > 0)
            {
                Close();
                string tmp = pathMD5Index + ".tmp";
                if (File.Exists(tmp))
                {
                    File.Delete(tmp);
                }

                File.Move(pathMD5Index, tmp);
                Open(false);
                md5_index.Clear();
                md5_index.Fill(new object[0]);
                var tmpCell = new PaCell(tp_pair_longs, tmp);

                foreach (object[] existingPair in tmpCell.Root.ElementValues())
                {
                    for (;
                         portionIndex < offsetsNC.Length &&
                         checkSums[portionIndex] <= (long)existingPair[0];
                         portionIndex++)
                    {
                        md5_index.Root.AppendElement(new object[] { checkSums[portionIndex], offsetsNC[portionIndex] });
                    }
                    md5_index.Root.AppendElement(existingPair);
                }
                tmpCell.Close();
                File.Delete(tmp);
            }
            for (; portionIndex < checkSums.Length; portionIndex++)
            {
                md5_index.Root.AppendElement(new object[] { checkSums[portionIndex], offsetsNC[portionIndex] });
            }

            md5_index.Flush();


            //Count += insertPortion.Count;
            return(insertPortion);
        }
Beispiel #21
0
        public static void Main1(string[] args)
        {
            string path         = @"..\..\..\Databases\";
            PType  seq          = new PTypeSequence(new PType(PTypeEnumeration.sstring));
            string originalCell = path + "original_nt.pac";
            string tmpCell      = path + "tmp_nt.pac";
            string sourceCell   = path + "source_nt.pac";

            Console.WriteLine("Start");
            PaCell   cell = new PaCell(seq, originalCell, false);
            DateTime tt0  = DateTime.Now;

            List <string> namePool = new List <string>(100000);

            for (int i = 0; i < 100000; i++)
            {
                namePool.Add(Guid.NewGuid().ToString());
            }
            SortedSet <string> ss = new SortedSet <string>(namePool); //var q = ss.ElementAt<string>(10);

            string[] ssa = ss.ToArray();
            Console.WriteLine("ssa.Count=" + ssa.Count());
            // Буду проводить слияние

            cell.Close();
            System.IO.File.Move(originalCell, sourceCell);
            if (!System.IO.File.Exists(tmpCell))
            {
                PaCell tmp = new PaCell(seq, tmpCell, false);
                tmp.Fill(new object[0]);
                tmp.Close();
            }
            System.IO.File.Move(tmpCell, originalCell);
            PaCell source = new PaCell(seq, sourceCell);
            PaCell target = new PaCell(seq, originalCell, false);

            if (!target.IsEmpty)
            {
                target.Clear();
            }
            target.Fill(new object[0]);

            int    ssa_ind      = 0;
            bool   ssa_notempty = ssa_ind < ssa.Count() ? true : false; //ssa_notempty = false;
            string ssa_current  = ssa_notempty ? ssa[ssa_ind] : null;

            ssa_ind++;

            long nn = source.Root.Count();

            Console.WriteLine("длина последовательности: " + nn);
            foreach (var val in source.Root.ElementValues())
            {
                // Пропускаю элементы из нового потока, которые меньше текущего сканированного элемента
                string s   = (string)val;
                int    cmp = 0;
                while (ssa_notempty && (cmp = ssa_current.CompareTo(s)) <= 0)
                {
                    if (cmp < 0)
                    {
                        target.Root.AppendElement(ssa_current);          // При равенстве, новый элемент игнорируется
                    }
                    if (ssa_ind < ssa.Count())
                    {
                        ssa_current = ssa[ssa_ind]; //ssa.ElementAt<string>(ssa_ind);
                        ssa_ind++;
                    }
                    else
                    {
                        ssa_notempty = false;
                    }
                }
                target.Root.AppendElement(s);
            }
            target.Close();
            source.Close();
            System.IO.File.Move(sourceCell, tmpCell);



            Console.WriteLine("duration=" + (DateTime.Now - tt0).Ticks / 10000L);
        }
Beispiel #22
0
 public void Close()
 {
     index_cell.Close();
 }
Beispiel #23
0
 public void Close()
 {
     this.Flush();
     index.Close();
 }
Beispiel #24
0
        public void Build()
        {
            DateTime tt0 = DateTime.Now;

            otriples.Flush();
            dtriples.Flush();
            otriples.Close();

            // Копирование файла
            if (System.IO.File.Exists(path + "otriples_op.pac"))
            {
                System.IO.File.Delete(path + "otriples_op.pac");
            }
            System.IO.File.Copy(path + "otriples.pac", path + "otriples_op.pac");
            otriples = new PaCell(tp_otriple_seq, path + "otriples.pac", false);
            PaCell otriples_op = new PaCell(tp_otriple_seq, path + "otriples_op.pac", false);

            //otriples_op.Clear(); otriples_op.Fill(new object[0]); // Другой вариант - покомпонентная перепись
            //otriples.Root.Scan((off, pobj) =>
            //{
            //    otriples_op.Root.AppendElement(pobj);
            //    return true;
            //});
            //otriples_op.Flush();

            //PaCell dtriples_sp = new PaCell(tp_dtriple_spf, path + "dtriples_spf.pac", false);
            //dtriples_sp.Clear(); dtriples_sp.Fill(new object[0]);
            //dtriples.Root.Scan((off, pobj) =>
            //{
            //    object[] tri = (object[])pobj;
            //    int s = (int)tri[0];
            //    int p = (int)tri[1];
            //    dtriples_sp.Root.AppendElement(new object[] { s, p, off });
            //    return true;
            //});
            //dtriples_sp.Flush();
            Console.WriteLine("Additional files ok. duration={0}", (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // Сортировки
            // Упорядочивание otriples по s-p-o
            SPOComparer spo_compare = new SPOComparer();

            otriples.Root.SortByKey <SubjPredObjInt>(rec => new SubjPredObjInt(rec), spo_compare);
            Console.WriteLine("otriples.Root.Sort ok. Duration={0} msec.", (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            SPComparer sp_compare = new SPComparer();

            // Упорядочивание otriples_op по o-p
            otriples_op.Root.SortByKey <SubjPredInt>(rec =>
            {
                object[] r = (object[])rec;
                return(new SubjPredInt()
                {
                    pred = (int)r[1], subj = (int)r[2]
                });
            }, sp_compare);
            Console.WriteLine("otriples_op Sort ok. Duration={0} msec.", (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // Упорядочивание dtriples_sp по s-p
            dtriples.Root.SortByKey(rec =>
            {
                object[] r = (object[])rec;
                return(new SubjPredInt()
                {
                    pred = (int)r[1], subj = (int)r[0]
                });
            }, sp_compare);
            Console.WriteLine("dtriples_sp.Root.Sort ok. Duration={0} msec.", (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;
            scale.WriteScale(otriples);
            Console.WriteLine("CreateScale ok. Duration={0} sec.", (DateTime.Now - tt0).Ticks / 10000000L); tt0 = DateTime.Now;
            //int cnt_e = MakeTreeFree(otriples, otriples_op, dtriples_sp);
            //Console.WriteLine("Scan3 ok. Duration={0} msec. cnt_e={1} ", (DateTime.Now - tt0).Ticks / 10000L, cnt_e); tt0 = DateTime.Now;
            //Console.WriteLine("otriples={0} otriples_op={1} dtriples_sp={2}", otriples.Root.Count(), otriples_op.Root.Count(), dtriples_sp.Root.Count());

            otriples.Close();
            otriples_op.Close();
            dtriples.Close();
            // Создает ячейку фиксированного формата tree_fix.pxc
            MakeTreeFix();
            dataCell.Flush();
            namespaceMaper.coding.MakeIndexed();
        }
Beispiel #25
0
        public void Close()
        {
            nc_cell.Close();

            openMode = null;
        }
Beispiel #26
0
        public Dictionary <string, int> InsertPortion(string[] sorted_arr) //(IEnumerable<string> portion)
        {
            Open(false);
            //DateTime tt0 = DateTime.Now;
            string[] ssa = sorted_arr;
            Array.Sort(ssa);
            if (ssa.Length == 0)
            {
                return(new Dictionary <string, int>());
            }

            this.Close();
            // Подготовим основную ячейку для работы
            if (System.IO.File.Exists(sourceCell))
            {
                System.IO.File.Delete(sourceCell);
            }
            System.IO.File.Move(originalCell, sourceCell);
            //if (!System.IO.File.Exists(tmpCell))
            //{
            //    PaCell tmp = new PaCell(tp_nc, tmpCell, false);
            //    tmp.Fill(new object[0]);
            //    tmp.Close();
            //}
            //System.IO.File.Move(tmpCell, originalCell);

            PaCell source = new PaCell(tp_nc, sourceCell);
            PaCell target = new PaCell(tp_nc, originalCell, false);

            //if (!target.IsEmpty) target.Clear();
            target.Fill(new object[0]);

            int    ssa_ind      = 0;
            bool   ssa_notempty = true;
            string ssa_current  = ssa_notempty ? ssa[ssa_ind] : null;

            ssa_ind++;

            // Для накопления пар
            List <KeyValuePair <string, int> > accumulator = new List <KeyValuePair <string, int> >(ssa.Length);

            // Очередной (новый) код (индекс)
            int code_new = 0;

            if (!source.IsEmpty)
            {
                code_new = (int)source.Root.Count();
                foreach (object[] val in source.Root.ElementValues())
                {
                    // Пропускаю элементы из нового потока, которые меньше текущего сканированного элемента
                    string s   = (string)val[1];
                    int    cmp = 0;
                    while (ssa_notempty && (cmp = ssa_current.CompareTo(s)) <= 0)
                    {
                        if (cmp < 0)
                        { // добавляется новый код
                            object[] v = new object[] { code_new, ssa_current };
                            target.Root.AppendElement(v);
                            code_new++;
                            accumulator.Add(new KeyValuePair <string, int>((string)v[1], (int)v[0]));
                        }
                        else
                        { // используется существующий код
                            accumulator.Add(new KeyValuePair <string, int>((string)val[1], (int)val[0]));
                        }
                        if (ssa_ind < ssa.Length)
                        {
                            ssa_current = ssa[ssa_ind++]; //ssa.ElementAt<string>(ssa_ind);
                        }
                        else
                        {
                            ssa_notempty = false;
                        }
                    }
                    target.Root.AppendElement(val); // переписывается тот же объект
                }
            }
            // В массиве ssa могут остаться элементы, их надо просто добавить
            if (ssa_notempty)
            {
                do
                {
                    object[] v = new object[] { code_new, ssa_current };
                    target.Root.AppendElement(v);
                    code_new++;
                    accumulator.Add(new KeyValuePair <string, int>((string)v[1], (int)v[0]));
                    if (ssa_ind < ssa.Length)
                    {
                        ssa_current = ssa[ssa_ind];
                    }
                    ssa_ind++;
                }while (ssa_ind <= ssa.Length);
            }

            target.Close();
            source.Close();
            System.IO.File.Delete(sourceCell);
            this.Open(true); // парный к this.Close() оператор
            // Финальный аккорд: формирование и выдача словаря
            Dictionary <string, int> dic = new Dictionary <string, int>();

            foreach (var keyValuePair in accumulator.Where(keyValuePair => !dic.ContainsKey(keyValuePair.Key)))
            {
                dic.Add(keyValuePair.Key, keyValuePair.Value);
            }
            //Console.WriteLine("Слияние ok (" + ssa.Length + "). duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;
            return(dic);
        }
Beispiel #27
0
        public void Load(int tripletsCountLimit, params string[] filesPaths)
        {
            directCell.Close();
            dataCell.Close();
            predDataCell.Close();
            predObjell.Close();
            idCell.Close();
            textCell.Close();

            File.Delete(dataCellPath);
            File.Delete(directCellPath);
            File.Delete(predDataCellPath);
            File.Delete(predObjellPath);
            File.Delete(idCellPath);
            File.Delete(textCellPath);

            directCell   = new PaCell(ptDirects, directCellPath, false);
            dataCell     = new PaCell(ptData, dataCellPath, false);
            predDataCell = new PaCell(ptHashValue, predDataCellPath, false);
            predObjell   = new PaCell(ptHashValue, predObjellPath, false);
            idCell       = new PaCell(new PTypeSequence(new PTypeRecord(new NamedType("hash", new PType(PTypeEnumeration.integer)), new NamedType("id", new PTypeFString(20)))), idCellPath, false);
            textCell     = new PaCell(ptHashValue, textCellPath, false);

            var directSerialFlow   = (ISerialFlow)directCell;
            var dataSerialFlow     = (ISerialFlow)dataCell;
            var idSerialFlow       = (ISerialFlow)idCell;
            var predObjSerialFlow  = (ISerialFlow)predObjell;
            var predDataSerialFlow = (ISerialFlow)predDataCell;
            var textSerialFlow     = (ISerialFlow)textCell;

            directSerialFlow.StartSerialFlow();
            dataSerialFlow.StartSerialFlow();
            idSerialFlow.StartSerialFlow();
            predObjSerialFlow.StartSerialFlow();
            predDataSerialFlow.StartSerialFlow();
            textSerialFlow.StartSerialFlow();
            directSerialFlow.S();
            dataSerialFlow.S();
            idSerialFlow.S();
            textSerialFlow.S();
            predObjSerialFlow.S();
            predDataSerialFlow.S();
            var existsId        = new HashSet <int>(); // ArrayIntMax<bool>();
            var existsText      = new HashSet <int>(); // = new ArrayIntMax<bool>();
            var existsPredicate = new HashSet <int>(); // = new ArrayIntMax<bool>();

            ReaderRDF.ReaderRDF.ReadFiles(tripletsCountLimit, filesPaths,
                                          (id, property, value, isObj, lang) =>
            {
                int hashId = id.GetHashCode();
                if (!existsId.Contains(hashId))
                {
                    idSerialFlow.V(new object[] { hashId, id });
                    existsId.Add(hashId);
                }
                int hProperty = property.GetHashCode();
                if (isObj)
                {
                    if (!existsPredicate.Contains(hProperty))
                    {
                        predObjSerialFlow.V(new object[] { hProperty, property });
                        existsPredicate.Add(hProperty);
                    }
                    var objHash = value.GetHashCode();
                    directSerialFlow.V(new object[] { hashId, hProperty, objHash });
                    if (!existsId.Contains(objHash))
                    {
                        existsId.Add(objHash);
                        idSerialFlow.V(new object[] { objHash, value });
                    }
                }
                else
                {
                    if (!existsPredicate.Contains(hProperty))
                    {
                        predDataSerialFlow.V(new object[] { hProperty, property });
                        existsPredicate.Add(hProperty);
                    }
                    int hashText = value.GetHashCode();
                    if (!existsText.Contains(hashText))
                    {
                        textSerialFlow.V(new object[] { hashText, value });
                        existsText.Add(hashText);
                    }
                    dataSerialFlow.V(new object[] { hashId, hProperty, hashText, lang ?? "" });
                }
            });

            directSerialFlow.Se();
            dataSerialFlow.Se();
            idSerialFlow.Se();
            textSerialFlow.Se();
            predObjSerialFlow.Se();
            predDataSerialFlow.Se();
            directSerialFlow.EndSerialFlow();
            dataSerialFlow.EndSerialFlow();
            idSerialFlow.EndSerialFlow();
            textSerialFlow.EndSerialFlow();
            predObjSerialFlow.EndSerialFlow();
            predDataSerialFlow.EndSerialFlow();
        }
Beispiel #28
0
        public override void LoadTurtle(string filepath, bool useBuffer)
        {
            DateTime tt0 = DateTime.Now;

            Close();

            Open(false);

            PaCell otriples    = new PaCell(tp_otriple_seq, otriples_filePath, false);
            PaCell dtriples_sp = new PaCell(tp_dtriple_spf, dtriples_filePath, false);

            if (useBuffer)
            {
                TurtleInt.LoadByGraphsBuffer(filepath, otriples, dtriples_sp, this);
            }
            else
            {
                TurtleInt.LoadTriplets(filepath, otriples, dtriples_sp, this);
            }

            Console.WriteLine("Load ok. Duration={0} sec.", (DateTime.Now - tt0).Ticks / 10000000L); tt0 = DateTime.Now;

            if (File.Exists(otriplets_op_filePath))
            {
                File.Delete(otriplets_op_filePath);
            }
            otriples.Close();
            File.Copy(otriples_filePath, otriplets_op_filePath);
            PaCell otriples_op = new PaCell(tp_otriple_seq, otriplets_op_filePath, false);

            otriples = new PaCell(tp_otriple_seq, otriples_filePath, false);
            Console.WriteLine("copy objects ok. Duration={0} sec.", (DateTime.Now - tt0).Ticks / 10000000L); tt0 = DateTime.Now;

            // Упорядочивание otriples по s-p-o
            otriples.Root.SortByKey(rec => new SubjPredObjInt(rec), new SPOComparer());
            Console.WriteLine("otriples.Root.Sort ok. Duration={0} sec.", (DateTime.Now - tt0).Ticks / 10000000L); tt0 = DateTime.Now;

            //SPOComparer spo_compare = new SPOComparer();
            SPComparer sp_compare = new SPComparer();

            // Упорядочивание otriples_op по o-p
            otriples_op.Root.SortByKey(rec =>
            {
                object[] r = (object[])rec;
                return(new SubjPredInt()
                {
                    pred = (int)r[1], subj = (int)r[2]
                });
            }, sp_compare);
            Console.WriteLine("otriples_op Sort ok. Duration={0} sec.", (DateTime.Now - tt0).Ticks / 10000000L); tt0 = DateTime.Now;

            // Упорядочивание dtriples_sp по s-p
            dtriples_sp.Root.SortByKey(rec =>
            {
                object[] r = (object[])rec;
                return(new SubjPredInt()
                {
                    pred = (int)r[1], subj = (int)r[0]
                });
            }, sp_compare);
            Console.WriteLine("dtriples_sp.Root.Sort ok. Duration={0} sec.", (DateTime.Now - tt0).Ticks / 10000000L); tt0 = DateTime.Now;

            Scale.WriteScale(otriples);
            Console.WriteLine("CreateScale ok. Duration={0} sec.", (DateTime.Now - tt0).Ticks / 10000000L); tt0 = DateTime.Now;


            // Создание "широкой" таблицы
            ewt.Load(new[]
            {
                new DiapasonScanner <int>(otriples, ent => (int)((object[])ent.Get())[0]),
                new DiapasonScanner <int>(otriples_op, ent => (int)((object[])ent.Get())[2]),
                new DiapasonScanner <int>(dtriples_sp, ent => (int)((object[])ent.Get())[0])
            });
            Console.WriteLine("ewt.Load() ok. Duration={0} sec.", (DateTime.Now - tt0).Ticks / 10000000L); tt0 = DateTime.Now;

            // Вычисление кеша. Это можно не делать, все равно - кеш в оперативной памяти
            //ewtHash.Load();
            // Console.WriteLine("ewtHash.Load() ok. Duration={0} sec.", (DateTime.Now - tt0).Ticks / 10000000L); tt0 = DateTime.Now;


            RemoveColumns(otriples, otriples_op, dtriples_sp);
            Console.WriteLine("RemoveColumns() ok. Duration={0} sec.", (DateTime.Now - tt0).Ticks / 10000000L); tt0 = DateTime.Now;
        }
Beispiel #29
0
        public void Build()
        {
            DateTime tt0 = DateTime.Now;

            otriples.Flush();
            dtriples.Flush();
            literals.Flush();
            // ======== Формирование вторичных ячеек ========
            PaCell otriples_op = new PaCell(tp_otriples, path + "otriples_op.pac", false);

            otriples_op.Clear(); otriples_op.Fill(new object[0]); // Другой вариант - копирование файла
            otriples.Root.Scan((off, pobj) =>
            {
                otriples_op.Root.AppendElement(pobj);
                return(true);
            });
            otriples_op.Flush();

            Console.WriteLine("Additional files ok. duration={0}", (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // ======= Сортировки =======
            // Упорядочивание otriples по s-p-o
            SPOComparer spo_compare = new SPOComparer();

            otriples.Root.SortByKey <SubjPredObjInt>(rec => new SubjPredObjInt(rec), spo_compare);
            Console.WriteLine("otriples.Root.Sort ok. Duration={0} msec.", (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            SPComparer sp_compare = new SPComparer();

            // Упорядочивание otriples_op по o-p
            otriples_op.Root.SortByKey <SubjPredInt>(rec =>
            {
                object[] r = (object[])rec;
                return(new SubjPredInt()
                {
                    pred = (int)r[1], subj = (int)r[2]
                });
            }, sp_compare);
            Console.WriteLine("otriples_op Sort ok. Duration={0} msec.", (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // Упорядочивание dtriples_sp по s-p
            dtriples.Root.SortByKey(rec =>
            {
                object[] r = (object[])rec;
                return(new SubjPredInt()
                {
                    pred = (int)r[1], subj = (int)r[0]
                });
            }, sp_compare);
            Console.WriteLine("dtriples.Root.Sort ok. Duration={0} msec.", (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // ==== Определение количества сущностей ====
            // Делаю три упрощенных сканера
            DiapasonScanner <int> i_fields  = new DiapasonScanner <int>(dtriples, ent => (int)((object[])ent.Get())[0]);
            DiapasonScanner <int> i_direct  = new DiapasonScanner <int>(otriples, ent => (int)((object[])ent.Get())[0]);
            DiapasonScanner <int> i_inverse = new DiapasonScanner <int>(otriples_op, ent => (int)((object[])ent.Get())[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, 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();

            // Заведем ячейку для результата сканирования
            tree_fix.Clear();
            tree_fix.Root.SetRepeat(n_entities);
            Console.WriteLine("tree_fix length={0}", tree_fix.Root.Count());
            long longindex = 0;

            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() };
                // Записываем в качестве элемента последовательности
                tree_fix.Root.Element(longindex).Set(record); longindex++;
            }
            tree_fix.Close();
            Console.WriteLine("tree_fix ok. Duration={0} msec.", (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;


            otriples.Close();
            otriples_op.Close();
            dtriples.Close();
            literals.Close();
        }
Beispiel #30
0
 public void Close()
 {
     offsetsCell.Close(); offsetsOnOffsetsCell.Close();
 }