add polytomous key generation to character matrix (experimental)
[taxeditor.git] / eu.etaxonomy.taxeditor.editor / src / main / java / eu / etaxonomy / taxeditor / editor / descriptiveDataSet / matrix / CharacterMatrixBottomToolbar.java
index a930030710ea5173ecc68057d03fb6456a0f5525..28eac14c416193e32b94700b63cdb186dde07344 100644 (file)
@@ -10,11 +10,8 @@ package eu.etaxonomy.taxeditor.editor.descriptiveDataSet.matrix;
 
 import java.util.ArrayList;
 import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
-import java.util.Set;
 import java.util.UUID;
 import java.util.stream.Collectors;
 
@@ -27,27 +24,35 @@ import org.eclipse.swt.layout.RowLayout;
 import org.eclipse.swt.widgets.Button;
 import org.eclipse.swt.widgets.Composite;
 
-import eu.etaxonomy.cdm.api.service.IDescriptionService;
 import eu.etaxonomy.cdm.api.service.IDescriptiveDataSetService;
-import eu.etaxonomy.cdm.api.service.IOccurrenceService;
+import eu.etaxonomy.cdm.api.service.IPolytomousKeyService;
 import eu.etaxonomy.cdm.api.service.ITaxonNodeService;
 import eu.etaxonomy.cdm.api.service.UpdateResult;
+import eu.etaxonomy.cdm.api.service.config.IdentifiableServiceConfiguratorImpl;
 import eu.etaxonomy.cdm.api.service.dto.RowWrapperDTO;
+import eu.etaxonomy.cdm.api.service.dto.SpecimenRowWrapperDTO;
+import eu.etaxonomy.cdm.api.service.dto.TaxonRowWrapperDTO;
+import eu.etaxonomy.cdm.common.CdmUtils;
 import eu.etaxonomy.cdm.model.description.CategoricalData;
-import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
+import eu.etaxonomy.cdm.model.description.DescriptiveDataSet;
 import eu.etaxonomy.cdm.model.description.Feature;
+import eu.etaxonomy.cdm.model.description.PolytomousKey;
 import eu.etaxonomy.cdm.model.description.QuantitativeData;
 import eu.etaxonomy.cdm.model.description.SpecimenDescription;
-import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
+import eu.etaxonomy.cdm.model.description.TaxonDescription;
 import eu.etaxonomy.cdm.model.taxon.Taxon;
 import eu.etaxonomy.cdm.model.taxon.TaxonNode;
 import eu.etaxonomy.cdm.persistence.dto.SpecimenNodeWrapper;
 import eu.etaxonomy.cdm.persistence.dto.TaxonNodeDto;
+import eu.etaxonomy.cdm.strategy.generate.PolytomousKeyGenerator;
+import eu.etaxonomy.cdm.strategy.generate.PolytomousKeyGeneratorConfigurator;
 import eu.etaxonomy.taxeditor.editor.l10n.Messages;
-import eu.etaxonomy.taxeditor.model.DescriptionHelper;
 import eu.etaxonomy.taxeditor.model.ImageResources;
 import eu.etaxonomy.taxeditor.model.MessagingUtils;
+import eu.etaxonomy.taxeditor.preference.IPreferenceKeys;
+import eu.etaxonomy.taxeditor.preference.PreferencesUtil;
 import eu.etaxonomy.taxeditor.store.CdmStore;
+import eu.etaxonomy.taxeditor.store.StoreUtil;
 import eu.etaxonomy.taxeditor.ui.dialog.selection.TaxonSelectionDialog;
 
 /**
@@ -79,25 +84,35 @@ public class CharacterMatrixBottomToolbar extends Composite{
         btnAddDescription.addSelectionListener(new SelectionAdapter() {
             @Override
             public void widgetSelected(SelectionEvent e) {
+                if(StoreUtil.promptCheckIsDirty(matrix.getPart())){
+                    return;
+                }
+                String error = ""; //$NON-NLS-1$
                 SpecimenSelectionDialog dialog = new SpecimenSelectionDialog(matrix.getShell(), matrix);
                 if(dialog.open()==Window.OK){
                     Collection<SpecimenNodeWrapper> wrappers = dialog.getSpecimen();
                     for (SpecimenNodeWrapper wrapper : wrappers) {
-                        SpecimenOrObservationBase specimen = CdmStore.getService(IOccurrenceService.class).load(wrapper.getUuidAndTitleCache().getUuid());
-                        SpecimenDescription description = getDescriptionForDescriptiveDataSet(specimen);
-                        //description elements
-                        Map<Feature, DescriptionElementBase> featureToElementMap = new HashMap<>();
-                        Set<DescriptionElementBase> elements = description.getElements();
-                        for (DescriptionElementBase descriptionElementBase : elements) {
-                            Feature feature = descriptionElementBase.getFeature();
-                            featureToElementMap.put(feature, descriptionElementBase);
+                        SpecimenDescription specimenDescription = CdmStore.getService(IDescriptiveDataSetService.class)
+                                .findSpecimenDescription(matrix.getDescriptiveDataSet().getUuid(),
+                                        wrapper.getUuidAndTitleCache().getUuid(), true);
+                        SpecimenRowWrapperDTO rowWrapper = CdmStore.getService(IDescriptiveDataSetService.class)
+                                .createSpecimenRowWrapper(specimenDescription, matrix.getDescriptiveDataSet());
+                        if(rowWrapper==null){
+                            error += specimenDescription;
+                            continue;
                         }
-                        RowWrapperDTO rowWrapper = CdmStore.getService(IDescriptiveDataSetService.class).createRowWrapper(description, matrix.getDescriptiveDataSet());
+                        //add specimen description
                         matrix.getDescriptions().add(rowWrapper);
-                        matrix.getDescriptiveDataSet().addDescription(description);
+                        matrix.getDescriptiveDataSet().addDescription(specimenDescription);
+                        matrix.getCdmEntitiySession().load(specimenDescription, true);
+
                         matrix.setDirty();
                         matrix.getSpecimenCache().remove(wrapper);
                     }
+                    if(CdmUtils.isNotBlank(error)){
+                        MessagingUtils.warningDialog(Messages.CharacterMatrixBottomToolbar_ERROR_ROW_CREATION_TITLE, this,
+                                String.format(Messages.CharacterMatrixBottomToolbar_ERROR_ROW_CREATION_MESSAGE, error));
+                    }
                 }
             }
         });
@@ -109,6 +124,12 @@ public class CharacterMatrixBottomToolbar extends Composite{
         btnRemoveDescription.addSelectionListener(new SelectionAdapter() {
             @Override
             public void widgetSelected(SelectionEvent e) {
+                if(StoreUtil.promptCheckIsDirty(matrix.getPart())){
+                    return;
+                }
+                if(!MessagingUtils.confirmDialog(Messages.CharacterMatrixBottomToolbar_CONFIRM_DELETE_TITLE, Messages.CharacterMatrixBottomToolbar_CONFIRM_DELETE_MESSAGE)){
+                    return;
+                }
                 int[] fullySelectedRowPositions = matrix.getBodyLayer().getSelectionLayer().getFullySelectedRowPositions();
                 List<RowWrapperDTO> toRemove = new ArrayList<>();
                 for (int i : fullySelectedRowPositions) {
@@ -117,10 +138,10 @@ public class CharacterMatrixBottomToolbar extends Composite{
                         toRemove.add((RowWrapperDTO) rowObject);
                     }
                 }
-                toRemove.forEach(rowToRemove->{
+                toRemove.forEach(rowToRemove -> {
                     matrix.getDescriptions().remove(rowToRemove);
-                    matrix.getDescriptiveDataSet().removeDescription(rowToRemove.getSpecimenDescription());
-                    matrix.setDirty();
+                    CdmStore.getService(IDescriptiveDataSetService.class).removeDescription(
+                            rowToRemove.getDescription().getUuid(), matrix.getDescriptiveDataSet().getUuid());
                 });
             }
         });
@@ -128,21 +149,22 @@ public class CharacterMatrixBottomToolbar extends Composite{
          * Aggregate button
          */
         Button btnAggregate = new Button(this, SWT.PUSH);
-        btnAggregate.setText("Aggregate");
+        btnAggregate.setText(Messages.CharacterMatrixBottomToolbar_AGGREGATE);
         btnAggregate.addSelectionListener(new SelectionAdapter() {
             @Override
             public void widgetSelected(SelectionEvent e) {
-                Set<TaxonNode> taxonSubtreeFilter = matrix.getDescriptiveDataSet().getTaxonSubtreeFilter();
+                if(StoreUtil.promptCheckIsDirty(matrix.getPart())){
+                    return;
+                }
+                List<TaxonNode> taxonSubtreeFilter = CdmStore.getService(IDescriptiveDataSetService.class).loadFilteredTaxonNodes(matrix.getDescriptiveDataSet(), null);
                 List<TaxonNodeDto> nodeDtos = taxonSubtreeFilter.stream()
                         .map(node -> new TaxonNodeDto(node)).collect(Collectors.toList());
                 TaxonNodeDto parentDto = CdmStore.getService(ITaxonNodeService.class).findCommonParentDto(nodeDtos);
                 UUID taxonUuid = parentDto.getTaxonUuid();
                 int response = MessagingUtils.confirmDialog(
-                        "Choose location for the aggregated description",
-                        String.format("The aggregated description will be stored at "
-                                + "the common parent taxon of this data set:\n%s\n\n"
-                                + "Do you want to use this taxon?"
-                                , parentDto.getTaxonTitleCache()), "Yes", "Choose taxon", "Cancel");
+                        Messages.CharacterMatrixBottomToolbar_AGGREGATION_TITLE,
+                        String.format(Messages.CharacterMatrixBottomToolbar_AGGREGATION_MESSAGE
+                                , parentDto.getTaxonTitleCache()), Messages.CharacterMatrixBottomToolbar_YES, Messages.CharacterMatrixBottomToolbar_CHOOSE_TAXON, Messages.CharacterMatrixBottomToolbar_CANCEL);
                 if(response==2){
                     return;
                 }
@@ -153,127 +175,84 @@ public class CharacterMatrixBottomToolbar extends Composite{
                     }
                     taxonUuid = taxon.getUuid();
                 }
-                UpdateResult result = CdmStore.getService(IDescriptionService.class).aggregateDescription(taxonUuid, null, matrix.getDescriptiveDataSet().getUuid());
-                matrix.addUpdateResult(result);
-                matrix.setDirty();
+                List<UUID> descriptionUuids = new ArrayList<>();
+                matrix.getDescriptiveDataSet().getDescriptions().forEach(desc->descriptionUuids.add(desc.getUuid()));
+                UpdateResult result = CdmStore.getService(IDescriptiveDataSetService.class).aggregateDescription(taxonUuid, descriptionUuids, matrix.getDescriptiveDataSet().getLabel(), matrix.getDescriptiveDataSet().getUuid());
+                TaxonDescription taxonDescription = (TaxonDescription) result.getCdmEntity();
+                TaxonRowWrapperDTO taxonRowWrapper = CdmStore.getService(IDescriptiveDataSetService.class).createTaxonRowWrapper(taxonDescription.getUuid(), matrix.getDescriptiveDataSet().getUuid());
+                matrix.getDescriptions().add(taxonRowWrapper);
 
-                //aggregate histogram for categorical tooltip
-                Map<Feature, CategoricalDataHistogram> featureToHistogramMap = matrix.getFeatureToHistogramMap();
-                featureToHistogramMap.clear();
-                aggregateCategorcialHistogram(featureToHistogramMap);
+                aggregateCategorcialHistogram(matrix.getFeatureToHistogramMap());
+                aggregateQuantitativeSummary(matrix.getFeatureToQuantDataStatisticsMap());
             }
-
         });
+        if(PreferencesUtil.getBooleanValue(IPreferenceKeys.SHOW_EXPERIMENTAL_FEATURES)){
+            /**
+             * Key generation button
+             */
+            Button btnGenerateKey = new Button(this, SWT.PUSH);
+            btnGenerateKey.setText("Generate Polytomous Key");
+            btnGenerateKey.addSelectionListener(new SelectionAdapter() {
+                @Override
+                public void widgetSelected(SelectionEvent e) {
+                    if(StoreUtil.promptCheckIsDirty(matrix.getPart())){
+                        return;
+                    }
+                    PolytomousKeyGeneratorConfigurator keyConfig = new PolytomousKeyGeneratorConfigurator();
+                    DescriptiveDataSet descriptiveDataSet = matrix.getDescriptiveDataSet();
+                    keyConfig.setDataSet(descriptiveDataSet);
+                    PolytomousKey key = new PolytomousKeyGenerator().invoke(keyConfig);
+                    IPolytomousKeyService keyService = CdmStore.getService(IPolytomousKeyService.class);
+                    IdentifiableServiceConfiguratorImpl<PolytomousKey> serviceConfig= new IdentifiableServiceConfiguratorImpl<>();
+                    serviceConfig.setTitleSearchString(descriptiveDataSet.getTitleCache());
+                    List<PolytomousKey> list = keyService.findByTitle(serviceConfig).getRecords();
+                    if(list!=null){
+                        // TODO clear old key
+                        System.out.println("Key with same name found for this data set found");
+                    }
+                    key.setTitleCache(descriptiveDataSet.getTitleCache(), true);
+                    keyService.save(key);
+                    key.print(System.out);
+                }
+            });
+        }
     }
 
     @SuppressWarnings("unchecked")
     private void aggregateCategorcialHistogram(Map<Feature, CategoricalDataHistogram> featureToHistogramMap) {
-        matrix.getDescriptions()
-                .forEach(o -> ((RowWrapperDTO) o).getSpecimenDescription().getElements().stream()
-                        .filter(descriptionElement -> descriptionElement instanceof CategoricalData)
-                        .forEach(categoricalData -> {
-                            Feature feature = ((CategoricalData) categoricalData).getFeature();
-                            CategoricalDataHistogram dataHistogram = featureToHistogramMap.get(feature);
-                            if(dataHistogram==null){
-                                dataHistogram = new CategoricalDataHistogram(feature);
-                            }
-                            featureToHistogramMap.put(feature, dataHistogram);
-                            ((CategoricalData) categoricalData).getStateData()
-                                    .forEach(stateData -> featureToHistogramMap.get(feature).addState(stateData.getState()));
-                        }));
+        featureToHistogramMap.clear();
+        matrix.getDescriptions().stream()
+        .filter(desc->desc instanceof SpecimenRowWrapperDTO)
+        .forEach(o -> ((SpecimenRowWrapperDTO) o).getDescription().getElements().stream()
+                .filter(descriptionElement -> descriptionElement instanceof CategoricalData)
+                .forEach(categoricalData -> {
+                    Feature feature = ((CategoricalData) categoricalData).getFeature();
+                    CategoricalDataHistogram dataHistogram = featureToHistogramMap.get(feature);
+                    if(dataHistogram==null){
+                        dataHistogram = new CategoricalDataHistogram(feature);
+                    }
+                    featureToHistogramMap.put(feature, dataHistogram);
+                    ((CategoricalData) categoricalData).getStateData()
+                    .forEach(stateData -> featureToHistogramMap.get(feature).addState(stateData.getState()));
+                }));
     }
 
-    private SpecimenDescription getDescriptionForDescriptiveDataSet(SpecimenOrObservationBase specimen){
-        Set<Feature> wsFeatures = matrix.getDescriptiveDataSet().getDescriptiveSystem().getDistinctFeatures();
-        List<DescriptionElementBase> matchingDescriptionElements = new ArrayList<>();
-
-        for (SpecimenDescription specimenDescription : (Set<SpecimenDescription>) specimen.getDescriptions()) {
-            specimenDescription = (SpecimenDescription) CdmStore.getService(IDescriptionService.class).load(specimenDescription.getUuid());
-            Set<Feature> specimenDescriptionFeatures = new HashSet<>();
-            //gather specimen description features and check for match with WS features
-            for (DescriptionElementBase specimenDescriptionElement : specimenDescription.getElements()) {
-                Feature feature = specimenDescriptionElement.getFeature();
-                specimenDescriptionFeatures.add(feature);
-                if(wsFeatures.contains(feature)){
-                    matchingDescriptionElements.add(specimenDescriptionElement);
-                }
-            }
-            //if description with the exact same features is found return the description
-            if(specimenDescriptionFeatures.equals(wsFeatures)){
-                return specimenDescription;
-            }
-        }
-        //Create new specimen description if no match was found
-        matrix.setDirty();
-        SpecimenDescription newDesription = SpecimenDescription.NewInstance(specimen);
-        newDesription.setTitleCache(Messages.CharacterMatrix_DESCRIPTIVE_DATA_SET+matrix.getDescriptiveDataSet().getLabel()+": "+newDesription.generateTitle(), true); //$NON-NLS-2$
-
-        //check for equals description element (same feature and same values)
-        Map<Feature, List<DescriptionElementBase>> featureToElementMap = new HashMap<>();
-        for(DescriptionElementBase element:matchingDescriptionElements){
-            List<DescriptionElementBase> list = featureToElementMap.get(element.getFeature());
-            if(list==null){
-                list = new ArrayList<>();
-            }
-            list.add(element);
-            featureToElementMap.put(element.getFeature(), list);
-        }
-        Set<DescriptionElementBase> descriptionElementsToClone = new HashSet<>();
-        for(Feature feature:featureToElementMap.keySet()){
-            List<DescriptionElementBase> elements = featureToElementMap.get(feature);
-            //no duplicate description elements found for this feature
-            if(elements.size()==1){
-                descriptionElementsToClone.add(elements.get(0));
-            }
-            //duplicates found -> check if all are equal
-            else{
-                DescriptionElementBase match = null;
-                for (DescriptionElementBase descriptionElementBase : elements) {
-                    if(match==null){
-                        match = descriptionElementBase;
-                    }
-                    else if(!new DescriptionElementCompareWrapper(match).equals(new DescriptionElementCompareWrapper(descriptionElementBase))){
-                        match = null;
-                        MessagingUtils.informationDialog(Messages.CharacterMatrix_MULTIPLE_DATA,
-                                String.format(Messages.CharacterMatrix_MULTIPLE_DATA_MESSAGE, feature.getLabel()));
-                        break;
+    @SuppressWarnings("unchecked")
+    private void aggregateQuantitativeSummary(Map<Feature, QuantitativeDataStatistics> featureToQuantDataStatisticsMap) {
+        featureToQuantDataStatisticsMap.clear();
+        matrix.getDescriptions().stream()
+        .filter(desc->desc instanceof SpecimenRowWrapperDTO)
+        .forEach(o -> ((SpecimenRowWrapperDTO) o).getDescription().getElements().stream()
+                .filter(descriptionElement -> descriptionElement instanceof QuantitativeData)
+                .forEach(quantData -> {
+                    Feature feature = ((QuantitativeData) quantData).getFeature();
+                    QuantitativeDataStatistics dataStatistics = featureToQuantDataStatisticsMap.get(feature);
+                    if(dataStatistics==null){
+                        dataStatistics = new QuantitativeDataStatistics();
                     }
-                }
-                if(match!=null){
-                    descriptionElementsToClone.add(match);
-                }
-            }
-        }
-        //clone matching descriptionElements
-        for (DescriptionElementBase descriptionElementBase : descriptionElementsToClone) {
-            DescriptionElementBase clone;
-            try {
-                clone = descriptionElementBase.clone(newDesription);
-                clone.getSources().forEach(source -> source.setOriginalNameString(DescriptionHelper.getLabel(descriptionElementBase)));
-            } catch (CloneNotSupportedException e) {
-                MessagingUtils.error(CharacterMatrix.class, e);
-            }
-        }
-
-        //add all remaining description elements to the new description
-        for(Feature wsFeature:wsFeatures){
-            boolean featureFound = false;
-            for(DescriptionElementBase element:newDesription.getElements()){
-                if(element.getFeature().equals(wsFeature)){
-                    featureFound = true;
-                    break;
-                }
-            }
-            if(!featureFound){
-                if(wsFeature.isSupportsCategoricalData()){
-                    newDesription.addElement(CategoricalData.NewInstance(wsFeature));
-                }
-                else if(wsFeature.isSupportsQuantitativeData()){
-                    newDesription.addElement(QuantitativeData.NewInstance(wsFeature));
-                }
-            }
-        }
-        return newDesription;
-
+                    featureToQuantDataStatisticsMap.put(feature, dataStatistics);
+                    dataStatistics.addQuantitativeData((QuantitativeData) quantData);
+                }));
     }
+
 }