use of gate.Annotation in project gate-core by GateNLP.
the class TestXml method helperBuildMatchesMap.
// End of buildMatchesMap()
/**
* This is a helper metod. It scans an annotation set and adds the ID of the annotations
* which have the matches feature to the map.
* @param sourceAnnotSet The annotation set investigated
* @param aMap
*/
private void helperBuildMatchesMap(AnnotationSet sourceAnnotSet, Map<Integer, List<Integer>> aMap) {
for (Iterator<Annotation> it = sourceAnnotSet.iterator(); it.hasNext(); ) {
Annotation a = it.next();
FeatureMap aFeatMap = a.getFeatures();
// Skip those annotations who don't have features
if (aFeatMap == null)
continue;
// Extract the matches feat
@SuppressWarnings("unchecked") List<Integer> matchesVal = (List<Integer>) aFeatMap.get("matches");
if (matchesVal == null)
continue;
Integer id = a.getId();
aMap.put(id, matchesVal);
}
// End for
}
use of gate.Annotation in project gate-core by GateNLP.
the class LuceneDocument method getTokens.
/**
* This method given a GATE document and other required parameters, for each
* annotation of type indexUnitAnnotationType creates a separate list of
* baseTokens underlying in it.
*/
private List<Token>[] getTokens(gate.Document document, AnnotationSet inputAs, List<String> featuresToInclude, List<String> featuresToExclude, String baseTokenAnnotationType, AnnotationSet baseTokenSet, String indexUnitAnnotationType, AnnotationSet indexUnitSet, Set<String> indexedFeatures) {
boolean excludeFeatures = false;
boolean includeFeatures = false;
// features
if (!featuresToInclude.isEmpty()) {
includeFeatures = true;
} else if (!featuresToExclude.isEmpty()) {
excludeFeatures = true;
}
HashSet<OffsetGroup> unitOffsetsSet = new HashSet<OffsetGroup>();
if (indexUnitAnnotationType == null || indexUnitAnnotationType.trim().length() == 0 || indexUnitSet == null || indexUnitSet.size() == 0) {
// the index Unit Annotation Type is not specified
// therefore we consider the entire document as a single unit
OffsetGroup group = new OffsetGroup();
group.startOffset = 0L;
group.endOffset = document.getContent().size();
unitOffsetsSet.add(group);
} else {
Iterator<Annotation> iter = indexUnitSet.iterator();
while (iter.hasNext()) {
Annotation annotation = iter.next();
OffsetGroup group = new OffsetGroup();
group.startOffset = annotation.getStartNode().getOffset();
group.endOffset = annotation.getEndNode().getOffset();
unitOffsetsSet.add(group);
}
}
Set<String> allTypes = new HashSet<String>();
for (String aType : inputAs.getAllTypes()) {
if (aType.indexOf(".") > -1 || aType.indexOf("=") > -1 || aType.indexOf(";") > -1 || aType.indexOf(",") > -1) {
System.err.println("Annotations of type " + aType + " cannot be indexed as the type name contains one of the ., =, or ; character");
continue;
}
allTypes.add(aType);
}
if (baseTokenSet != null && baseTokenSet.size() > 0) {
allTypes.remove(baseTokenAnnotationType);
}
if (indexUnitSet != null && indexUnitSet.size() > 0)
allTypes.remove(indexUnitAnnotationType);
AnnotationSet toUseSet = new AnnotationSetImpl(document);
for (String type : allTypes) {
for (Annotation a : inputAs.get(type)) {
try {
toUseSet.add(a.getStartNode().getOffset(), a.getEndNode().getOffset(), a.getType(), a.getFeatures());
} catch (InvalidOffsetException ioe) {
throw new GateRuntimeException(ioe);
}
}
}
@SuppressWarnings({ "cast", "unchecked", "rawtypes" }) List<Token>[] toReturn = (List<Token>[]) new List[unitOffsetsSet.size()];
Iterator<OffsetGroup> iter = unitOffsetsSet.iterator();
int counter = 0;
while (iter.hasNext()) {
OffsetGroup group = iter.next();
List<Token> newTokens = new ArrayList<Token>();
List<Annotation> tokens = new ArrayList<Annotation>(toUseSet.getContained(group.startOffset, group.endOffset));
// add tokens from the baseTokenSet
if (baseTokenSet != null && baseTokenSet.size() != 0) {
tokens.addAll(baseTokenSet.getContained(group.startOffset, group.endOffset));
}
if (tokens.isEmpty())
return null;
Collections.sort(tokens, new OffsetComparator());
int position = -1;
for (int i = 0; i < tokens.size(); i++) {
byte inc = 1;
Annotation annot = tokens.get(i);
String type = annot.getType();
// if the feature is specified in featuresToExclude -exclude it
if (excludeFeatures && featuresToExclude.contains(type))
continue;
// exclude it
if (includeFeatures && !featuresToInclude.contains(type))
continue;
int startOffset = annot.getStartNode().getOffset().intValue();
int endOffset = annot.getEndNode().getOffset().intValue();
String text = document.getContent().toString().substring(startOffset, endOffset);
Token token1 = new Token(type, startOffset, endOffset, "*");
// we add extra info of position
if (i > 0) {
if (annot.getStartNode().getOffset().longValue() == tokens.get(i - 1).getStartNode().getOffset().longValue()) {
token1.setPositionIncrement(0);
inc = 0;
}
}
position += inc;
token1.setPosition(position);
newTokens.add(token1);
if (!type.equals(baseTokenAnnotationType) || (annot.getFeatures().get("string") == null)) {
// we need to create one string feature for this
Token tk1 = new Token(text, startOffset, endOffset, type + ".string");
indexedFeatures.add(type + ".string");
tk1.setPositionIncrement(0);
tk1.setPosition(position);
newTokens.add(tk1);
}
// now find out the features and add them
FeatureMap features = annot.getFeatures();
Iterator<Object> fIter = features.keySet().iterator();
while (fIter.hasNext()) {
String type1 = fIter.next().toString();
// it
if (excludeFeatures && featuresToExclude.contains(type + "." + type1)) {
continue;
}
// exclude it
if (includeFeatures && !featuresToInclude.contains(type + "." + type1))
continue;
Object tempText = features.get(type1);
if (tempText == null)
continue;
String text1 = tempText.toString();
// we need to qualify the type names
// for each annotation type feature we add AT.Feature=="**" to be able
// to search for it
// to calculate stats
Token tempToken = new Token(text1, startOffset, endOffset, type + "." + type1);
indexedFeatures.add(type + "." + type1);
tempToken.setPositionIncrement(0);
tempToken.setPosition(position);
newTokens.add(tempToken);
Token onlyATFeature = new Token(type + "." + type1, startOffset, endOffset, "**");
onlyATFeature.setPosition(position);
onlyATFeature.setPositionIncrement(0);
newTokens.add(onlyATFeature);
}
}
toReturn[counter] = newTokens;
counter++;
}
return toReturn;
}
use of gate.Annotation in project gate-core by GateNLP.
the class AnnotationDiffGUI method initListeners.
protected void initListeners() {
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
new CloseAction().actionPerformed(null);
}
});
addWindowFocusListener(new WindowAdapter() {
@Override
public void windowGainedFocus(WindowEvent e) {
populateGUI();
}
});
keyDocCombo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
int keyDocSelectedIndex = keyDocCombo.getSelectedIndex();
if (keyDocSelectedIndex == -1) {
return;
}
Document newDoc = (Document) documents.get(keyDocSelectedIndex);
if (keyDoc == newDoc) {
return;
}
pairings.clear();
diffTableModel.fireTableDataChanged();
copyToTargetSetAction.setEnabled(false);
keyDoc = newDoc;
keySets = new ArrayList<AnnotationSet>();
List<String> keySetNames = new ArrayList<String>();
keySets.add(keyDoc.getAnnotations());
keySetNames.add("[Default set]");
if (keyDoc.getNamedAnnotationSets() != null) {
for (Object o : keyDoc.getNamedAnnotationSets().keySet()) {
String name = (String) o;
keySetNames.add(name);
keySets.add(keyDoc.getAnnotations(name));
}
}
keySetCombo.setModel(new DefaultComboBoxModel<String>(keySetNames.toArray(new String[keySetNames.size()])));
if (!keySetNames.isEmpty()) {
keySetCombo.setSelectedIndex(0);
if (resSetCombo.getItemCount() > 0) {
// find first annotation set with annotation type in common
for (int res = 0; res < resSetCombo.getItemCount(); res++) {
resSetCombo.setSelectedIndex(res);
for (int key = 0; key < keySetCombo.getItemCount(); key++) {
if (keyDoc.equals(resDoc) && resSetCombo.getItemAt(res).equals(keySetCombo.getItemAt(key))) {
// same document, skip it
continue;
}
keySetCombo.setSelectedIndex(key);
if (annTypeCombo.getSelectedItem() != null) {
break;
}
}
if (annTypeCombo.getSelectedItem() != null) {
break;
}
}
if (annTypeCombo.getSelectedItem() == null) {
statusLabel.setText("There is no annotation type in common.");
statusLabel.setForeground(Color.RED);
} else if (statusLabel.getText().equals("There is no annotation type in common.")) {
statusLabel.setText("The first annotation sets with" + " annotation type in common have been automatically selected.");
statusLabel.setForeground(Color.BLACK);
}
}
}
}
});
resDocCombo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
int resDocSelectedIndex = resDocCombo.getSelectedIndex();
if (resDocSelectedIndex == -1) {
return;
}
Document newDoc = (Document) documents.get(resDocSelectedIndex);
if (resDoc == newDoc) {
return;
}
resDoc = newDoc;
pairings.clear();
diffTableModel.fireTableDataChanged();
copyToTargetSetAction.setEnabled(false);
resSets = new ArrayList<AnnotationSet>();
List<String> resSetNames = new ArrayList<String>();
resSets.add(resDoc.getAnnotations());
resSetNames.add("[Default set]");
if (resDoc.getNamedAnnotationSets() != null) {
for (Object o : resDoc.getNamedAnnotationSets().keySet()) {
String name = (String) o;
resSetNames.add(name);
resSets.add(resDoc.getAnnotations(name));
}
}
resSetCombo.setModel(new DefaultComboBoxModel<String>(resSetNames.toArray(new String[resSetNames.size()])));
if (!resSetNames.isEmpty()) {
resSetCombo.setSelectedIndex(0);
if (keySetCombo.getItemCount() > 0) {
// find annotation sets with annotations in common
for (int res = 0; res < resSetCombo.getItemCount(); res++) {
resSetCombo.setSelectedIndex(res);
for (int key = 0; key < keySetCombo.getItemCount(); key++) {
if (keyDoc.equals(resDoc) && resSetCombo.getItemAt(res).equals(keySetCombo.getItemAt(key))) {
continue;
}
keySetCombo.setSelectedIndex(key);
if (annTypeCombo.getSelectedItem() != null) {
break;
}
}
if (annTypeCombo.getSelectedItem() != null) {
break;
}
}
if (annTypeCombo.getSelectedItem() == null) {
statusLabel.setText("There is no annotations in common.");
statusLabel.setForeground(Color.RED);
} else if (statusLabel.getText().equals("There is no annotations in common.")) {
statusLabel.setText("The first annotation sets with" + " annotations in common have been selected.");
statusLabel.setForeground(Color.BLACK);
}
}
}
}
});
/**
* This populates the types combo when set selection changes
*/
ActionListener setComboActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
keySet = keySets == null || keySets.isEmpty() ? null : keySets.get(keySetCombo.getSelectedIndex());
resSet = resSets == null || resSets.isEmpty() ? null : resSets.get(resSetCombo.getSelectedIndex());
Set<String> keyTypes = (keySet == null || keySet.isEmpty()) ? new HashSet<String>() : keySet.getAllTypes();
Set<String> resTypes = (resSet == null || resSet.isEmpty()) ? new HashSet<String>() : resSet.getAllTypes();
Set<String> types = new HashSet<String>(keyTypes);
types.retainAll(resTypes);
List<String> typesList = new ArrayList<String>(types);
Collections.sort(typesList);
annTypeCombo.setModel(new DefaultComboBoxModel<String>(typesList.toArray(new String[typesList.size()])));
if (typesList.size() > 0) {
annTypeCombo.setSelectedIndex(0);
diffAction.setEnabled(true);
doDiffBtn.setForeground((Color) UIManager.getDefaults().get("Button.foreground"));
doDiffBtn.setToolTipText((String) diffAction.getValue(Action.SHORT_DESCRIPTION));
} else {
diffAction.setEnabled(false);
doDiffBtn.setForeground((Color) UIManager.getDefaults().get("Button.disabledText"));
doDiffBtn.setToolTipText("Choose two annotation sets " + "that have at least one annotation type in common.");
}
}
};
keySetCombo.addActionListener(setComboActionListener);
resSetCombo.addActionListener(setComboActionListener);
someFeaturesBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
if (someFeaturesBtn.isSelected()) {
if (keySet == null || keySet.isEmpty() || annTypeCombo.getSelectedItem() == null)
return;
Iterator<Annotation> annIter = keySet.get((String) annTypeCombo.getSelectedItem()).iterator();
Set<String> featureSet = new HashSet<String>();
while (annIter.hasNext()) {
Annotation ann = annIter.next();
Map<Object, Object> someFeatures = ann.getFeatures();
if (someFeatures == null) {
continue;
}
for (Object feature : someFeatures.keySet()) {
featureSet.add((String) feature);
}
}
List<String> featureList = new ArrayList<String>(featureSet);
Collections.sort(featureList);
featureslistModel.clear();
Iterator<String> featIter = featureList.iterator();
int index = 0;
while (featIter.hasNext()) {
String aFeature = featIter.next();
featureslistModel.addElement(aFeature);
if (significantFeatures.contains(aFeature))
featuresList.addSelectionInterval(index, index);
index++;
}
int ret = JOptionPane.showConfirmDialog(AnnotationDiffGUI.this, new JScrollPane(featuresList), "Select features", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (ret == JOptionPane.OK_OPTION) {
significantFeatures.clear();
int[] selIdxs = featuresList.getSelectedIndices();
for (int selIdx : selIdxs) {
significantFeatures.add(featureslistModel.get(selIdx));
}
}
}
}
});
// enable/disable buttons according to the table state
diffTableModel.addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(javax.swing.event.TableModelEvent e) {
if (diffTableModel.getRowCount() > 0) {
htmlExportAction.setEnabled(true);
htmlExportBtn.setToolTipText((String) htmlExportAction.getValue(Action.SHORT_DESCRIPTION));
showDocumentAction.setEnabled(true);
showDocumentBtn.setToolTipText((String) showDocumentAction.getValue(Action.SHORT_DESCRIPTION));
} else {
htmlExportAction.setEnabled(false);
htmlExportBtn.setToolTipText("Use first the \"Compare\" button.");
showDocumentAction.setEnabled(false);
showDocumentBtn.setToolTipText("Use first the \"Compare\"" + " button then select an annotation in the table.");
}
}
});
// enable/disable buttons according to the table selection
diffTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
int row = diffTable.rowViewToModel(diffTable.getSelectedRow());
if (row == -1) {
showDocumentAction.setEnabled(false);
return;
}
AnnotationDiffer.Pairing pairing = pairings.get(row);
Annotation key = pairing.getKey();
Annotation response = pairing.getResponse();
int column = diffTable.convertColumnIndexToModel(diffTable.getSelectedColumn());
boolean enabled;
switch(column) {
case DiffTableModel.COL_KEY_START:
case DiffTableModel.COL_KEY_END:
case DiffTableModel.COL_KEY_STRING:
case DiffTableModel.COL_KEY_FEATURES:
enabled = (key != null);
break;
case DiffTableModel.COL_RES_START:
case DiffTableModel.COL_RES_END:
case DiffTableModel.COL_RES_STRING:
case DiffTableModel.COL_RES_FEATURES:
enabled = (response != null);
break;
default:
enabled = false;
}
showDocumentAction.setEnabled(enabled);
}
});
// enable/disable buttons according to the table selection
diffTable.getColumnModel().addColumnModelListener(new TableColumnModelListener() {
@Override
public void columnAdded(TableColumnModelEvent e) {
/* do nothing */
}
@Override
public void columnRemoved(TableColumnModelEvent e) {
/* do nothing */
}
@Override
public void columnMoved(TableColumnModelEvent e) {
/* do nothing */
}
@Override
public void columnMarginChanged(ChangeEvent e) {
/* do nothing */
}
@Override
public void columnSelectionChanged(ListSelectionEvent e) {
int row = diffTable.rowViewToModel(diffTable.getSelectedRow());
if (row == -1) {
showDocumentAction.setEnabled(false);
return;
}
AnnotationDiffer.Pairing pairing = pairings.get(row);
Annotation key = pairing.getKey();
Annotation response = pairing.getResponse();
int column = diffTable.convertColumnIndexToModel(diffTable.getSelectedColumn());
boolean enabled;
switch(column) {
case DiffTableModel.COL_KEY_START:
case DiffTableModel.COL_KEY_END:
case DiffTableModel.COL_KEY_STRING:
case DiffTableModel.COL_KEY_FEATURES:
enabled = (key != null);
break;
case DiffTableModel.COL_RES_START:
case DiffTableModel.COL_RES_END:
case DiffTableModel.COL_RES_STRING:
case DiffTableModel.COL_RES_FEATURES:
enabled = (response != null);
break;
default:
enabled = false;
}
showDocumentAction.setEnabled(enabled);
}
});
// inverse state of selected checkboxes when Space key is pressed
diffTable.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() != KeyEvent.VK_SPACE || !(diffTable.isColumnSelected(DiffTableModel.COL_KEY_COPY) || diffTable.isColumnSelected(DiffTableModel.COL_RES_COPY))) {
return;
}
// disable normal behavior of Space key in a table
e.consume();
int[] cols = { DiffTableModel.COL_KEY_COPY, DiffTableModel.COL_RES_COPY };
for (int col : cols) {
for (int row : diffTable.getSelectedRows()) {
if (diffTable.isCellSelected(row, col) && diffTable.isCellEditable(row, col)) {
diffTable.setValueAt(!(Boolean) diffTable.getValueAt(row, col), row, col);
diffTableModel.fireTableCellUpdated(row, col);
}
}
}
}
});
// context menu for the check boxes to easily change their state
diffTable.addMouseListener(new MouseAdapter() {
private JPopupMenu mousePopup;
JMenuItem menuItem;
@Override
public void mousePressed(MouseEvent e) {
showContextMenu(e);
}
@Override
public void mouseReleased(MouseEvent e) {
showContextMenu(e);
}
private void showContextMenu(MouseEvent e) {
int col = diffTable.convertColumnIndexToModel(diffTable.columnAtPoint(e.getPoint()));
if (!e.isPopupTrigger() || (col != DiffTableModel.COL_KEY_COPY && col != DiffTableModel.COL_RES_COPY)) {
return;
}
mousePopup = new JPopupMenu();
for (final String tick : new String[] { "Tick", "Untick" }) {
menuItem = new JMenuItem(tick + " selected check boxes");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
int keyCol = diffTable.convertColumnIndexToView(DiffTableModel.COL_KEY_COPY);
int responseCol = diffTable.convertColumnIndexToView(DiffTableModel.COL_RES_COPY);
for (int row = 0; row < diffTable.getRowCount(); row++) {
int rowModel = diffTable.rowViewToModel(row);
AnnotationDiffer.Pairing pairing = pairings.get(rowModel);
if (diffTable.isCellSelected(row, keyCol) && pairing.getKey() != null) {
diffTable.setValueAt(tick.equals("Tick"), row, keyCol);
}
if (diffTable.isCellSelected(row, responseCol) && pairing.getResponse() != null) {
diffTable.setValueAt(tick.equals("Tick"), row, responseCol);
}
}
diffTableModel.fireTableDataChanged();
}
});
mousePopup.add(menuItem);
}
mousePopup.addSeparator();
String[] types = new String[] { "correct", "partially correct", "missing", "false positives", "mismatch" };
String[] symbols = new String[] { "=", "~", "-?", "?-", "<>" };
for (int i = 0; i < types.length; i++) {
menuItem = new JMenuItem("Tick " + types[i] + " annotations");
final String symbol = symbols[i];
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
int matchCol = diffTable.convertColumnIndexToView(DiffTableModel.COL_MATCH);
for (int row = 0; row < diffTable.getRowCount(); row++) {
int rowModel = diffTable.rowViewToModel(row);
AnnotationDiffer.Pairing pairing = pairings.get(rowModel);
if (diffTable.getValueAt(row, matchCol).equals(symbol) && pairing.getKey() != null) {
keyCopyValueRows.set(diffTable.rowViewToModel(row), true);
} else if (diffTable.getValueAt(row, matchCol).equals(symbol) && pairing.getResponse() != null) {
resCopyValueRows.set(diffTable.rowViewToModel(row), true);
}
}
diffTableModel.fireTableDataChanged();
}
});
mousePopup.add(menuItem);
}
mousePopup.show(e.getComponent(), e.getX(), e.getY());
}
});
// revert to default name if the field is empty and lost focus
consensusASTextField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
String target = consensusASTextField.getText().trim();
if (target.length() == 0) {
consensusASTextField.setText("consensus");
}
if (keyDoc != null && keyDoc.getAnnotationSetNames().contains(target)) {
statusLabel.setText("Be careful, the annotation set " + target + " already exists.");
statusLabel.setForeground(Color.RED);
}
}
});
bottomTabbedPane.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (bottomTabbedPane.getSelectedIndex() == 0) {
diffTable.hideColumn(DiffTableModel.COL_KEY_COPY);
diffTable.hideColumn(DiffTableModel.COL_RES_COPY);
} else {
int middleIndex = Math.round(diffTable.getColumnCount() / 2);
diffTable.showColumn(DiffTableModel.COL_KEY_COPY, middleIndex);
diffTable.showColumn(DiffTableModel.COL_RES_COPY, middleIndex + 2);
diffTable.getColumnModel().getColumn(DiffTableModel.COL_KEY_COPY).setPreferredWidth(10);
diffTable.getColumnModel().getColumn(DiffTableModel.COL_RES_COPY).setPreferredWidth(10);
diffTable.doLayout();
}
}
});
// define keystrokes action bindings at the level of the main window
InputMap inputMap = ((JComponent) this.getContentPane()).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = ((JComponent) this.getContentPane()).getActionMap();
inputMap.put(KeyStroke.getKeyStroke("F1"), "Help");
actionMap.put("Help", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
new HelpAction().actionPerformed(null);
}
});
}
use of gate.Annotation in project gate-core by GateNLP.
the class AnnotationEditor method moveAnnotation.
/**
* Changes the span of an existing annotation by creating a new annotation
* with the same ID, type and features but with the new start and end offsets.
*
* @param set
* the annotation set
* @param oldAnnotation
* the annotation to be moved
* @param newStartOffset
* the new start offset
* @param newEndOffset
* the new end offset
*/
protected void moveAnnotation(AnnotationSet set, Annotation oldAnnotation, Long newStartOffset, Long newEndOffset) throws InvalidOffsetException {
// Moving is done by deleting the old annotation and creating a new one.
// If this was the last one of one type it would mess up the gui which
// "forgets" about this type and then it recreates it (with a different
// colour and not visible.
// In order to avoid this problem, we'll create a new temporary annotation.
Annotation tempAnn = null;
if (set.get(oldAnnotation.getType()).size() == 1) {
// create a clone of the annotation that will be deleted, to act as a
// placeholder
Integer tempAnnId = set.add(oldAnnotation.getStartNode(), oldAnnotation.getStartNode(), oldAnnotation.getType(), oldAnnotation.getFeatures());
tempAnn = set.get(tempAnnId);
}
Integer oldID = oldAnnotation.getId();
set.remove(oldAnnotation);
set.add(oldID, newStartOffset, newEndOffset, oldAnnotation.getType(), oldAnnotation.getFeatures());
Annotation newAnn = set.get(oldID);
// update the selection to the new annotation
getOwner().selectAnnotation(new AnnotationDataImpl(set, newAnn));
editAnnotation(newAnn, set);
// remove the temporary annotation
if (tempAnn != null)
set.remove(tempAnn);
owner.annotationChanged(newAnn, set, null);
}
use of gate.Annotation in project gate-core by GateNLP.
the class CorefEditor method featureMapUpdated.
/**
* Called when features are changed outside the co-refEditor
*/
@Override
public void featureMapUpdated() {
if (explicitCall)
return;
// we would first save the current settings
// 1. Current AnnotSet
// 2. Current AnnotType
// 3. ShowAnnotation Status
String currentAnnotSet = (String) annotSets.getSelectedItem();
String currentAnnotType = (String) annotTypes.getSelectedItem();
boolean currentShowAnnotationStatus = showAnnotations.isSelected();
// there is some change in the featureMap
Object matchesMapObject = document.getFeatures().get(ANNIEConstants.DOCUMENT_COREF_FEATURE_NAME);
if (matchesMapObject == null || !(matchesMapObject instanceof Map)) {
// no need to do anything
// and return
reinitAllVariables();
explicitCall = false;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// not sure why this is necessary but if we are going to do
// it then at least do it on the EDT to avoid a violation
annotSets.setSelectedIndex(0);
}
});
return;
}
@SuppressWarnings("unchecked") Map<String, List<List<Integer>>> matchesMap = (Map<String, List<List<Integer>>>) matchesMapObject;
// AnnotationSetName --> List of ArrayLists
// each ArrayList contains Ids of related annotations
Iterator<String> setIter = matchesMap.keySet().iterator();
HashMap<Object, Boolean> annotSetsNamesMap = new HashMap<Object, Boolean>();
for (int i = 0; i < annotSets.getItemCount(); i++) {
annotSetsNamesMap.put(annotSets.getItemAt(i), new Boolean(false));
}
outer: while (setIter.hasNext()) {
String currentSet = setIter.next();
List<List<Integer>> matches = matchesMap.get(currentSet);
currentSet = (currentSet == "") ? DEFAULT_ANNOTSET_NAME : currentSet;
if (matches == null)
continue;
AnnotationSet currAnnotSet = getAnnotationSet(currentSet);
annotSetsNamesMap.put(currentSet, new Boolean(true));
Iterator<List<Integer>> entitiesIter = matches.iterator();
if (corefAnnotationSetNodesMap.get(currentSet) == null) {
// we need to create the node for this
if (currentSet.equals(DEFAULT_ANNOTSET_NAME)) {
corefAnnotationSetNodesMap.put(DEFAULT_ANNOTSET_NAME, createChain(document.getAnnotations(), true));
} else {
corefAnnotationSetNodesMap.put(currentSet, createChain(document.getAnnotations(currentSet), false));
}
continue outer;
}
Map<CorefTreeNode, List<Integer>> chains = corefChains.get(corefAnnotationSetNodesMap.get(currentSet));
Map<CorefTreeNode, Boolean> visitedList = new HashMap<CorefTreeNode, Boolean>();
if (chains != null) {
Iterator<CorefTreeNode> chainsList = chains.keySet().iterator();
// intially no chainHead is visited
while (chainsList.hasNext()) {
visitedList.put(chainsList.next(), new Boolean(false));
}
// now we need to search for the chainHead of each group
List<List<Integer>> idsToRemove = new ArrayList<List<Integer>>();
while (entitiesIter.hasNext()) {
List<Integer> ids = entitiesIter.next();
if (ids == null || ids.size() == 0) {
idsToRemove.add(ids);
continue;
}
CorefTreeNode chainHead = null;
for (int i = 0; i < ids.size(); i++) {
Integer id = ids.get(i);
// now lets find out the headnode for this, if it is available
chainHead = findOutTheChainHead(currAnnotSet.get(id), currentSet);
if (chainHead != null) {
visitedList.put(chainHead, new Boolean(true));
break;
}
}
if (chainHead != null) {
// we found the chainHead for this
// so we would replace the ids
// but before that we would check if chainHead should be replaced
Annotation longestAnn = findOutTheLongestAnnotation(ids, getAnnotationSet(currentSet));
if (getString(longestAnn).equals(chainHead.toString())) {
chains.put(chainHead, ids);
corefChains.put(corefAnnotationSetNodesMap.get(currentSet), chains);
} else {
// we first check if new longestAnnotation String is already available as some other chain Node head
if (currentColors.containsKey(getString(longestAnn))) {
// yes one chainHead with this string already exists
// so we need to merge them together
String longestString = getString(longestAnn);
CorefTreeNode tempChainHead = findOutChainNode(longestString, currentSet);
// now all the ids under current chainHead should be placed under the tempChainHead
List<Integer> tempIds = chains.get(tempChainHead);
List<Integer> currentChainHeadIds = chains.get(chainHead);
// so lets merge them
tempIds.addAll(currentChainHeadIds);
// and update the chains
chains.remove(chainHead);
chains.put(tempChainHead, tempIds);
corefChains.put(corefAnnotationSetNodesMap.get(currentSet), chains);
visitedList.put(chainHead, new Boolean(false));
visitedList.put(tempChainHead, new Boolean(true));
} else {
String previousString = chainHead.toString();
String newString = getString(longestAnn);
chainHead.setUserObject(newString);
// we need to change the colors
Color color = currentColors.get(previousString);
currentColors.remove(previousString);
currentColors.put(newString, color);
colorChainsMap.put(newString, currentColors);
// we need to change the selections
Boolean val = currentSelections.get(previousString);
currentSelections.remove(previousString);
currentSelections.put(newString, val);
selectionChainsMap.put(newString, currentSelections);
chains.put(chainHead, ids);
corefChains.put(corefAnnotationSetNodesMap.get(currentSet), chains);
}
}
} else {
// this is something new addition
// so we need to create a new chainNode
// this is the new chain
// get the current annotSetNode
CorefTreeNode annotSetNode = corefAnnotationSetNodesMap.get(currentSet);
// we need to find out the longest string annotation
@SuppressWarnings("unused") AnnotationSet actSet = getAnnotationSet(currentSet);
Annotation ann = findOutTheLongestAnnotation(ids, getAnnotationSet(currentSet));
// so before creating a new chainNode we need to find out if
// any of the chainNodes has the same string that of this chainNode
HashMap<String, Boolean> tempSelection = (HashMap<String, Boolean>) selectionChainsMap.get(currentSet);
CorefTreeNode chainNode = null;
if (tempSelection.containsKey(getString(ann))) {
chainNode = findOutChainNode(getString(ann), currentSet);
// ArrayList matches
Map<CorefTreeNode, List<Integer>> newHashMap = corefChains.get(annotSetNode);
newHashMap.put(chainNode, ids);
corefChains.put(annotSetNode, newHashMap);
visitedList.put(chainNode, new Boolean(true));
} else {
// create the new chainNode
chainNode = new CorefTreeNode(getString(ann), false, CorefTreeNode.CHAIN_NODE);
// add this to tree
annotSetNode.add(chainNode);
corefAnnotationSetNodesMap.put(currentSet, annotSetNode);
// ArrayList matches
Map<CorefTreeNode, List<Integer>> newHashMap = corefChains.get(annotSetNode);
newHashMap.put(chainNode, ids);
corefChains.put(annotSetNode, newHashMap);
boolean selectionValue = false;
if (currentAnnotSet.equals(currentSet))
selectionValue = true;
// entry into the selection
tempSelection.put(chainNode.toString(), new Boolean(selectionValue));
selectionChainsMap.put(currentSet, tempSelection);
// entry into the colors
float[] components = colorGenerator.getNextColor().getComponents(null);
Color color = new Color(components[0], components[1], components[2], 0.5f);
Map<String, Color> tempColors = colorChainsMap.get(currentSet);
tempColors.put(chainNode.toString(), color);
colorChainsMap.put(annotSets.getSelectedItem().toString(), tempColors);
}
}
}
// ok we need to remove Idsnow
Iterator<List<Integer>> removeIter = idsToRemove.iterator();
while (removeIter.hasNext()) {
explicitCall = true;
List<Integer> ids = removeIter.next();
matches.remove(ids);
String set = currentSet.equals(DEFAULT_ANNOTSET_NAME) ? "" : currentSet;
matchesMap.put(set, matches);
explicitCall = false;
}
explicitCall = true;
document.getFeatures().put(ANNIEConstants.DOCUMENT_COREF_FEATURE_NAME, matchesMap);
explicitCall = false;
// here we need to find out the chainNodes those are no longer needed
Iterator<CorefTreeNode> visitedListIter = visitedList.keySet().iterator();
while (visitedListIter.hasNext()) {
CorefTreeNode chainNode = visitedListIter.next();
if (!visitedList.get(chainNode).booleanValue()) {
// yes this should be deleted
CorefTreeNode annotSetNode = corefAnnotationSetNodesMap.get(currentSet);
// remove from the tree
annotSetNode.remove(chainNode);
corefAnnotationSetNodesMap.put(currentSet, annotSetNode);
// ArrayList matches
Map<CorefTreeNode, List<Integer>> newHashMap = corefChains.get(annotSetNode);
newHashMap.remove(chainNode);
corefChains.put(annotSetNode, newHashMap);
// remove from the selections
Map<String, Boolean> tempSelection = selectionChainsMap.get(currentSet);
tempSelection.remove(chainNode.toString());
selectionChainsMap.put(currentSet, tempSelection);
// remove from the colors
Map<String, Color> tempColors = colorChainsMap.get(currentSet);
tempColors.remove(chainNode.toString());
colorChainsMap.put(currentSet, currentColors);
}
}
}
}
Iterator<Object> tempIter = annotSetsNamesMap.keySet().iterator();
while (tempIter.hasNext()) {
String currentSet = (String) tempIter.next();
if (!annotSetsNamesMap.get(currentSet).booleanValue()) {
String annotSet = currentSet;
// find out the currently Selected annotationSetName
@SuppressWarnings("unused") String annotSetName = (String) annotSets.getSelectedItem();
// remove it from the main data store
corefChains.remove(corefAnnotationSetNodesMap.get(annotSet));
// remove it from the main data store
corefAnnotationSetNodesMap.remove(annotSet);
// remove it from the annotationSetModel (combobox)
annotSetsModel.removeElement(annotSet);
annotSets.setModel(annotSetsModel);
annotSets.updateUI();
// remove it from the colorChainMap
colorChainsMap.remove(annotSet);
// remove it from the selectionChainMap
selectionChainsMap.remove(annotSet);
}
}
if (annotSetsModel.getSize() == 0) {
// so set visible false
if (popupWindow != null && popupWindow.isVisible()) {
popupWindow.setVisible(false);
}
corefTree.setVisible(false);
// remove all highlights
List<Object> allHighlights = new ArrayList<Object>();
if (typeSpecificHighlightedTags != null)
allHighlights.addAll(typeSpecificHighlightedTags);
if (highlightedTags != null) {
Iterator<List<Object>> iter = highlightedTags.values().iterator();
while (iter.hasNext()) {
List<Object> highlights = iter.next();
allHighlights.addAll(highlights);
}
}
for (int i = 0; i < allHighlights.size(); i++) {
highlighter.removeHighlight(allHighlights.get(i));
}
// highlighter.removeAllHighlights();
highlightedTags = null;
typeSpecificHighlightedTags = null;
return;
} else {
if (popupWindow != null && popupWindow.isVisible()) {
popupWindow.setVisible(false);
}
// remove all highlights
List<Object> allHighlights = new ArrayList<Object>();
if (typeSpecificHighlightedTags != null)
allHighlights.addAll(typeSpecificHighlightedTags);
if (highlightedTags != null) {
Iterator<List<Object>> iter = highlightedTags.values().iterator();
while (iter.hasNext()) {
List<Object> highlights = iter.next();
allHighlights.addAll(highlights);
}
}
for (int i = 0; i < allHighlights.size(); i++) {
highlighter.removeHighlight(allHighlights.get(i));
}
// highlighter.removeAllHighlights();
highlightedTags = null;
typeSpecificHighlightedTags = null;
if (currentAnnotSet != null) {
annotSets.setSelectedItem(currentAnnotSet);
currentSelections = selectionChainsMap.get(currentAnnotSet);
currentColors = colorChainsMap.get(currentAnnotSet);
highlightAnnotations();
showAnnotations.setSelected(currentShowAnnotationStatus);
if (currentAnnotType != null)
annotTypes.setSelectedItem(currentAnnotType);
else if (annotTypes.getModel().getSize() > 0) {
annotTypes.setSelectedIndex(0);
}
} else {
explicitCall = false;
annotSets.setSelectedIndex(0);
}
}
}
Aggregations