예제 #1
0
void ModelTagMatcher::Print( lem::OFormatter & to, Dictionary & dict ) const
{
 if( !lexeme.empty() )
  to.printf( "\"%us\" ", lexeme.c_str() );

 for( lem::Container::size_type i=0; i<id_lemma.size(); ++i )
  {
   int id_entry = id_lemma[i];
   const SG_Entry & e = dict.GetSynGram().GetEntry(id_entry);
   int id_class = e.GetClass();
   const SG_Class & c = dict.GetSynGram().GetClass( id_class );
   to.printf( "%us:%us ", c.GetName().c_str(), e.GetName().c_str() );
  }

 for( lem::Container::size_type i=0; i<pos.size(); ++i )
  {
   const SG_Class & c = dict.GetSynGram().GetClass( pos[i] );
   lem::mout->printf( "%us ", c.GetName().c_str() );
  }

 for( lem::Container::size_type i=0; i<pairs.size(); ++i )
  {
   const Solarix::GramCoordPair & p = pairs[i];
   p.SaveTxt( to, dict.GetSynGram() );
   to.printf( " " );
  }

 return;
}
예제 #2
0
void LA_Recognizer::LoadTxt_Misspelling( lem::Iridium::Macro_Parser &txtfile, Dictionary &dict )
{
 txtfile.read_it(B_LANGUAGE);
 // дальше идет наименование языка, в рамках которого действует правило.
 txtfile.read_it( B_EQUAL );
 lem::Iridium::BethToken t1 = txtfile.read();
 int id_language = dict.GetSynGram().Find_Language(t1.string());
 if( id_language==UNKNOWN )
  {
   lem::Iridium::Print_Error(t1,txtfile);
   dict.GetIO().merr().printf( "Unknown language name %us\n", t1.c_str() );
   throw lem::E_BaseException();
  }

 txtfile.read_it( B_OFIGPAREN );

 txtfile.read_it( B_IF );

 Solarix::Lexem old_word = txtfile.read().string();
 old_word.strip(L'"');
 dict.GetLexAuto().TranslateLexem( old_word, true, id_language );
 
 txtfile.read_it( B_THEN );

 Solarix::Lexem new_word = txtfile.read().string();
 new_word.strip(L'"');
 dict.GetLexAuto().TranslateLexem( new_word, true, id_language );
  
 txtfile.read_it( B_CFIGPAREN );

 storage->AddMisspelling( id_language, old_word, new_word );
 return;
}
void ExportCoordFunction_IfContains::LoadTxt(
                                             Dictionary &dict,
                                             lem::Iridium::Macro_Parser & txtfile,
                                             const SynPatterns & pattern_declarations,
                                             SynPatternCompilation & compilation_context,
                                             const SynPatternPoint & point
                                            )
{
 txtfile.read_it( B_OROUNDPAREN );
 pair.LoadTxt( txtfile, dict.GetSynGram() );
 txtfile.read_it( B_CROUNDPAREN );
 return;
}
예제 #4
0
int TF_ClassFilter::Score( const Word_Form &wf, const Dictionary &dict ) const
{
 if( allowed_classes.empty() )
  return 0;

 const int ekey = wf.GetEntryKey();
 if( lem::is_quantor(ekey) )
  return 0;

 const int iclass = dict.GetSynGram().GetEntry(ekey).GetClass();

 return (iclass==UNKNOWN || allowed_classes.find(iclass)!=UNKNOWN) ? 0 : -100;
}
예제 #5
0
void TreeScorerCall::PrintContext( Dictionary & dict, OFormatter & out ) const
{
 out.printf( "Edges count=%d:\n", edges.size() );
 for( int i=0; i<edges.size(); ++i )
  {
   edges[i].from->Print( out, & dict.GetSynGram(), true );
   const int lt = edges[i].link_type;
   out.printf( " --" );
   if( lt==UNKNOWN )
    out.printf( "<<UNKNOWN>>" );
   else
    out.printf( "%us", dict.GetSynGram().GetLink(lt).c_str() );

   out.printf( "--> " );

   edges[i].to->Print( out, & dict.GetSynGram(), true );
   out.eol();
  }

 out.eol();

 return;
}
예제 #6
0
void SyllabRule::LoadTxt( lem::Iridium::Macro_Parser &txtfile, Dictionary &dict )
{
 lem::Iridium::BSourceState point_begin = txtfile.tellp();
 id_src = dict.GetDebugSymbols().RegisterLocation( txtfile, point_begin );

 // шапка: syllab_rule XXXX language=YYY
 name = txtfile.read().string();
 txtfile.read_it( B_LANGUAGE );
 txtfile.read_it( B_EQUAL );
 lem::Iridium::BethToken lang = txtfile.read();
 id_language = dict.GetSynGram().Find_Language(lang.string());
 if( id_language==UNKNOWN )
  {
   lem::Iridium::Print_Error(lang,txtfile);
   dict.GetIO().merr().printf( "Unknown language name %us\n", lang.c_str() );
   throw lem::E_BaseException();
  }     

 txtfile.read_it( B_OFIGPAREN );

 txtfile.read_it( B_IF );
 txtfile.read_it( B_CONTEXT );

 condition.LoadTxt( txtfile, dict );

 txtfile.read_it( B_THEN );
 txtfile.read_it( B_OFIGPAREN );
 txtfile.read_it( B_CONTEXT );

 result.LoadTxt( txtfile, dict, condition );
 
 txtfile.read_it( B_CFIGPAREN ); // закрываем блок then { ... }
 
 txtfile.read_it( B_CFIGPAREN ); // закрываем тело правила

 return; 
}
예제 #7
0
MLNetNode::MLNetNode(
    const MLNetNode* prev,
    int ifrom,
    int nword,
    int tot_len,
    const MCollect<MLProjJob*> &proj,
    const MCollect<MLProjList*> &job_list,
    const MCollect<int> &word_job,
    const MCollect<Lexem> &words,
    Dictionary &dict
)
{
    // Наш узел описывает мультилексемы, начнающиеся с позиции ifrom и
    // содержащие nword лексем.
    previous = prev;
    from = ifrom;
    n = nword;

    const int njob = CastSizeToInt(job_list.size());

    // Собираем пробные мультилексемы, начиная с позиции from предложения.
    // Общая длина предложения задана как tot_len, максимальная длина
    // создаваемых мультилексем равна max_ml_len. Информация о пробных
    // мультилексемах будет хранится в подключаемых узлах.
    const int iFrom = ifrom + nword; // Индекс начала следующих мультилексем.

    if (iFrom == tot_len)
        return;

    int IPROJ_found = UNKNOWN;
    bool PROJ_found = false;

    int max_ml_len = dict.GetSynGram().IsMultiLexemBegin(words[iFrom]);
    if (max_ml_len <= 0)
        max_ml_len = 1;

    Lexem ml;

    SynGram &sg = dict.GetSynGram();

    for (int len = 1; len <= max_ml_len && (iFrom + len) <= tot_len; len++)
    {
        if (len == 1)
        {
            PROJ_found = true;

            const int m0 = tot_len - iFrom;
            const int m1 = std::min(m0, max_ml_len);
            if (m1 == 2)
            {
                if (!sg.IsWordForm(words[iFrom]))
                {
                    ml = words[iFrom];
                    ml.Add(words[iFrom + 1]);
                    if (sg.IsMultiLexem(ml))
                        continue;
                }
                else if (!sg.IsWordForm(words[iFrom + 1]))
                {
                    ml = words[iFrom];
                    ml.Add(words[iFrom + 1]);
                    if (sg.IsMultiLexem(ml))
                        continue;
                }
            }
            else if (m1 == 3)
            {
                ml = words[iFrom];
                ml.Add(words[iFrom + 1]);
                ml.Add(words[iFrom + 2]);
                if (sg.IsMultiLexem(ml))
                {
                    ml = words[iFrom + 1];
                    ml.Add(words[iFrom + 2]);
                    if (!sg.IsMultiLexem(ml))
                    {
                        if (!sg.IsWordForm(words[iFrom + 1]) || !sg.IsWordForm(words[iFrom + 2]))
                            continue;
                    }
                }
            }
        }
        else
        {
            PROJ_found = false;
            IPROJ_found = UNKNOWN;

            ml.clear();
            for (int ii = 0; ii < len; ii++)
                ml.Add(words[iFrom + ii]);

            if (dict.GetSynGram().IsMultiLexem(ml))
            {
                // Если в списке job_list заданий на проекцию мультилексем фразоблока
                // удастся найти задание для нашей мультилексемы и эта мультилексема
                // хоть раз спроецирована, то имеет смысл продолжать построение сети
                // далее.
                for (int ijob = 0; ijob < njob; ijob++)
                {
                    if (
                        *(job_list[ijob]->GetContent()) == ml &&
                        job_list[ijob]->IsProjected()
                        )
                    {
                        PROJ_found = true;
                        IPROJ_found = ijob;
                        break;
                    }
                }
            }
        }

        if (!PROJ_found)
            continue;

        MLNetNode *to_add = new MLNetNode(
            this,
            iFrom,
            len,
            tot_len,
            proj,
            job_list,
            word_job,
            words,
            dict
        );

        child.push_back(to_add);

        // Выставим для узла to_add значение достоверности и индекса задания на
        // проекцию.
        if (len == 1)
        {
            const MLProjJob &prj = *proj[word_job[iFrom]];
            to_add->val = prj.GetVal();
            to_add->proj_job_i = prj.GetiJob();

            //mout.printf( "ml=%us val=%f\n",  proj[word_job[iFrom]].GetContent()->string().c_str(), prj.GetVal().GetFloat() );
        }
        else
        {
            Real1 VAL(100);
            to_add->val = VAL;
            to_add->proj_job_i = IPROJ_found;
        }
    }

    return;
}
예제 #8
0
void SynPattern::LoadTxt(
                         Dictionary &dict,
                         lem::Iridium::Macro_Parser & txtfile,
                         const SynPatterns &patterns,
                         WordEntrySet &wordentry_set,
                         const TrProcedureDeclaration &procs,
                         TrFunctions &functions
                        )
{
 lem::Iridium::BSourceState pattern_beginning = txtfile.tellp();

 id_src = dict.GetDebugSymbols().RegisterLocation( txtfile, txtfile.tellp() );

 if( dict.GetDebugLevel_ir()>=3 )
  {
   dict.GetIO().mecho().printf( "pattern " );
  }

 // ќпционально могут быть заданы целевой ¤зык и опции.

 while( !txtfile.eof() )
 {
  if( txtfile.probe( B_OFIGPAREN ) )
   break;

  if( txtfile.probe( B_LANGUAGE ) )
   {
    txtfile.read_it( B_EQUAL );
   
    lem::Iridium::BethToken lang = txtfile.read();
    id_language = dict.GetSynGram().Find_Language(lang.string());
    if( id_language==UNKNOWN )
     {
      lem::Iridium::Print_Error(lang,txtfile);
      dict.GetIO().merr().printf( "Unknown language name %us\n", lang.c_str() );
      throw lem::E_BaseException();
     }     
   }
  else if( txtfile.probe( L"incomplete" ) )
   {
    incomplete=true;
   }
  else
   {
    lem::Iridium::BethToken tname = txtfile.read();
    name = tname.string();
  
    if( dict.GetDebugLevel_ir()>=3 )
     {
      dict.GetIO().mecho().printf( "%vfE%us%vn ", name.c_str() );
     }
  
    if( !patterns.IsPatternName(name) )
     {
      dict.GetIO().merr().printf( "Patterns group [%us] is not declared\n", name.c_str() );
      lem::Iridium::Print_Error(tname,txtfile);
      throw lem::E_BaseException();
     }
  
    const SynPatternOptions & group_options = patterns.GetOptions(name);
    id_language = group_options.GetLanguageId();
  
    // —екци¤ export { ... } содержит объ¤влени¤ координат, которые паттерн выдает наружу
    // —начала попробуем вз¤ть содержимое экспорта по умолчанию, зарегистрированное в объ¤влении
    // группы паттернов.
  
    if( txtfile.probe(L"export") )
     {
      export_info.LoadTxt( dict, txtfile );
     }
    else
     {
      const SynPatternOptions & p_options = patterns.GetOptions(name);
      export_info = p_options.GetExport();
     }
  
    export_info.RegisterExport( *compilation_context );
  
    if( txtfile.probe( B_LANGUAGE ) )
     {
      txtfile.read_it( B_EQUAL );
      
      lem::Iridium::BethToken lang = txtfile.read();
      id_language = dict.GetSynGram().Find_Language(lang.string());
      if( id_language==UNKNOWN )
       {
        lem::Iridium::Print_Error(lang,txtfile);
        dict.GetIO().merr().printf( "Unknown language name %us\n", lang.c_str() );
        throw lem::E_BaseException();
       }     
     }
  
    txtfile.read_it( B_OFIGPAREN );
    break;
   }
 }

 // —писок опорных точек в фигурных скобочках
 lem::Iridium::BSourceState beg = txtfile.tellp();

 compilation_context->SetName( name );
 compilation_context->Set(&wordentry_set);

 while( !txtfile.eof() )
  {
   if( txtfile.pick().GetToken()==B_CFIGPAREN )
    {
     txtfile.read();
     break;
    }

   SlotProperties slot;
   slot.LoadTxt( dict, txtfile );

   SynPatternPoint *p = new SynPatternPoint;
   p->LoadTxt( dict, txtfile, patterns, *compilation_context, procs, functions );

   points.push_back(p);
   slots.push_back(slot);
   compilation_context->BeforeNextPointCompilation();
  }

 if( points.empty() )
  {
   lem::Iridium::Print_Error(beg,txtfile);
   dict.GetIO().merr().printf("Pattern must not be empty\n" );
   throw E_Solarix();
  }

 if( !compilation_context->PatternHasBeenCompiled(dict.GetSynGram()) )
  {
   lem::Iridium::Print_Error(pattern_beginning,txtfile);
   dict.GetIO().merr().printf("Some export items are not actually exported\n" );
   throw E_Solarix();
  }

 points.back()->Terminator();

 bool links_loaded=false, ngrams_loaded=false, predicates_loaded=false, constraints_loaded=false;

 while( !txtfile.eof() )
  if( txtfile.probe(B_COLON) )
   {
    lem::Iridium::BSourceState section_beg = txtfile.tellp();

    if( txtfile.probe( L"links" ) )
     {
      if( links_loaded )
       {
        lem::Iridium::Print_Error(section_beg,txtfile);
        dict.GetIO().merr().printf("Redefinition of 'links'\n" );
        throw E_Solarix();
       }
 
      LoadLinks( dict, txtfile, *compilation_context );
      links_loaded=true;
     }
    else if( txtfile.probe( L"ngrams" ) )
     {
      if( ngrams_loaded )
       {
        lem::Iridium::Print_Error(section_beg,txtfile);
        dict.GetIO().merr().printf("Redefinition of 'ngrams'\n" );
        throw E_Solarix();
       }

      LoadNGrams( dict, txtfile, *compilation_context );
      ngrams_loaded=true;
     }
    else if( txtfile.probe( L"predicates" ) )
     {
      if( predicates_loaded )
       {
        lem::Iridium::Print_Error(section_beg,txtfile);
        dict.GetIO().merr().printf("Redefinition of 'predicates'\n" );
        throw E_Solarix();
       }

      LoadPredicates( dict, txtfile, *compilation_context );
      predicates_loaded=true;
     }
/*
    else if( sparse && txtfile.probe( L"constraints" ) )
     {
      if( constraints_loaded )
       {
        lem::Iridium::Print_Error(section_beg,txtfile);
        dict.GetIO().merr().printf("Redefinition of 'constraints'\n" );
        throw E_Solarix();
       }

      LoadConstraints( dict, txtfile, *compilation_context );
      constraints_loaded=true;
     }*/
    else
     {
      lem::Iridium::Print_Error(txtfile);
      dict.GetIO().merr().printf("Unexpected token\n" );
      throw E_Solarix();
     }
   }
  else
   {
    break;
   }


 // ќпорные точки могут теперь выполнить внутренние оптимизации, в частности - учесть использование
 // маркировок и улучшить эффективность директивы @mark()
 for( lem::Container::size_type i=0; i<points.size(); ++i )
  points[i]->OptimizeAfterCompilation( *compilation_context );

 // Ѕезым¤нные паттерны, то есть правила самого верхнего уровн¤, должны быть прив¤заны к ¤зыку с помощью директивы { language=XXX }
 if( id_language==UNKNOWN && name.empty() )
  {
   lem::Iridium::Print_Error(pattern_beginning,txtfile);
   dict.GetIO().merr().printf("Pattern must be bound to a language\n" );
   throw E_Solarix();
  }

 if( dict.GetDebugLevel_ir()>=3 )
  {
   dict.GetIO().mecho().printf( "%vfAOK%vn\n" );
  }
 
 return;
}
예제 #9
0
void SynPatternExport::LoadTxt(
                               Dictionary &dict,
                               lem::Iridium::Macro_Parser & txtfile
                              )
{
 txtfile.read_it( B_OFIGPAREN );

 while( !txtfile.eof() )
  {
   bool null_export = txtfile.probe( B_OROUNDPAREN );
   lem::Iridium::BethToken coord_name = txtfile.read();
 
   if( coord_name.GetToken()==B_CFIGPAREN )
    break;

   if( coord_name.string().eqi( L"node" ) )
    {
     txtfile.read_it( B_COLON );
     lem::Iridium::BethToken t_node_name = txtfile.read();
     lem::UCString node_name = t_node_name.string();
     node_name.to_upper();

     if( export_nodes.find(node_name)!=UNKNOWN )
      {
       dict.GetIO().merr().printf( "Wordform %us is already mentioned in export section\n", t_node_name.string().c_str() );
       lem::Iridium::Print_Error(t_node_name,txtfile);
       throw lem::E_BaseException();
      }

     export_nodes.push_back( node_name );
     null_export_nodes.push_back( null_export ? 1 : 0 );

     if( null_export )
      txtfile.read_it( B_CROUNDPAREN );

     continue;
    }

   const GramCoordAdr iglob_coord = dict.GetSynGram().FindCoord(coord_name.string());
 
   if( !iglob_coord.IsDefined() )
    {
     dict.GetIO().merr().printf( "Unknown coordinate %us\n", coord_name.c_str() );
     lem::Iridium::Print_Error(coord_name,txtfile);
     throw lem::E_BaseException();
    }
 
   if( export_coords.find( iglob_coord.GetIndex() )!=UNKNOWN )
    {
     dict.GetIO().merr().printf( "Coordinate %us is already mentioned in export section\n", coord_name.c_str() );
     lem::Iridium::Print_Error(coord_name,txtfile);
     throw lem::E_BaseException();
    }
 
   export_coords.push_back(iglob_coord.GetIndex());
   null_export_coords.push_back( null_export ? 1 : 0 );

   if( null_export )
    txtfile.read_it( B_CROUNDPAREN );
  }

 return;
}
예제 #10
0
void PatternConstraint::LoadTxt( 
                                Dictionary &dict,
                                lem::Iridium::Macro_Parser & txtfile,
                                SynPatternCompilation & compilation_context
                               )
{
 lem::Iridium::BethToken marker_name = txtfile.read();

 if( compilation_context.Find(marker_name)==UNKNOWN )
  {
   dict.GetIO().merr().printf( "Marker [%us] is not declared in this pattern", marker_name.c_str() );
   lem::Iridium::Print_Error(marker_name,txtfile);
   throw lem::E_BaseException();
  }

 // ---------------------------

 from_marker = marker_name.string();
 from_marker.to_upper();

 // ---------------------------

 txtfile.read_it( B_COLON );

 lem::Iridium::BethToken coord_name1 = txtfile.read();
 //if( for_group ) txtfile.read_it( B_CSPAREN );

 Solarix::GramCoordAdr iglob_coord1 = dict.GetSynGram().FindCoord(coord_name1.string());

 if( !iglob_coord1.IsDefined() )
  {
   dict.GetSynGram().GetIO().merr().printf( "Unknown coordinate %us\n", coord_name1.c_str() );
   lem::Iridium::Print_Error(coord_name1,txtfile);
   throw lem::E_BaseException();
  }

 from_coord_id = iglob_coord1.GetIndex();

 // ---------------------------

 lem::Iridium::BethToken func = txtfile.read();

 if( func.GetToken()==B_EQUAL )
  constraint_func = EqualFunc;
 else if( func.GetToken()==B_LOGNE )
  constraint_func = NotEqualFunc;
 else
  {
   dict.GetIO().merr().printf( "Unknown constraint [%us]", func.string().c_str() );
   lem::Iridium::Print_Error(func,txtfile);
   throw lem::E_BaseException();
  }

 marker_name = txtfile.read();

 if( compilation_context.Find(marker_name)==UNKNOWN )
  {
   dict.GetIO().merr().printf( "Marker [%us] is not declared in this pattern", marker_name.c_str() );
   lem::Iridium::Print_Error(marker_name,txtfile);
   throw lem::E_BaseException();
  }

 to_marker = marker_name.string();
 to_marker.to_upper();

 // ---------------------------

 txtfile.read_it( B_COLON );

 lem::Iridium::BethToken coord_name2 = txtfile.read();
 //if( for_group ) txtfile.read_it( B_CSPAREN );

 Solarix::GramCoordAdr iglob_coord2 = dict.GetSynGram().FindCoord(coord_name2.string());

 if( !iglob_coord2.IsDefined() )
  {
   dict.GetSynGram().GetIO().merr().printf( "Unknown coordinate %us\n", coord_name2.c_str() );
   lem::Iridium::Print_Error(coord_name2,txtfile);
   throw lem::E_BaseException();
  }

 to_coord_id = iglob_coord2.GetIndex();

 return;
}