Example #1
0
        public async Task <IActionResult> Edit(int id, [Bind("SampleId,BurialId,LocConcat,RackNum,BagNum,LowNs,HighNs,NS,LowEw,HighEw,EW,Area,BurialNum,SubBurialNum,ClusterNum,DateDay,DateMonth,DateYear,PreviouslySampled,Notes,Initials")] Samples2 samples2)
        {
            if (id != samples2.SampleId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                //Injects correctly made LocConcat
                samples2.LocConcat = ($"{samples2.NS} {samples2.LowNs} / {samples2.HighNs} {samples2.EW} {samples2.LowEw} / {samples2.HighEw} {samples2.Area} #{samples2.BurialNum}");

                try
                {
                    _context.Update(samples2);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!Samples2Exists(samples2.SampleId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["BurialId"] = new SelectList(_context.MasterBurial2, "BurialId", "BurialId", samples2.BurialId);
            return(View(samples2));
        }
Example #2
0
        public async Task <IActionResult> Create([Bind("SampleId,BurialId,LocConcat,RackNum,BagNum,LowNs,HighNs,NS,LowEw,HighEw,EW,Area,BurialNum,SubBurialNum,ClusterNum,DateDay,DateMonth,DateYear,PreviouslySampled,Notes,Initials")] Samples2 samples2)
        {
            if (ModelState.IsValid)
            {
                //Injects correctly made LocConcat
                samples2.LocConcat = ($"{samples2.NS} {samples2.LowNs} / {samples2.HighNs} {samples2.EW} {samples2.LowEw} / {samples2.HighEw} {samples2.Area} #{samples2.BurialNum}");



                //samples2.BurialId = ViewBag.Id;
                _context.Add(samples2);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["BurialId"] = new SelectList(_context.MasterBurial2, "BurialId", "BurialId", samples2.BurialId);
            return(View(samples2));
        }
Example #3
0
 public SamplePanorama(UINavigationController controller)
 {
     this.monokitSamples = new Samples2(controller);
 }
Example #4
0
 /// <summary>
 ///   Returns a <see cref="System.String"/> that represents this instance.
 /// </summary>
 ///
 /// <returns>
 ///   A <see cref="System.String"/> that represents this instance.
 /// </returns>
 ///
 public override string ToString(string format, IFormatProvider formatProvider)
 {
     return(String.Format(formatProvider, "MannWhitney(u; n1 = {0}, n2 = {1})",
                          Samples1.ToString(format, formatProvider),
                          Samples2.ToString(format, formatProvider)));
 }
Example #5
0
    static void Main(string[] args)
    {
        string dictionary_path     = @"e:\MVoice\lem\bin-windows\dictionary.xml"; // путь к словарной базе
        string samples_path        = @"E:\MVoice\lem\Слова\rus\SENT5.plain.txt";  // путь к файлу со списком предложений (одно предложение на одной строке)
        int    NSAMPLE             = 20000;                                       // сколько предложений максимум обработать
        int    START_INDEX         = 0;                                           // порядковый номер первого обрабатываемого предложений в исходном файле
        int    MAXARGS             = 20;                                          // beam size
        bool   append_result       = false;                                       // если леммы надо добавлять к существующему файлу, а не формировать файл с нуля
        string save_path           = null;                                        // путь к файлу, куда будут записаны леммы
        int    source_format       = 0;                                           // 0 - token per line, 1 - sentence per line
        bool   output_lemmas       = true;                                        // в результат записывать леммы с приведением к нижнему регистру
        bool   output_suffix       = false;
        bool   output_words        = false;                                       // в результат записывать исходные слова с приведением к нижнему регистру
        int    suffix_len          = 0;
        int    min_sentence_length = 0;                                           // фильтр по минимальной длине предложений
        int    max_sentence_length = int.MaxValue;                                // фильтр по максимальной длине предложений
        bool   reject_unknown      = false;                                       // отбрасывать предложения с несловарными токенами
        bool   emit_eol            = false;                                       // добавлять в выходной файл токены <EOL> для маркировки конца предложения
        int    eol_count           = 0;                                           // кол-во вставляемых <EOL>, гарантированно перекрывающее размер окна в word2vec

        List <System.Text.RegularExpressions.Regex> rx_stop = new List <System.Text.RegularExpressions.Regex>();

        for (int i = 0; i < args.Length; ++i)
        {
            if (args[i] == "-dict")
            {
                ++i;
                dictionary_path = args[i];
            }
            else if (args[i] == "-samples")
            {
                ++i;
                samples_path = args[i];
            }
            else if (args[i] == "-source_format")
            {
                ++i;
                source_format = int.Parse(args[i]);
            }
            else if (args[i] == "-append")
            {
                // Добавлять в конец существующего файла
                append_result = true;
            }
            else if (args[i] == "-emit_eol")
            {
                ++i;
                eol_count = int.Parse(args[i]);
                if (eol_count > 0)
                {
                    emit_eol = true;
                }
            }
            else if (args[i] == "-result")
            {
                // Способ обработки токенов:
                // lemma  => лемматизация
                // suffix => усечение до псевдосуффикса длиной -suffix_len
                // raw    => исходные слова
                ++i;
                output_lemmas = false;
                output_suffix = false;
                output_words  = false;

                if (args[i] == "suffix")
                {
                    output_suffix = true;
                }
                else if (args[i] == "lemma")
                {
                    output_lemmas = true;
                }
                else if (args[i] == "raw")
                {
                    output_words = true;
                }
                else
                {
                    throw new ApplicationException(string.Format("Unknown result format: {0}", args[i]));
                }
            }
            else if (args[i] == "-save")
            {
                // Путь к файлу, куда будут записываться результаты обработки
                ++i;
                save_path = args[i];
            }
            else if (args[i] == "-nsample")
            {
                // кол-во обрабатываемых предложений, начиная с -start_index
                ++i;
                NSAMPLE = int.Parse(args[i]);
            }
            else if (args[i] == "-min_sent_len")
            {
                // Обрабатывать только предложения, содержащие не менее NNN токенов
                ++i;
                min_sentence_length = int.Parse(args[i]);
            }
            else if (args[i] == "-max_sent_len")
            {
                // Обрабатывать только предложения, содержащие не более NNN токенов
                ++i;
                max_sentence_length = int.Parse(args[i]);
            }
            else if (args[i] == "-suffix_len")
            {
                ++i;
                suffix_len = int.Parse(args[i]);
            }
            else if (args[i] == "-start_index")
            {
                // Начинать обработку с предложения с указанным индексом
                ++i;
                START_INDEX = int.Parse(args[i]);
            }
            else if (args[i] == "-reject_unknown")
            {
                reject_unknown = true;
            }
            else if (args[i] == "-rx_stop")
            {
                ++i;
                using (System.IO.StreamReader rdr = new System.IO.StreamReader(args[i]))
                {
                    while (!rdr.EndOfStream)
                    {
                        string line = rdr.ReadLine();
                        if (line == null)
                        {
                            break;
                        }

                        line = line.Trim();
                        if (line.Length > 0)
                        {
                            rx_stop.Add(new System.Text.RegularExpressions.Regex(line));
                        }
                    }
                }
            }
            else
            {
                throw new ApplicationException(string.Format("Unknown option {0}", args[i]));
            }
        }


        Samples sources = null;

        if (source_format == 1)
        {
            sources = new Samples1(samples_path);
        }
        else
        {
            sources = new Samples2(samples_path);
        }

        sources.SetMinSentenceLen(min_sentence_length);
        sources.SetMaxSentenceLen(max_sentence_length);

        if (output_suffix || output_words)
        {
            sources.SetTokenDelimiter('|');
        }

        SolarixGrammarEngineNET.GrammarEngine2 gren = null;
        gren = new SolarixGrammarEngineNET.GrammarEngine2();

        if (output_lemmas)
        {
            gren.Load(dictionary_path, true);
        }

        int counter     = -1;
        int n_processed = 1;
        int MAX_COUNT   = NSAMPLE;

        int LanguageID  = SolarixGrammarEngineNET.GrammarEngineAPI.RUSSIAN_LANGUAGE;
        int Constraints = 120000 | (MAXARGS << 22); // 2 мин и 20 альтернатив

        SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags Flags = SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_MODEL_ONLY |
                                                                      SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_MODEL;

        // сколько всего предложений
        Console.WriteLine("Counting lines in source file {0}...", samples_path);
        int n_total_lines = sources.TotalCount();

        Console.WriteLine("Total number of lines={0}", n_total_lines.ToString("N0", new System.Globalization.CultureInfo("en-US")));

        System.IO.StreamWriter wrt = new System.IO.StreamWriter(save_path, append_result, new UTF8Encoding(false));

        sources.Start();
        while (true)
        {
            string sample = sources.Next();
            if (sample == null)
            {
                break;
            }

            sample = sample.Trim();

            counter++;

            if (counter < START_INDEX)
            {
                continue;
            }

            if (n_processed >= MAX_COUNT)
            {
                break;
            }

            bool contains_insane_chars = false;
            foreach (char c in sample)
            {
                if (c < 32)
                {
                    contains_insane_chars = true;
                    break;
                }
            }

            if (contains_insane_chars)
            {
                System.Text.StringBuilder b = new StringBuilder(sample.Length);
                foreach (char c in sample)
                {
                    if (c >= 32)
                    {
                        b.Append(c);
                    }
                }

                sample = b.ToString();
            }

            n_processed++;

            if (sample.Length == 0)
            {
                continue;
            }


            if (rx_stop.Count > 0)
            {
                bool reject_this_sample = false;
                foreach (var rx in rx_stop)
                {
                    if (rx.Match(sample).Success)
                    {
                        reject_this_sample = true;
                        break;
                    }
                }

                if (reject_this_sample)
                {
                    continue;
                }
            }

            if (output_lemmas)
            {
                using (SolarixGrammarEngineNET.AnalysisResults tokens = gren.AnalyzeMorphology(sample, LanguageID, Flags, Constraints))
                {
                    for (int i = 1; i < tokens.Count - 1; ++i)
                    {
                        if (char.IsPunctuation(tokens[i].GetWord()[0]))
                        {
                            continue;
                        }

                        int    id_entry = tokens[i].GetEntryID();
                        string lemma    = gren.GetEntryName(id_entry);
                        if (lemma == "???" || lemma.Equals("UNKNOWNENTRY", StringComparison.InvariantCultureIgnoreCase) || lemma.Equals("number_", StringComparison.InvariantCultureIgnoreCase))
                        {
                            lemma = tokens[i].GetWord();
                        }

                        lemma = lemma.ToLower();
                        wrt.Write(" {0}", lemma);
                    }
                }
            }
            else if (output_words)
            {
                string[] tokens = sample.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                foreach (string token in tokens)
                {
                    if (token.Length >= 1 && char.IsPunctuation(token[0]))
                    {
                        continue;
                    }

                    string norma = token.ToLower();
                    wrt.Write(" {0}", norma);
                }
            }
            else if (output_suffix)
            {
                string[] tokens = sample.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                foreach (string token in tokens)
                {
                    if (token.Length == 0 || (token.Length == 1 && char.IsPunctuation(token[0])))
                    {
                        continue;
                    }

                    string suffix = token;


                    int num;
                    if (int.TryParse(token, out num))
                    {
                        suffix = token.Substring(token.Length - 1);
                    }
                    else if (token.Length > suffix_len + 1)
                    {
                        suffix = "~" + token.Substring(token.Length - suffix_len);
                    }

                    wrt.Write(" {0}", suffix.ToLower());
                }
            }

            if (emit_eol)
            {
                for (int k = 0; k < eol_count; ++k)
                {
                    wrt.Write(" <EOL>");
                }
            }

            Console.WriteLine("[{1}/{2}] {0}", sample, counter, n_total_lines);

            wrt.Flush();
        }

        wrt.Close();

        return;
    }
Example #6
0
    static void Execute( string[] args )
    {
        string dictionary_path = @"e:\MVoice\lem\bin-windows\dictionary.xml"; // путь к словарной базе
          string samples_path = @"E:\MVoice\lem\Слова\rus\SENT5.plain.txt"; // путь к файлу со списком предложений (одно предложение на одной строке)
          int NSAMPLE = 20000; // сколько предложений максимум обработать
          int START_INDEX = 0; // порядковый номер первого обрабатываемого предложений в исходном файле
          int MAXARGS = 20; // beam size
          bool append_result = false; // если леммы надо добавлять к существующему файлу, а не формировать файл с нуля
          string save_path = null; // путь к файлу, куда будут записаны леммы
          int source_format = 0; // 0 - token per line, 1 - sentence per line
          bool output_lemmas = true; // в результат записывать леммы с приведением к нижнему регистру
          bool output_suffix = false;
          bool output_words = false; // в результат записывать исходные слова с приведением к нижнему регистру
          int suffix_len = 0;
          int min_sentence_length = 0; // фильтр по минимальной длине предложений
          int max_sentence_length = int.MaxValue; // фильтр по максимальной длине предложений
          bool reject_unknown = false; // отбрасывать предложения с несловарными токенами
          bool emit_eol = false; // добавлять в выходной файл токены <EOL> для маркировки конца предложения
          int eol_count = 0; // кол-во вставляемых <EOL>, гарантированно перекрывающее размер окна в word2vec

          List<System.Text.RegularExpressions.Regex> rx_stop = new List<System.Text.RegularExpressions.Regex>();

          for( int i = 0; i < args.Length; ++i )
          {
           if( args[i] == "-dict" )
           {
        ++i;
        dictionary_path = args[i];
           }
           else if( args[i] == "-samples" )
           {
        ++i;
        samples_path = args[i];
           }
           else if( args[i] == "-source_format" )
           {
        ++i;
        source_format = int.Parse( args[i] );
           }
           else if( args[i] == "-append" )
           {
        // Добавлять в конец существующего файла
        append_result = true;
           }
           else if( args[i] == "-emit_eol" )
           {
        ++i;
        eol_count = int.Parse( args[i] );
        if( eol_count > 0 )
         emit_eol = true;
           }
           else if( args[i] == "-result" )
           {
        // Способ обработки токенов:
        // lemma  => лемматизация
        // suffix => усечение до псевдосуффикса длиной -suffix_len
        // raw    => исходные слова
        ++i;
        output_lemmas = false;
        output_suffix = false;
        output_words = false;

        if( args[i] == "suffix" )
        {
         output_suffix = true;
        }
        else if( args[i] == "lemma" )
        {
         output_lemmas = true;
        }
        else if( args[i] == "raw" )
        {
         output_words = true;
        }
        else throw new ApplicationException( string.Format( "Unknown result format: {0}", args[i] ) );
           }
           else if( args[i] == "-save" )
           {
        // Путь к файлу, куда будут записываться результаты обработки
        ++i;
        save_path = args[i];
           }
           else if( args[i] == "-nsample" )
           {
        // кол-во обрабатываемых предложений, начиная с -start_index
        ++i;
        NSAMPLE = int.Parse( args[i] );
           }
           else if( args[i] == "-min_sent_len" )
           {
        // Обрабатывать только предложения, содержащие не менее NNN токенов
        ++i;
        min_sentence_length = int.Parse( args[i] );
           }
           else if( args[i] == "-max_sent_len" )
           {
        // Обрабатывать только предложения, содержащие не более NNN токенов
        ++i;
        max_sentence_length = int.Parse( args[i] );
           }
           else if( args[i] == "-suffix_len" )
           {
        ++i;
        suffix_len = int.Parse( args[i] );
           }
           else if( args[i] == "-start_index" )
           {
        // Начинать обработку с предложения с указанным индексом
        ++i;
        START_INDEX = int.Parse( args[i] );
           }
           else if( args[i] == "-reject_unknown" )
           {
        reject_unknown = true;
           }
           else if( args[i] == "-rx_stop" )
           {
        ++i;
        using( System.IO.StreamReader rdr = new System.IO.StreamReader( args[i] ) )
        {
         while( !rdr.EndOfStream )
         {
          string line = rdr.ReadLine();
          if( line == null )
           break;

          line = line.Trim();
          if( line.Length > 0 )
          {
           rx_stop.Add( new System.Text.RegularExpressions.Regex( line ) );
          }
         }
        }
           }
           else
        throw new ApplicationException( string.Format( "Unknown option {0}", args[i] ) );
          }

          Samples sources = null;
          if( source_format == 1 )
           sources = new Samples1( samples_path );
          else
           sources = new Samples2( samples_path );

          sources.SetMinSentenceLen( min_sentence_length );
          sources.SetMaxSentenceLen( max_sentence_length );

          if( output_suffix || output_words )
           sources.SetTokenDelimiter( '|' );

          SolarixGrammarEngineNET.GrammarEngine2 gren = null;
          gren = new SolarixGrammarEngineNET.GrammarEngine2();

          if( output_lemmas )
          {
           gren.Load( dictionary_path, true );
          }

          int counter = -1;
          int n_processed = 1;
          int MAX_COUNT = NSAMPLE;

          int LanguageID = SolarixGrammarEngineNET.GrammarEngineAPI.RUSSIAN_LANGUAGE;
          int Constraints = 120000 | ( MAXARGS << 22 ); // 2 мин и 20 альтернатив

          SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags Flags = SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_MODEL_ONLY |
        SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_MODEL;

          // сколько всего предложений
          Console.WriteLine( "Counting lines in source file {0}...", samples_path );
          int n_total_lines = sources.TotalCount();
          Console.WriteLine( "Total number of lines={0}", n_total_lines.ToString( "N0", new System.Globalization.CultureInfo( "en-US" ) ) );

          System.IO.StreamWriter wrt = new System.IO.StreamWriter( save_path, append_result, new UTF8Encoding( false ) );

          sources.Start();
          while( true )
          {
           string sample = sources.Next();
           if( sample == null )
        break;

           sample = sample.Trim();

           counter++;

           if( counter < START_INDEX )
        continue;

           if( n_processed >= MAX_COUNT )
        break;

           bool contains_insane_chars = false;
           foreach( char c in sample )
        if( c < 32 )
        {
         contains_insane_chars = true;
         break;
        }

           if( contains_insane_chars )
           {
        System.Text.StringBuilder b = new StringBuilder( sample.Length );
        foreach( char c in sample )
         if( c >= 32 )
          b.Append( c );

        sample = b.ToString();
           }

           n_processed++;

           if( sample.Length == 0 )
        continue;

           if( rx_stop.Count > 0 )
           {
        bool reject_this_sample = false;
        foreach( var rx in rx_stop )
         if( rx.Match( sample ).Success )
         {
          reject_this_sample = true;
          break;
         }

        if( reject_this_sample )
         continue;
           }

           if( output_lemmas )
           {
        using( SolarixGrammarEngineNET.AnalysisResults tokens = gren.AnalyzeMorphology( sample, LanguageID, Flags, Constraints ) )
        {
         for( int i = 1; i < tokens.Count - 1; ++i )
         {
          if( char.IsPunctuation( tokens[i].GetWord()[0] ) )
           continue;

          int id_entry = tokens[i].GetEntryID();
          string lemma = gren.GetEntryName( id_entry );
          if( lemma == "???" || lemma.Equals( "UNKNOWNENTRY", StringComparison.InvariantCultureIgnoreCase ) || lemma.Equals( "number_", StringComparison.InvariantCultureIgnoreCase ) )
           lemma = tokens[i].GetWord();

          lemma = lemma.ToLower();
          wrt.Write( " {0}", lemma );
         }
        }
           }
           else if( output_words )
           {
        string[] tokens = sample.Split( "|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries );

        foreach( string token in tokens )
        {
         if( token.Length >= 1 && char.IsPunctuation( token[0] ) )
          continue;

         string norma = token.ToLower();
         wrt.Write( " {0}", norma );
        }
           }
           else if( output_suffix )
           {
        string[] tokens = sample.Split( "|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries );

        foreach( string token in tokens )
        {
         if( token.Length == 0 || ( token.Length == 1 && char.IsPunctuation( token[0] ) ) )
          continue;

         string suffix = token;

         int num;
         if( int.TryParse( token, out num ) )
          suffix = token.Substring( token.Length - 1 );
         else if( token.Length > suffix_len + 1 )
          suffix = "~" + token.Substring( token.Length - suffix_len );

         wrt.Write( " {0}", suffix.ToLower() );
        }
           }

           if( emit_eol )
        for( int k = 0; k < eol_count; ++k )
         wrt.Write( " <EOL>" );

           Console.WriteLine( "[{1}/{2}] {0}", sample, counter, n_total_lines );

           wrt.Flush();
          }

          wrt.Close();

          return;
    }