LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
SpecificEntitiesConstraints.cpp
Go to the documentation of this file.
1// Copyright 2002-2019 CEA LIST
2// SPDX-FileCopyrightText: 2022 CEA LIST <gael.de-chalendar@cea.fr>
3//
4// SPDX-License-Identifier: MIT
5
6/***************************************************************************
7 * Copyright (C) 2004-2019 by CEA LIST *
8 * *
9 ***************************************************************************/
21#include <QStringList>
22#include <queue>
23#include <iostream>
24#include <sstream>
25
26// #include <assert.h>
27
28using namespace Lima::Common::MediaticData;
29using namespace Lima::Common::AnnotationGraphs;
34
35namespace Lima
36{
37
39{
40
41namespace SpecificEntities
42{
43
44// factories for constraint functions defined in this file
45ConstraintFunctionFactory<isAlphaPossessive>
47
50
53
56
59
62
65
68
71
72
74isAlphaPossessive(MediaId language,
75 const LimaString& complement):
76ConstraintFunction(language,complement)
77{
78}
79
81 const LinguisticGraphVertex& v,
82 AnalysisContent& /*analysis*/) const
83{
84 LinguisticGraph* lingGraph = const_cast<LinguisticGraph*>(graph.getGraph());
85// Token* token=get(vertex_token,*(graph.getGraph()),v);
86 VertexTokenPropertyMap tokenMap = get(vertex_token, *lingGraph);
87 const TStatus& status = tokenMap[v]->status();
88 return( status.isAlphaPossessive() );
89}
90
91
93isASpecificEntity(MediaId language,
94 const LimaString& complement):
95ConstraintFunction(language,complement),
96m_type()
97{
98 if (! complement.isEmpty()) {
99 m_type=Common::MediaticData::MediaticData::single().getEntityType(complement);
100 }
101}
102
104 const LinguisticGraphVertex& v,
105 AnalysisContent& analysis) const
106{
107 auto recoData = std::dynamic_pointer_cast<RecognizerData>(analysis.getData("RecognizerData"));
108 auto annotationData = std::dynamic_pointer_cast< AnnotationData >(analysis.getData("AnnotationData"));
109 if (annotationData == 0)
110 {
111 return false;
112 }
113 bool annotFound = false;
114 //std::set< uint64_t > matches = annotationData->matches(recoData->getGraphId(),v,"annot"); portage 32 64
115 //for (std::set< uint64_t >::const_iterator it = matches.begin(); portage 32 64
116 std::set< AnnotationGraphVertex > matches = annotationData->matches(recoData->getGraphId(),v,"annot");
117 for (std::set< AnnotationGraphVertex >::const_iterator it = matches.begin();
118 it != matches.end(); it++)
119 {
120 if (annotationData->hasAnnotation(*it, Common::Misc::utf8stdstring2limastring("SpecificEntity")))
121 {
122 annotFound = true;
123 break;
124 }
125 }
126
127 if (!annotFound)
128 {
129 return false;
130 }
131
132 if (m_type == Common::MediaticData::EntityType())
133 {
134 return true;
135 }
136 else
137 {
138 //for (std::set< uint64_t >::const_iterator it = matches.begin(); portage 32 64
139 for (std::set< AnnotationGraphVertex >::const_iterator it = matches.begin();
140 it != matches.end(); it++)
141 {
142 if (annotationData->annotation(*it,
144 .pointerValue<SpecificEntityAnnotation>()->getType() == m_type)
145 {
146 return true;
147 }
148 }
149 return false;
150 }
151 return false;
152}
153
154
156 const LimaString& complement):
157ConstraintFunction(language,complement),
158m_language(language)
159{
160#ifdef DEBUG_LP
161 SELOGINIT;
162#endif
163
164 LimaString str=complement; // copy for easier parse (modify)
166 if (!str.isEmpty()) {
167 LimaString typeName;
168 int j=str.indexOf(sep);
169 if (j!=-1) {
170 typeName=str.left(j);
171 str=str.mid(j+1);
172 }
173 else {
174 typeName=complement;
175 str.clear();
176 }
177#ifdef DEBUG_LP
178 LDEBUG << "CreateSpecificEntity: getting entity type "
180#endif
181 try {
183 } catch (const LimaException& e) {
184 SELOGINIT;
185 LIMA_EXCEPTION("Unknown entity type" << typeName << e.what());
186 }
187 }
188
189 const Common::PropertyCode::PropertyManager& microManager=
190 static_cast<const Common::MediaticData::LanguageData&>(Common::MediaticData::MediaticData::single().mediaData(language)).getPropertyCodeManager().
191getPropertyManager("MICRO");
192
193 if (!str.isEmpty())
194 {
195 //uint64_t currentPos = 0; portage 32 64
196 int currentPos = 0;
197 while (currentPos != str.size()+1)
198 {
199 int sepPos = str.indexOf(sep, currentPos);
200
201 if (sepPos == -1)
202 {
203 sepPos = str.size();
204 }
205 std::string smicro=Common::Misc::limastring2utf8stdstring(str.mid(currentPos, sepPos-currentPos));
206 LinguisticCode micro = microManager.getPropertyValue(smicro);
207 m_microsToKeep.insert(micro);
208// LDEBUG << "Added " << smicro << " / " << micro << " to micros to keep";
209 currentPos = sepPos+1;
210 }
211 }
212}
213
216 AnalysisContent& analysis) const
217{
218#ifdef DEBUG_LP
219 SELOGINIT;
220 LDEBUG << "CreateSpecificEntity: create entity of type " << match.getType() << " on vertices " << match;
221#endif
222 if (match.empty()) return false;
223 LinguisticGraphVertex v1 = (*(match.begin())).m_elem.first;
224 LinguisticGraphVertex v2 = (*(match.rbegin())).m_elem.first;
226
227// LDEBUG << "CreateSpecificEntity action between " << v1 << " and " << v2
228// << " with complement " << m_complement;
229 auto syntacticData = std::dynamic_pointer_cast<SyntacticData>(analysis.getData("SyntacticData"));
230
231 auto annotationData = std::dynamic_pointer_cast< AnnotationData >(analysis.getData("AnnotationData"));
232 if (annotationData==0)
233 {
234 return false;
235 }
236 // do not create annotation if annotation of same type exists
237 if (match.size() == 1)
238 {
239 //&& (isASpecificEntity(0,LimaString())(graph,v1,analysis)))
240 //std::set< uint64_t > matches = annotationData->matches(graph.getGraphId(),v1,"annot"); portage 32 64
241 //for (std::set< uint64_t >::const_iterator it = matches.begin(); portage 32 64
242 std::set< AnnotationGraphVertex > matches = annotationData->matches(graph.getGraphId(),v1,"annot");
243 for (std::set< AnnotationGraphVertex >::const_iterator it = matches.begin();
244 it != matches.end(); it++) {
245 if (annotationData->hasAnnotation(*it, Common::Misc::utf8stdstring2limastring("SpecificEntity"))
246 && annotationData->annotation(*it,
248 .pointerValue<SpecificEntityAnnotation>()->getType() == match.getType() ) {
249 return false;
250 }
251 }
252 }
253
254/* {
255 std::set< uint32_t > annots = annotationData->matches(recoData.getGraphId(), v1, "annot");
256 for ( std::set< uint32_t >::iterator it = annots.begin(); it != annots.end(); it++)
257 {
258 if (annotationData->hasAnnotation( *it, Common::Misc::utf8stdstring2limastring("SpecificEntity")))
259 }
260 }*/
261 if (annotationData->dumpFunction("SpecificEntity") == 0)
262 {
263 annotationData->dumpFunction("SpecificEntity", new DumpSpecificEntityAnnotation());
264 }
265
266 auto rdata = analysis.getData("RecognizerData");
267 if (rdata == 0) {
268 SELOGINIT;
269 LERROR << "CreateSpecificEntity: missing data RecognizerData: entity will not be created";
270 return false;
271 }
272 auto recoData = std::dynamic_pointer_cast<RecognizerData>(rdata);
273 if (recoData==0) {
274 SELOGINIT;
275 LERROR << "CreateSpecificEntity: missing data RecognizerData: entity will not be created";
276 return false;
277 }
278 std::string graphId=recoData->getGraphId();
279
280// LDEBUG << " match is " << match;
281
282// LDEBUG << " Creating annotation ";
283 SpecificEntityAnnotation annot(match, Common::MediaticData::MediaticData::changeable().stringsPool(m_language));
284 std::ostringstream oss;
285 annot.dump(oss);
286#ifdef DEBUG_LP
287 LDEBUG << "CreateSpecificEntity: annot = " << oss.str();
288
289// LDEBUG << " Building new morphologic data for head "<< annot.getHead();
290#endif
291 // getting data
292 LinguisticGraph* lingGraph = const_cast<LinguisticGraph*>(graph.getGraph());
293// LDEBUG << "There is " << out_degree(v2, *lingGraph) << " edges out of " << v2;
294 VertexTokenPropertyMap tokenMap = get(vertex_token, *lingGraph);
295 VertexDataPropertyMap dataMap = get(vertex_data, *lingGraph);
296
297 LinguisticGraphVertex head = annot.getHead();
298 if( head == 0 ) {
299 // take status of last element in match for eng
300 head = v2;
301 // or take status of first element in match (in fre?)
302 // head = v1;
303 }
304 const MorphoSyntacticData* dataHead = dataMap[head];
305
306 // Preparer le Token et le MorphoSyntacticData pour le nouveau noeud. Construits
307 // a partir des infos de l'entitee nommee
308 StringsPoolIndex seFlex = annot.getString();
309 // !!! RB: use normalized form for lemma : better for cascading rules, since its easier to write rules that
310 // match the expected normalized form given in a previous rule than rules that match the lemma, which is computed by LIMA
311 // @todo : check the impact of this change
312 //StringsPoolIndex seLemma = annot.getNormalizedString();
313 StringsPoolIndex seLemma = annot.getNormalizedForm();
314 StringsPoolIndex seNorm = annot.getNormalizedForm();
315
316// LDEBUG << " Creating LinguisticElement";
317// LDEBUG << " Creating MorphoSyntacticData";
318 // creer un MorphoSyntacticData
319 MorphoSyntacticData* newMorphData = new MorphoSyntacticData();
320
321 // all linguisticElements of this morphosyntacticData share common SE information
323 elem.inflectedForm = seFlex; // StringsPoolIndex
324 elem.lemma = seLemma; // StringsPoolIndex
325 elem.normalizedForm = seNorm; // StringsPoolIndex
326 elem.type = SPECIFIC_ENTITY; // MorphoSyntacticType
327
328 if (! m_microsToKeep.empty()) {
329#ifdef DEBUG_LP
330 LDEBUG << "CreateSpecificEntity, use micros from the rule ";
331#endif
332 // micros are given in the rules
333 addMicrosToMorphoSyntacticData(newMorphData,dataHead,m_microsToKeep,elem);
334 }
335 else {
336#ifdef DEBUG_LP
337 LDEBUG << "CreateSpecificEntity, use micros from config file ";
338#endif
339 // use micros given in the config file : get the specific resource
340 // (specific to modex) AddEntityFeature
341 // WARN : some hard coded stuff here in resource names
342 EntityType seType=match.getType();
343 if (seType.getGroupId() == static_cast<EntityGroupId>(0))
344 {
345 SELOGINIT;
346 LERROR << "CreateSpecificEntity::operator() null group id:" << seType;
347 delete newMorphData;
348 return false;
349 }
350 const LimaString& resourceName =
352 auto res = LinguisticResources::single().getResource(m_language,resourceName.toUtf8().constData());
353#ifdef DEBUG_LP
354 LDEBUG << "Entities resource name is : " << resourceName;
355#endif
356 if (res!=0) {
357 auto entityMicros = std::dynamic_pointer_cast<SpecificEntitiesMicros>(res);
358 auto micros = entityMicros->getMicros(seType);
359#ifdef DEBUG_LP
360 if (logger.isDebugEnabled())
361 {
362 std::ostringstream oss;
363 for (std::set<LinguisticCode>::const_iterator it=micros->begin(),it_end=micros->end();it!=it_end;it++) {
364 oss << (*it) << ";";
365 }
366 LDEBUG << "CreateSpecificEntity, micros are " << oss.str();
367 }
368#endif
369 addMicrosToMorphoSyntacticData(newMorphData,dataHead,*micros,elem);
370 }
371 else {
372 // cannot find micros for this type: error
373 SELOGINIT;
374 LERROR << "CreateSpecificEntity: missing resource " << resourceName ;
375 delete newMorphData;
376 return false;
377 }
378 }
379
381 Token* newToken = new Token(
382 seFlex,
383 sp[seFlex],
384 match.positionBegin(),
385 match.length());
386
387 // take posessive tstatus from head
388 TStatus tStatus = tokenMap[head]->status();
389 const TStatus& headTStatus = tokenMap[v2]->status();
390 if(headTStatus.isAlphaPossessive()) {
391 tStatus.setAlphaPossessive(true);
392 }
393 newToken->setStatus(tStatus);
394
395 if (newMorphData->empty())
396 {
397 SELOGINIT;
398 LERROR << "CreateSpecificEntity::operator() Found no morphosyntactic data for new vertex. Abort.";
399 delete newToken;
400 delete newMorphData;
401 assert(false);
402 return false;
403 }
404// LDEBUG << " Updating morphologic graph "<< graphId;
405 // creer le noeud et ses 2 arcs
406 LinguisticGraphVertex newVertex;
407 DependencyGraphVertex newDepVertex = 0;
408 if (syntacticData != 0)
409 {
410 boost::tie (newVertex, newDepVertex) = syntacticData->addVertex();
411 }
412 else
413 {
414 newVertex = add_vertex(*lingGraph);
415 }
416 AnnotationGraphVertex agv = annotationData->createAnnotationVertex();
417 annotationData->addMatching(graphId, newVertex, "annot", agv);
418 annotationData->annotate(agv, Common::Misc::utf8stdstring2limastring(graphId), newVertex);
419 tokenMap[newVertex] = newToken;
420 dataMap[newVertex] = newMorphData;
421#ifdef DEBUG_LP
422 LDEBUG << " - new vertex " << newVertex << "("<<graphId<<"), " << newDepVertex
423 << "(dep), " << agv << "(annot) added";
424
425// LDEBUG << " Setting annotation ";
426#endif
427 GenericAnnotation ga(annot);
428
429 annotationData->annotate(agv, Common::Misc::utf8stdstring2limastring("SpecificEntity"), ga);
430// LDEBUG << " Creating SE annotation edges between SE match vertices "
431// "annotation and the new annotation vertex";
432 Automaton::RecognizerMatch::const_iterator matchIt, matchIt_end;
433 matchIt = match.begin(); matchIt_end = match.end();
434 for (; matchIt != matchIt_end; matchIt++)
435 {
436 std::set< AnnotationGraphVertex > matches = annotationData->matches(graphId,(*matchIt).m_elem.first,"annot");
437 if (matches.empty())
438 {
439 SELOGINIT;
440 LERROR << "CreateSpecificEntity::operator() No annotation 'annot' for" << (*matchIt).m_elem.first;
441 }
442 else
443 {
444 if( recoData->hasVertexAsEmbededEntity((*matchIt).m_elem.first) )
445 {
446#ifdef DEBUG_LP
447 LDEBUG << "CreateSpecificEntity::operator(): vertex " << *(matches.begin()) << " is embeded";
448#endif
449 AnnotationGraphVertex src = *(matches.begin());
450 annotationData->annotate( agv, src, Common::Misc::utf8stdstring2limastring("holds"), 1);
451 }
452 }
453 }
454
455 // creer les relations necessaires dans le graphe morphosyntaxique
456 // 1. entre les noeuds avant v1 et le nouveau noeud
457 std::vector< LinguisticGraphVertex > previous;
458 LinguisticGraphInEdgeIt firstInEdgesIt, firstInEdgesIt_end;
459 boost::tie(firstInEdgesIt, firstInEdgesIt_end) = in_edges(v1, *lingGraph);
460 std::set< std::pair<LinguisticGraphVertex,LinguisticGraphVertex > > newEdgesToRemove;
461 for (; firstInEdgesIt != firstInEdgesIt_end; firstInEdgesIt++)
462 {
463 LinguisticGraphVertex firstInVertex = source(*firstInEdgesIt, *lingGraph);
464 previous.push_back(firstInVertex);
465 if (shouldRemoveInitial(source(*firstInEdgesIt, *lingGraph),target(*firstInEdgesIt, *lingGraph), match))
466 {
467#ifdef DEBUG_LP
468 LDEBUG << " - storing edge " << source(*firstInEdgesIt, *lingGraph) <<" -> "<<target(*firstInEdgesIt, *lingGraph) << " to be removed";
469#endif
470/* recoData->setEdgeToBeRemoved(analysis, *firstInEdgesIt);*/
471 newEdgesToRemove.insert(std::make_pair(source(*firstInEdgesIt, *lingGraph),target(*firstInEdgesIt, *lingGraph)));
472 }
473 else
474 {
475#ifdef DEBUG_LP
476 LDEBUG << " - do not store initial edge " << source(*firstInEdgesIt, *lingGraph) <<" -> "<<target(*firstInEdgesIt, *lingGraph) << " to be removed";
477#endif
478 }
479 }
480 std::vector< LinguisticGraphVertex >::iterator pit, pit_end;
481 pit = previous.begin(); pit_end = previous.end();
482 for (; pit != pit_end; pit++)
483 {
484 /* Si X-Y doit etre supprime et que Z remplace Y , alors ne pas creer X-Z
485 autrement dit si *pit-v1 est dans recoData->m_edgesToRemove, ne pas creer l'arc */
486 if (!recoData->isEdgeToBeRemoved(*pit, v1))
487 {
488 bool success;
490 boost::tie(e, success) = add_edge(*pit, newVertex, *lingGraph);
491 if (success)
492 {
493#ifdef DEBUG_LP
494 LDEBUG << " - in edge " << e.m_source << " -> " << e.m_target << " added";
495#endif
496 }
497 else
498 {
500 LERROR << " - in edge " << *pit << " ->" << newVertex << " NOT added";
501 }
502 }
503 else
504 {
505#ifdef DEBUG_LP
506 LDEBUG << " - edge " << *pit << " - " << newVertex << " not added because " << *pit << " - " << v1 << " has to be removed";
507#endif
508 }
509 }
510 std::set< std::pair<LinguisticGraphVertex,LinguisticGraphVertex > >::iterator newEdgesToRemoveIt = newEdgesToRemove.begin();
511 for (; newEdgesToRemoveIt != newEdgesToRemove.end(); newEdgesToRemoveIt++)
512 {
513 recoData->setEdgeToBeRemoved(analysis, edge( newEdgesToRemoveIt->first, newEdgesToRemoveIt->second, *lingGraph).first);
514 }
515#ifdef DEBUG_LP
516 LDEBUG << " - in edges added";
517#endif
518
519
520 // 2. entre le nouveau noeud et les noeuds qui etaient apres v2
521#ifdef DEBUG_LP
522 LDEBUG << " there is " << out_degree(v2, *lingGraph) << " edges out of " << v2;
523#endif
524 LinguisticGraphOutEdgeIt secondOutEdgesIt, secondOutEdgesIt_end;
525 boost::tie(secondOutEdgesIt, secondOutEdgesIt_end) = out_edges(v2, *lingGraph);
526 std::vector< LinguisticGraphVertex > nexts;
527 for (; secondOutEdgesIt != secondOutEdgesIt_end; secondOutEdgesIt++)
528 {
529#ifdef DEBUG_LP
530 LDEBUG << " looking at edge " << source(*secondOutEdgesIt, *lingGraph) << " -> " << target(*secondOutEdgesIt, *lingGraph);
531#endif
532 LinguisticGraphVertex secondOutVertex = target(*secondOutEdgesIt, *lingGraph);
533 if (secondOutVertex == v2) continue;
534 nexts.push_back(secondOutVertex);
535 if (shouldRemoveFinal(source(*secondOutEdgesIt, *lingGraph),target(*secondOutEdgesIt, *lingGraph), match))
536 {
537#ifdef DEBUG_LP
538 LDEBUG << " - storing edge " << source(*secondOutEdgesIt, *lingGraph) << " -> " << target(*secondOutEdgesIt, *lingGraph) << " to be removed";
539#endif
540 recoData->setEdgeToBeRemoved(analysis, *secondOutEdgesIt);
541 }
542 else
543 {
544#ifdef DEBUG_LP
545 LDEBUG << " - do not store final edge " << source(*secondOutEdgesIt, *lingGraph) << " -> " << target(*secondOutEdgesIt, *lingGraph) << " to be removed";
546#endif
547 }
548 }
549 std::vector< LinguisticGraphVertex >::iterator nit, nit_end;
550 nit = nexts.begin(); nit_end = nexts.end();
551 for (; nit != nit_end; nit++)
552 {
553 bool success;
555 boost::tie(e, success) = add_edge(newVertex, *nit, *lingGraph);
556 if (success)
557 {
558#ifdef DEBUG_LP
559 LDEBUG << " - out edge " << e.m_source << " -> " << e.m_target << " added";
560#endif
561 }
562 else
563 {
564 SELOGINIT;
565 LERROR << " - out edge " << newVertex << " ->" << *nit << " NOT added";
566 }
567 }
568#ifdef DEBUG_LP
569 LDEBUG << " - out edges added";
570#endif
571
572 // 3. supprimer les arcs a remplacer
573 recoData->removeEdges( analysis );
574
575 // 4 specifier le noeud suivant a utiliser dans la recherche :
576 // - nouveau noeud si l'expression reconnue etait composee de plusieurs noeuds
577 // - les fils du nouveau noeud sinon (pour eviter les bouclages)
578 // correction 08/2016 : always restart rules application from following vertices
579 // to avoid unexpected behaviors (see issues #44 and #45)
580 /*if (annot.m_vertices.size() > 1)
581 {
582 recoData->setNextVertex(newVertex);
583 }
584 else*/
585 {
586 LinguisticGraphOutEdgeIt outItr,outItrEnd;
587 boost::tie(outItr,outItrEnd) = out_edges(newVertex,*lingGraph);
588 for (;outItr!=outItrEnd;outItr++)
589 {
590 recoData->setNextVertex(target(*outItr, *lingGraph));
591 }
592 }
593 RecognizerMatch::const_iterator matchItr=match.begin();
594 for (; matchItr!=match.end(); matchItr++)
595 {
596 recoData->clearUnreachableVertices( analysis, (*matchItr).getVertex());
597 }
598
599 return true;
600}
601
602void CreateSpecificEntity::addMicrosToMorphoSyntacticData(LinguisticAnalysisStructure::MorphoSyntacticData* newMorphData,
604 const std::set<LinguisticCode>& micros,
606{
607 // The accessor is not cached at construction: the compiled rules (and thus
608 // this constraint) outlive a reinitialization of the media data, e.g. when
609 // a second analyzer is created in the same process.
610 const auto& microAccessor = static_cast<const Common::MediaticData::LanguageData&>(
612 .getPropertyCodeManager().getPropertyAccessor("MICRO");
613 // try to filter existing microcategories
614 for (MorphoSyntacticData::const_iterator it=oldMorphData->begin(),
615 it_end=oldMorphData->end(); it!=it_end; it++) {
616
617 if (micros.find(microAccessor.readValue((*it).properties)) !=
618 micros.end()) {
619 elem.properties=(*it).properties;
620 newMorphData->push_back(elem);
621 }
622 }
623 // if no categories kept : assign all micros to keep
624 if (newMorphData->empty()) {
625 for (std::set<LinguisticCode>::const_iterator it=micros.begin(),
626 it_end=micros.end(); it!=it_end; it++) {
627 elem.properties=*it;
628 newMorphData->push_back(elem);
629 }
630 }
631}
632
633bool CreateSpecificEntity::shouldRemoveInitial(
634 LinguisticGraphVertex /*src*/,
635 LinguisticGraphVertex /*tgt*/,
636 const RecognizerMatch& match) const
637{
638#ifdef DEBUG_LP
639 SELOGINIT;
640#endif
641 if (match.size() == 1)
642 {
643 return true;
644 }
645 const LinguisticAnalysisStructure::AnalysisGraph& graph = *(match.getGraph());
646
647 std::set< LinguisticGraphVertex > matchVertices;
648 Automaton::RecognizerMatch::const_iterator matchIt, matchIt_end;
649
650 matchIt = match.begin();
651 matchIt_end = match.end();
652 for (; matchIt != matchIt_end; matchIt++)
653 {
654 matchVertices.insert((*matchIt).m_elem.first);
655 }
656
657 matchIt = match.begin();
658 matchIt_end = match.end()-1;
659 if (boost::out_degree((*matchIt).m_elem.first,*graph.getGraph()) > 1)
660 {
661#ifdef DEBUG_LP
662 LDEBUG << "removing edge (" << (*matchIt).m_elem.first << "," << (*(matchIt+1)).m_elem.first << ") because there is more than one path from the first vertex of the match.";
663#endif
664 boost::remove_edge((*matchIt).m_elem.first,(*(matchIt+1)).m_elem.first, *const_cast<LinguisticGraph*>(graph.getGraph()));
665 return false;
666 }
667 matchIt++;
668 for (; matchIt != matchIt_end; matchIt++)
669 {
670 if (boost::out_degree((*matchIt).m_elem.first,*graph.getGraph()) > 1)
671 {
672 LinguisticGraphOutEdgeIt outIt, outIt_end;
673 boost::tie (outIt, outIt_end) = boost::out_edges((*matchIt).m_elem.first, *graph.getGraph());
674 for (; outIt != outIt_end; outIt++)
675 {
676 if (matchVertices.find(source(*outIt, *graph.getGraph())) != matchVertices.end())
677 {
678// LDEBUG << "removing initial edge " << *outIt;
679// boost::remove_edge(*outIt, *const_cast<LinguisticGraph*>(graph.getGraph()));
680 break;
681 }
682 }
683 return false;
684 }
685 }
686
687 return true;
688}
689
690bool CreateSpecificEntity::shouldRemoveFinal(
691 LinguisticGraphVertex /*src*/,
692 LinguisticGraphVertex /*tgt*/,
693 const RecognizerMatch& match) const
694{
695#ifdef DEBUG_LP
696 SELOGINIT;
697#endif
698 if (match.size() == 1)
699 {
700 return true;
701 }
702 const LinguisticAnalysisStructure::AnalysisGraph& graph = *(match.getGraph());
703
704 std::set< LinguisticGraphVertex > matchVertices;
705 Automaton::RecognizerMatch::const_iterator matchIt, matchIt_end;
706
707 matchIt = match.begin();
708 matchIt_end = match.end();
709 for (; matchIt != matchIt_end; matchIt++)
710 {
711 matchVertices.insert((*matchIt).m_elem.first);
712 }
713
714 matchIt = match.begin()+1;
715 matchIt_end = match.end();
716 for (; matchIt != matchIt_end; matchIt++)
717 {
718 if (boost::in_degree((*matchIt).m_elem.first,*graph.getGraph()) > 1)
719 {
720 LinguisticGraphInEdgeIt inIt, inIt_end;
721 boost::tie (inIt, inIt_end) = boost::in_edges((*matchIt).m_elem.first, *graph.getGraph());
722 for (; inIt != inIt_end; inIt++)
723 {
724 if (matchVertices.find(source(*inIt, *graph.getGraph())) != matchVertices.end())
725 {
726#ifdef DEBUG_LP
727 LDEBUG << "removing final edge " << source(*inIt, *graph.getGraph()) << " -> " << target(*inIt, *graph.getGraph());
728#endif
729 boost::remove_edge(*inIt, *const_cast<LinguisticGraph*>(graph.getGraph()));
730 break;
731 }
732 }
733 return false;
734 }
735 }
736
737 return true;
738}
739
740
741//----------------------------------------------------------------------------------------
742// SetEntityFeature : add a given feature to the recognized entity
743// we do not have direct access to the RecognizerMatch of the entity when calling this function
744// (called during the matching process) => hence, store features in an AnalysisData and use
745// this Data in normalization functions or CreateSpecificEntity function to get the features.
746// Use already existing RecognizerData (no need for another Data).
747// CAREFUL: the features must be cleaned after use: explicit call to clearFeatures in case of
748// matching failure must be added in the rule.
749
751 const LimaString& complement):
752ConstraintFunction(language,complement),
753m_featureName(""),
754m_featureType(QVariant::String)
755{
756 if (complement.size()) {
757 QStringList complementElements = complement.split(":");
758 m_featureName=complementElements.front().toUtf8().constData();
759 complementElements.pop_front();
760 if (!complementElements.empty()) {
761 const QString& complementType = complementElements.front();
762 m_featureType = QVariant::nameToType(complementType.toUtf8().constData());
763 if (m_featureType != QVariant::Invalid) {
764 if (complementType == "int") {
765 m_featureType = QVariant::Int;
766 }
767 else if (complementType == "double") {
768 m_featureType = QVariant::Double;
769 }
770 else {
771 m_featureType = QVariant::String;
772 }
773 }
774 }
775 }
776}
777
778bool SetEntityFeature::
779operator()(const LinguisticAnalysisStructure::AnalysisGraph& graph,
780 const LinguisticGraphVertex& vertex,
781 AnalysisContent& analysis) const
782{
783#ifdef DEBUG_LP
784 SELOGINIT;
785 LDEBUG << "SetEntityFeature:: (one argument) start... ";
786 LDEBUG << "SetEntityFeature::(feature:" << m_featureName << ", vertex:" << vertex << ")";
787#endif
788 // get RecognizerData: the data in which the features are stored
789 auto recoData = std::dynamic_pointer_cast<RecognizerData>(analysis.getData("RecognizerData"));
790 if (recoData==0) {
791 SELOGINIT;
792 LERROR << "SetEntityFeature:: Error: missing RecognizerData";
793 return false;
794 }
795
796 // get string from the vertex and associate it to the feature
797
798 // get string from the vertex :
799 // @todo: if named entity, take normalized string, otherwise take lemma
800 LimaString featureValue;
801 Token* token=get(vertex_token,*(graph.getGraph()),vertex);
802
803 if (token == nullptr)
804 throw LimaException("Token is equal to nullptr");
805
806 if (token!=0) {
807 featureValue=token->stringForm();
808 }
809 switch (m_featureType) {
810 case QVariant::String:
811#ifdef DEBUG_LP
812 LDEBUG << "SetEntityFeature:: recoData->setEntityFeature(feature:" << m_featureName << ", featureValue:" << featureValue<< ")";
813#endif
814 recoData->setEntityFeature(m_featureName,featureValue);
815 break;
816 case QVariant::Int:
817#ifdef DEBUG_LP
818 LDEBUG << "SetEntityFeature:: recoData->setEntityFeature(feature:" << m_featureName << ", featureValue:" << featureValue.toInt() << ")";
819#endif
820 recoData->setEntityFeature(m_featureName,featureValue.toInt());
821 break;
822 case QVariant::Double:
823#ifdef DEBUG_LP
824 LDEBUG << "SetEntityFeature:: recoData->setEntityFeature(feature:" << m_featureName << ", featureValue:" << featureValue.toDouble() << ")";
825#endif
826 recoData->setEntityFeature(m_featureName,featureValue.toDouble());
827 break;
828 default:
829 recoData->setEntityFeature(m_featureName,featureValue);
830 }
831 uint64_t pos = (int64_t)(token->position());
832 uint64_t len = (int64_t)(token->length());
833 Automaton::EntityFeatures& features = recoData->getEntityFeatures();
834
835 std::vector<EntityFeature>::iterator featureIt =
836 features.find(m_featureName);
837 if( featureIt != recoData->getEntityFeatures().end() )
838 {
839 featureIt->setPosition(pos);
840 featureIt->setLength(len);
841 }
842
843 return true;
844}
845
846bool SetEntityFeature::
847operator()(const LinguisticAnalysisStructure::AnalysisGraph& graph,
848 const LinguisticGraphVertex& v1,
849 const LinguisticGraphVertex& v2,
850 AnalysisContent& analysis) const
851{
852#ifdef DEBUG_LP
853 SELOGINIT;
854 LDEBUG << "SetEntityFeature:: (two arguments) start... ";
855 LDEBUG << "SetEntityFeature::(feature:" << m_featureName << ", v1:" << v1 << ", v2:" << v2 << ")";
856#endif
857
858 // get RecognizerData: the data in which the features are stored
859 auto recoData = std::dynamic_pointer_cast<RecognizerData>(analysis.getData("RecognizerData"));
860 if (recoData==0) {
861 SELOGINIT;
862 LERROR << "SetEntityFeature:: Error: missing RecognizerData";
863 return false;
864 }
865 // get string from the set of vertices between v1 and v2
866 // @todo: if named entity, take normalized string, otherwise take lemma
867 LimaString featureValue;
868 const LinguisticGraph& lGraph = *(graph.getGraph());
869
870 // (some code borrowed from SpecificEntitiesXmlLogger::process)
871 // assert v2 follows v1 within a path composed with a direct sequence of out_edges
872 // assert also there exist no ambiguities in the graph.
873 std::queue<LinguisticGraphVertex> toVisit;
874 std::set<LinguisticGraphVertex> visited;
875 toVisit.push(v1);
876 uint64_t pos = UNDEFPOSITION;
877 uint64_t len = UNDEFLENGTH;
878
879 LinguisticGraphOutEdgeIt outItr,outItrEnd;
880 unsigned int nbEdges(0);
881 while (!toVisit.empty()) {
882 LinguisticGraphVertex v=toVisit.front();
883 toVisit.pop();
884 if (v != v2) {
885 for (boost::tie(outItr,outItrEnd)=out_edges(v,lGraph); outItr!=outItrEnd; outItr++)
886 {
887 LinguisticGraphVertex next=target(*outItr,lGraph);
888 if (visited.find(next)==visited.end())
889 {
890 visited.insert(next);
891 toVisit.push(next);
892 nbEdges++;
893 }
894 }
895 }
896 if( nbEdges > 1 ) {
897 SELOGINIT;
898 LWARN << "SetEntityFeature:: Warning: ambiguities in graph";
899 }
900
901 Token* token=get(vertex_token,lGraph,v);
902 if (v == v1) {
903 pos = (int64_t)(token->position());
904 }
905 if (v == v2) {
906 if( pos != UNDEFPOSITION )
907 len = (int64_t)(token->position()) - pos + 1 + (int64_t)(token->length());
908 }
909 // @ todo: add separator, check non standard cases where separator is no whitespace.
910 // see RecognizeMatch::getString()
911 featureValue.append( token->stringForm());
912 }
913
914 switch (m_featureType) {
915 case QVariant::String:
916 recoData->setEntityFeature(m_featureName,featureValue);
917 break;
918 case QVariant::Int:
919 recoData->setEntityFeature(m_featureName,featureValue.toInt());
920 break;
921 case QVariant::Double:
922 recoData->setEntityFeature(m_featureName,featureValue.toDouble());
923 break;
924 default:
925 recoData->setEntityFeature(m_featureName,featureValue);
926 }
927 Automaton::EntityFeatures& features = recoData->getEntityFeatures();
928 std::vector<EntityFeature>::iterator featureIt =
929 features.find(m_featureName);
930 if( featureIt != recoData->getEntityFeatures().end() )
931 {
932 featureIt->setPosition(pos);
933 featureIt->setLength(len);
934 }
935 return true;
936}
937
938//----------------------------------------------------------------------------------------
939// AddEntityFeatureAsEntity : assert the vertex is a named entity.
940// Add it to the list of components as an embeded entity (the list is used to create the link
941// "holds" between the annotation of the embeded and the embedding entity.
942// Remember the embedding entity is no yet created.
943
945 const LimaString& complement):
946ConstraintFunction(language,complement),
947m_featureName(),
948m_type()
949{
950 if (complement.size()) {
951 QStringList complementElements = complement.split(":");
952 m_featureName=complementElements.front().toUtf8().constData();
953 complementElements.pop_front();
954 if (!complementElements.empty()) {
955#ifdef DEBUG_LP
956 SELOGINIT;
957 LERROR << "AddEntityFeatureAsEntity::AddEntityFeatureAsEntity(): no type specification authorized for the feature ("
958 << complementElements << ") the feature type is the type of the entity";
959#endif
960 }
961 }
962}
963
964bool AddEntityFeatureAsEntity::
965operator()(const LinguisticAnalysisStructure::AnalysisGraph& /* unused graph */,
966 const LinguisticGraphVertex& vertex,
967 AnalysisContent& analysis) const
968{
969#ifdef DEBUG_LP
970 SELOGINIT;
971 LDEBUG << "AddEntityFeatureAsEntity:: (one argument) start... ";
972 LDEBUG << "AddEntityFeatureAsEntity::(feature:" << m_featureName << ", vertex:" << vertex << ")";
973#endif
974 // get RecognizerData: the data in which the features are stored
975 auto recoData = std::dynamic_pointer_cast<RecognizerData>(analysis.getData("RecognizerData"));
976 if (recoData==0) {
977 SELOGINIT;
978 LERROR << "AddEntityFeatureAsEntity:: Error: missing RecognizerData";
979 return false;
980 }
981 // add the vertex to the list of embeded named entities
982 recoData->addVertexAsEmbededEntity(vertex);
983 return true;
984}
985
986//----------------------------------------------------------------------------------------
987// AddEntityFeature : add a value for a given feature to the recognized entity
988// we do not have direct access to the RecognizerMatch of the entity when calling this function
989// (called during the matching process) => hence, store features in an AnalysisData and use
990// this Data in normalization functions or CreateSpecificEntity function to get the features.
991// Use already existing RecognizerData (no need for another Data).
992// CAREFUL: the features must be cleaned after use: explicit call to clearFeatures in case of
993// matching failure must be added in the rule.
994
996 const LimaString& complement):
997ConstraintFunction(language,complement),
998m_featureName(""),
999m_featureType(QVariant::String)
1000{
1001 if (complement.size()) {
1002 QStringList complementElements = complement.split(":");
1003 m_featureName=complementElements.front().toUtf8().constData();
1004 complementElements.pop_front();
1005 if (!complementElements.empty()) {
1006 const QString& complementType = complementElements.front();
1007 m_featureType = QVariant::nameToType(complementType.toUtf8().constData());
1008 if (m_featureType != QVariant::Invalid) {
1009 if (complementType == "int") {
1010 m_featureType = QVariant::Int;
1011 }
1012 else if (complementType == "double") {
1013 m_featureType = QVariant::Double;
1014 }
1015 else {
1016 m_featureType = QVariant::String;
1017 }
1018 }
1019 }
1020 }
1021}
1022
1023bool AddEntityFeature::
1024operator()(const LinguisticAnalysisStructure::AnalysisGraph& graph,
1025 const LinguisticGraphVertex& vertex,
1026 AnalysisContent& analysis) const
1027{
1028#ifdef DEBUG_LP
1029 SELOGINIT;
1030 LDEBUG << "AddEntityFeature:: (one argument) start... ";
1031 LDEBUG << "AddEntityFeature::(feature:" << m_featureName << ", vertex:" << vertex << ")";
1032#endif
1033 // get RecognizerData: the data in which the features are stored
1034 auto recoData = std::dynamic_pointer_cast<RecognizerData>(analysis.getData("RecognizerData"));
1035 if (recoData==0) {
1036 SELOGINIT;
1037 LERROR << "AddEntityFeature:: Error: missing RecognizerData";
1038 return false;
1039 }
1040
1041 // get string from the vertex and associate it to the feature
1042
1043 // get string from the vertex :
1044 // @todo: if named entity, take normalized string, otherwise take lemma
1045 LimaString featureValue;
1046 Token* token=get(vertex_token,*(graph.getGraph()),vertex);
1047
1048 if (token == nullptr)
1049 throw LimaException("Token is equal to nullptr");
1050
1051 if (token!=0) {
1052 featureValue=token->stringForm();
1053 }
1054 switch (m_featureType) {
1055 case QVariant::String:
1056#ifdef DEBUG_LP
1057 LDEBUG << "AddEntityFeature:: recoData->addEntityFeature(feature:" << m_featureName << ", featureValue:" << featureValue<< ")";
1058#endif
1059 recoData->addEntityFeature(m_featureName,featureValue);
1060 break;
1061 case QVariant::Int:
1062#ifdef DEBUG_LP
1063 LDEBUG << "AddEntityFeature:: recoData->addEntityFeature(feature:" << m_featureName << ", featureValue:" << featureValue.toInt()<< ")";
1064#endif
1065 recoData->addEntityFeature(m_featureName,featureValue.toInt());
1066 break;
1067 case QVariant::Double:
1068#ifdef DEBUG_LP
1069 LDEBUG << "AddEntityFeature:: recoData->addEntityFeature(feature:" << m_featureName << ", featureValue:" << featureValue.toDouble()<< ")";
1070#endif
1071 recoData->addEntityFeature(m_featureName,featureValue.toDouble());
1072 break;
1073 default:
1074 recoData->addEntityFeature(m_featureName,featureValue);
1075 }
1076 uint64_t pos = (int64_t)(token->position());
1077 uint64_t len = (int64_t)(token->length());
1078 Automaton::EntityFeatures& features = recoData->getEntityFeatures();
1079
1080 std::vector<EntityFeature>::iterator featureIt =
1081 features.findLast(m_featureName);
1082 if( featureIt != recoData->getEntityFeatures().end() )
1083 {
1084 featureIt->setPosition(pos);
1085 featureIt->setLength(len);
1086 }
1087
1088 return true;
1089}
1090
1091bool AddEntityFeature::
1092operator()(const LinguisticAnalysisStructure::AnalysisGraph& graph,
1093 const LinguisticGraphVertex& v1,
1094 const LinguisticGraphVertex& v2,
1095 AnalysisContent& analysis) const
1096{
1097#ifdef DEBUG_LP
1098 SELOGINIT;
1099 LDEBUG << "AddEntityFeature:: (two arguments) start... ";
1100 LDEBUG << "AddEntityFeature::(feature:" << m_featureName << ", v1:" << v1 << ", v2:" << v2 << ")";
1101#endif
1102
1103 // get RecognizerData: the data in which the features are stored
1104 auto recoData = std::dynamic_pointer_cast<RecognizerData>(analysis.getData("RecognizerData"));
1105 if (recoData==0) {
1106 SELOGINIT;
1107 LERROR << "AddEntityFeature:: Error: missing RecognizerData";
1108 return false;
1109 }
1110 // get string from the set of vertices between v1 and v2
1111 // @todo: if named entity, take normalized string, otherwise take lemma
1112 LimaString featureValue;
1113 const LinguisticGraph& lGraph = *(graph.getGraph());
1114
1115 // (some code borrowed from SpecificEntitiesXmlLogger::process)
1116 // assert v2 follows v1 within a path composed with a direct sequence of out_edges
1117 // assert also there exist no ambiguities in the graph.
1118 std::queue<LinguisticGraphVertex> toVisit;
1119 std::set<LinguisticGraphVertex> visited;
1120 toVisit.push(v1);
1121 uint64_t pos = UNDEFPOSITION;
1122 uint64_t len = UNDEFLENGTH;
1123
1124 LinguisticGraphOutEdgeIt outItr,outItrEnd;
1125 unsigned int nbEdges(0);
1126 while (!toVisit.empty()) {
1127 LinguisticGraphVertex v=toVisit.front();
1128 toVisit.pop();
1129 if (v != v2) {
1130 for (boost::tie(outItr,outItrEnd)=out_edges(v,lGraph); outItr!=outItrEnd; outItr++)
1131 {
1132 LinguisticGraphVertex next=target(*outItr,lGraph);
1133 if (visited.find(next)==visited.end())
1134 {
1135 visited.insert(next);
1136 toVisit.push(next);
1137 nbEdges++;
1138 }
1139 }
1140 }
1141 if( nbEdges > 1 ) {
1142 SELOGINIT;
1143 LWARN << "AddEntityFeature:: Warning: ambiguities in graph";
1144 }
1145
1146 Token* token=get(vertex_token,lGraph,v);
1147 if (v == v1) {
1148 pos = (int64_t)(token->position());
1149 }
1150 if (v == v2) {
1151 if( pos != UNDEFPOSITION )
1152 len = (int64_t)(token->position()) - pos + 1 + (int64_t)(token->length());
1153 }
1154 // @ todo: add separator, check non standard cases where separator is no whitespace.
1155 // see RecognizeMatch::getString()
1156 featureValue.append( token->stringForm());
1157 }
1158
1159 switch (m_featureType) {
1160 case QVariant::String:
1161 recoData->setEntityFeature(m_featureName,featureValue);
1162 break;
1163 case QVariant::Int:
1164 recoData->setEntityFeature(m_featureName,featureValue.toInt());
1165 break;
1166 case QVariant::Double:
1167 recoData->setEntityFeature(m_featureName,featureValue.toDouble());
1168 break;
1169 default:
1170 recoData->setEntityFeature(m_featureName,featureValue);
1171 }
1172 Automaton::EntityFeatures& features = recoData->getEntityFeatures();
1173 std::vector<EntityFeature>::iterator featureIt =
1174 features.findLast(m_featureName);
1175 if( featureIt != recoData->getEntityFeatures().end() )
1176 {
1177 featureIt->setPosition(pos);
1178 featureIt->setLength(len);
1179 }
1180 return true;
1181}
1182
1183//----------------------------------------------------------------------------------------
1184// AppendEntityFeature : add a given feature to the recognized entity or append the
1185// value of a given feature if it already exists.
1186// Same remark as for SetEntityFeature about the relation with RecognizerMatch
1187// and RecognizerData.
1188
1190 const LimaString& complement):
1191ConstraintFunction(language,complement),
1192m_featureName(""),
1193m_featureType(QVariant::String)
1194{
1195 if (complement.size()) {
1196 QStringList complementElements = complement.split(":");
1197 m_featureName=complementElements.front().toUtf8().constData();
1198 complementElements.pop_front();
1199 if (!complementElements.empty()) {
1200 const QString& complementType = complementElements.front();
1201 m_featureType = QVariant::nameToType(complementType.toUtf8().constData());
1202 if (m_featureType != QVariant::Invalid) {
1203 if (complementType == "int") {
1204 m_featureType = QVariant::Int;
1205 }
1206 else if (complementType == "double") {
1207 m_featureType = QVariant::Double;
1208 }
1209 else {
1210 m_featureType = QVariant::String;
1211 }
1212 }
1213 }
1214 }
1215}
1216
1217uint64_t AppendEntityFeature::minPos( const uint64_t pos1, const uint64_t pos2 ) const {
1218 if( pos1 == UNDEFPOSITION )
1219 return pos2;
1220 if( pos2 == UNDEFPOSITION )
1221 return pos1;
1222 if( pos1 < pos2 )
1223 return pos1;
1224 return pos2;
1225}
1226
1227uint64_t AppendEntityFeature::maxPos( const uint64_t pos1, const uint64_t pos2 ) const {
1228 if( pos1 == UNDEFPOSITION )
1229 return pos2;
1230 if( pos2 == UNDEFPOSITION )
1231 return pos1;
1232 if( pos1 > pos2 )
1233 return pos1;
1234 return pos2;
1235}
1236
1239 const LinguisticGraphVertex& vertex,
1240 AnalysisContent& analysis) const
1241{
1242#ifdef DEBUG_LP
1243 SELOGINIT;
1244 LDEBUG << "AppendEntityFeature::() (one argument) start... ";
1245 LDEBUG << "AppendEntityFeature::() feature:" << m_featureName << ", vertex:" << vertex << ")";
1246#endif
1247 // get RecognizerData: the data in which the features are stored
1248 auto recoData = std::dynamic_pointer_cast<RecognizerData>(analysis.getData("RecognizerData"));
1249 if (recoData==0) {
1250 SELOGINIT;
1251 LERROR << "AppendEntityFeature::() Error: missing RecognizerData";
1252 return false;
1253 }
1254
1255 // get position/length from feature
1256 // position is min of position.
1257 // length is span from min of position
1258 // to max of position + augmented with length of last element.
1259 uint64_t pos = UNDEFPOSITION;
1260 uint64_t len = UNDEFLENGTH;
1261 Automaton::EntityFeatures& features = recoData->getEntityFeatures();
1262 std::vector<EntityFeature>::iterator featureIt = features.find(m_featureName);
1263 Token* token=get(vertex_token,*(graph.getGraph()),vertex);
1264// Token* token=get(vertex_token,lGraph,vertex);
1265 // if feature already exists
1266 if( featureIt != recoData->getEntityFeatures().end() )
1267 {
1268 pos = minPos( featureIt->getPosition(), (int64_t)(token->position()) );
1269#ifdef DEBUG_LP
1270 LDEBUG << "AppendEntityFeature::() minPos=" << pos;
1271#endif
1272 uint64_t maxPos1 = UNDEFPOSITION;
1273 if( featureIt->getPosition() != UNDEFPOSITION ) {
1274 maxPos1 = featureIt->getPosition() + featureIt->getLength();
1275 }
1276#ifdef DEBUG_LP
1277 LDEBUG << "AppendEntityFeature::() maxPos1=" << maxPos1;
1278 #endif
1279 uint64_t maxPos2 = (int64_t)(token->position()) + (int64_t)(token->length());
1280#ifdef DEBUG_LP
1281 LDEBUG << "AppendEntityFeature::() maxPos2=" << maxPos2;
1282#endif
1283 uint64_t maxPos3 = maxPos( maxPos1, maxPos2 );
1284#ifdef DEBUG_LP
1285 LDEBUG << "AppendEntityFeature::() maxPos3=" << maxPos3;
1286#endif
1287 len = maxPos3 - pos;
1288#ifdef DEBUG_LP
1289 LDEBUG << "AppendEntityFeature::() len=" << len;
1290#endif
1291 }
1292 else {
1293 pos = (int64_t)(token->position());
1294 len = (int64_t)(token->length());
1295 }
1296
1297 // get string from the vertex and associate it to the feature
1298
1299 // get string from the vertex :
1300 // @todo: if named entity, take normalized string, otherwise take lemma
1301 LimaString featureValue;
1302 if (token!=0) {
1303 featureValue=token->stringForm();
1304 }
1305 switch (m_featureType) {
1306 case QVariant::String:
1307 recoData->appendEntityFeature(m_featureName,featureValue);
1308 break;
1309 case QVariant::Int:
1310 recoData->appendEntityFeature(m_featureName,featureValue.toInt());
1311 break;
1312 case QVariant::Double:
1313 recoData->appendEntityFeature(m_featureName,featureValue.toDouble());
1314 break;
1315 default:
1316 recoData->appendEntityFeature(m_featureName,featureValue);
1317 }
1318 featureIt = features.find(m_featureName);
1319#ifdef DEBUG_LP
1320 LDEBUG << "AppendEntityFeature::() pos before = ("
1321 << featureIt->getPosition() << ","
1322 << featureIt->getLength() << ")";
1323#endif
1324 featureIt->setPosition(pos);
1325 featureIt->setLength(len);
1326#ifdef DEBUG_LP
1327 LDEBUG << "AppendEntityFeature::() pos after = (" << pos << "," << len << ")";
1328#endif
1329
1330 return true;
1331}
1332
1333// clear stored entity features, added by the SetEntityFeature function
1335const LimaString& complement):
1336ConstraintFunction(language,complement)
1337{
1338}
1340operator()(AnalysisContent& analysis) const
1341{
1342 // get RecognizerData: the data in which the features are stored
1343 auto recoData = std::dynamic_pointer_cast<RecognizerData>(analysis.getData("RecognizerData"));
1344 if (recoData!=0) {
1345 recoData->clearEntityFeatures();
1346 }
1347 return true;
1348}
1349
1350
1351//----------------------------------------------------
1352// Normalize entity using stored features
1354const LimaString& complement):
1355ConstraintFunction(language,complement)
1356{
1357}
1360{
1361 // get stored features in recognizerData
1362 auto recoData = std::dynamic_pointer_cast<RecognizerData>(analysis.getData("RecognizerData"));
1363 if (recoData == nullptr) {
1364 SELOGINIT;
1365 LERROR << "NormalizeEntity:: Error: missing RecognizerData";
1366 return false;
1367 }
1368 // assign stored features to RecognizerMatch features (preserving DEFAULT_ATTIBUTE)
1369 //match.features()=recoData->getEntityFeatures();
1370 const auto& features = recoData->getEntityFeatures();
1371 for (auto it = features.cbegin(); it != features.cend(); ++it) {
1372 match.features().addFeature(it->getName(),it->getValue());
1373 if( it->getPosition() != UNDEFPOSITION ) {
1374 auto featureIt = match.features().findLast(it->getName());
1375 (*featureIt).setPosition(it->getPosition());
1376 (*featureIt).setLength(it->getLength());
1377 }
1378 }
1379 // must clear the stored features, once they are used (otherwise, will be kept for next entity)
1380 recoData->clearEntityFeatures();
1381 return true;
1382}
1383
1384} // SpecificEntities
1385} // LinguisticProcessing
1386} // Lima
This file is the main header file for the data related to annotation graphs.
DependencyGraph::vertex_descriptor DependencyGraphVertex
#define UNDEFLENGTH
#define UNDEFPOSITION
#define LWARN
Definition LimaCommon.h:160
#define LIMA_EXCEPTION(X)
This macro writes the message X to a previously configured error stream before throwing a LimaExcepti...
Definition LimaCommon.h:293
#define LDEBUG
Definition LimaCommon.h:157
#define LERROR
Definition LimaCommon.h:161
LinguisticGraph::in_edge_iterator LinguisticGraphInEdgeIt
boost::property_map< LinguisticGraph, vertex_data_t >::type VertexDataPropertyMap
boost::graph_traits< LinguisticGraph >::edge_descriptor LinguisticGraphEdge
typedefs to simplify the access to various graphs elements
boost::property_map< LinguisticGraph, vertex_token_t >::type VertexTokenPropertyMap
@ vertex_token
LinguisticGraph::vertex_descriptor LinguisticGraphVertex
@ vertex_data
LinguisticGraph::out_edge_iterator LinguisticGraphOutEdgeIt
boost::adjacency_list< boost::vecS, boost::vecS, boost::bidirectionalS, LinguisticVertexProperties > LinguisticGraph
Property to identify the chains in the graph.
#define SELOGINIT
#define SetEntityFeatureId
#define CreateSpecificEntityId
#define isAlphaPossessiveId
#define NormalizeEntityId
#define ClearEntityFeaturesId
#define AddEntityFeatureId
#define isASpecificEntityId
#define AppendEntityFeatureId
#define AddEntityFeatureAsEntityId
Data used for the syntactic analyzis of texts.
Holds all data that pass through the ProcessUnits Analysis data are shared pointers,...
std::shared_ptr< AnalysisData > getData(const QString &id)
return AnalysisData by id
This class allows to convert any object into an annotation by inheritance.
Holds linguistic data for one language.
const LimaString & getEntityGroupName(EntityGroupId id) const
const FsaStringsPool & stringsPool(MediaId med) const
const MediaData & mediaData(MediaId media) const
EntityType getEntityType(const LimaString &entityName) const
entity types manager
Provide tools to manage a specific property.
LinguisticCode getPropertyValue(const std::string &symbolicValue) const
Get the coded property value from the symbolic value.
The main LIMA exception class.
Definition LimaCommon.h:262
virtual const char * what() const override
Definition LimaCommon.h:280
ConstraintFunction(MediaId language, const LimaString &complement=LimaString())
a list of generic features: each feature is unique (only one feature for a name)
EntityFeatures::const_iterator findLast(const std::string &featureName) const
void addFeature(const std::string &name, const ValueType &value)
EntityFeatures::const_iterator find(const std::string &featureName) const
const Common::MediaticData::EntityType & getType() const
const LinguisticAnalysisStructure::AnalysisGraph * getGraph() const
An AnalysisData containing a LinguisticGraph with a language and an id.
const LinguisticGraph * getGraph(void) const
Returns the underlying graph structure.
void setStatus(const TStatus &status)
Set the TStatus of a token.
Definition Token.h:100
AddEntityFeatureAsEntity(MediaId language, const LimaString &complement=LimaString())
AddEntityFeature(MediaId language, const LimaString &complement=LimaString())
uint64_t maxPos(const uint64_t pos1, const uint64_t pos2) const
bool operator()(const LinguisticAnalysisStructure::AnalysisGraph &graph, const LinguisticGraphVertex &vertex, AnalysisContent &analysis) const override
unary constraint function : the constraint only applies on one vertices in the graph (the graph is al...
uint64_t minPos(const uint64_t pos1, const uint64_t pos2) const
AppendEntityFeature(MediaId language, const LimaString &complement=LimaString())
ClearEntityFeatures(MediaId language, const LimaString &complement=LimaString())
bool operator()(AnalysisContent &analysis) const override
zero-ary constraint function : applies the function without a vertex indication (used for actions,...
CreateSpecificEntity(MediaId language, const LimaString &complement=LimaString())
bool operator()(Automaton::RecognizerMatch &match, AnalysisContent &analysis) const override
Definition of a function suitable to be used as a dumper for specific entities annotations of an anno...
NormalizeEntity(MediaId language, const LimaString &complement=LimaString())
bool operator()(Automaton::RecognizerMatch &match, AnalysisContent &analysis) const override
zero-ary constraint function : applies the function without a vertex indication (used for actions,...
SetEntityFeature(MediaId language, const LimaString &complement=LimaString())
A representation of a specific entity to store in the annotation graph.
void dump(std::ostream &os) const
The functions that dumps a SpecificEntityAnnotation on an output stream.
bool operator()(const LinguisticAnalysisStructure::AnalysisGraph &graph, const LinguisticGraphVertex &v, AnalysisContent &analysis) const override
unary constraint function : the constraint only applies on one vertices in the graph (the graph is al...
isASpecificEntity(MediaId language, const LimaString &complement=LimaString())
isAlphaPossessive(MediaId language, const LimaString &complement=LimaString())
bool operator()(const LinguisticAnalysisStructure::AnalysisGraph &graph, const LinguisticGraphVertex &v, AnalysisContent &analysis) const override
unary constraint function : the constraint only applies on one vertices in the graph (the graph is al...
static const MediaticData & single()
Definition Singleton.h:51
static MediaticData & changeable()
Definition Singleton.h:71
AnnotationGraph::vertex_descriptor AnnotationGraphVertex
std::string limastring2utf8stdstring(const Lima::LimaString &phrase, uint32_t size0)
Convert a wide string to a string , in dest up to size bytes.
LimaString utf8stdstring2limastring(const std::string &src)
ConstraintFunctionFactory< AddEntityFeatureAsEntity > AddEntityFeatureAsEntityFactory(AddEntityFeatureAsEntityId)
ConstraintFunctionFactory< AppendEntityFeature > AppendEntityFeatureFactory(AppendEntityFeatureId)
ConstraintFunctionFactory< ClearEntityFeatures > ClearEntityFeaturesFactory(ClearEntityFeaturesId)
ConstraintFunctionFactory< isAlphaPossessive > isAlphaPossessiveFactory(isAlphaPossessiveId)
ConstraintFunctionFactory< NormalizeEntity > NormalizeEntityFactory(NormalizeEntityId)
ConstraintFunctionFactory< CreateSpecificEntity > CreateSpecificEntityFactory(CreateSpecificEntityId)
ConstraintFunctionFactory< isASpecificEntity > isASpecificEntityFactory(isASpecificEntityId)
ConstraintFunctionFactory< SetEntityFeature > SetEntityFeatureFactory(SetEntityFeatureId)
ConstraintFunctionFactory< AddEntityFeature > AddEntityFeatureFactory(AddEntityFeatureId)
NAUTITIA.
QString LimaString
Definition LimaString.h:33