Search in sources :

Example 1 with HighChart

use of de.symeda.sormas.ui.highcharts.HighChart in project SORMAS-Project by hzi-braunschweig.

the class StatisticsView method generateChart.

public void generateChart() {
    List<StatisticsCaseCountDto> resultData = generateStatistics();
    if (resultData.isEmpty()) {
        resultsLayout.addComponent(emptyResultLabel);
        return;
    }
    if (showCaseIncidence && caseIncidencePossible && populationReferenceYear != null && populationReferenceYear != Calendar.getInstance().get(Calendar.YEAR)) {
        referenceYearLabel = new Label(VaadinIcons.INFO_CIRCLE.getHtml() + " " + String.format(I18nProperties.getString(Strings.infoPopulationReferenceYear), populationReferenceYear), ContentMode.HTML);
        resultsLayout.addComponent(referenceYearLabel);
        CssStyles.style(referenceYearLabel, CssStyles.VSPACE_TOP_4);
    }
    if (showCaseIncidence && (!caseIncidencePossible || hasMissingPopulationData)) {
        if (!caseIncidencePossible) {
            if (hasMissingPopulationData) {
                caseIncidenceNotPossibleLabel = new Label(VaadinIcons.INFO_CIRCLE.getHtml() + " " + String.format(I18nProperties.getString(Strings.infoCaseIncidenceNotPossible), missingPopulationDataNames), ContentMode.HTML);
            } else {
                caseIncidenceNotPossibleLabel = new Label(VaadinIcons.INFO_CIRCLE.getHtml() + " " + I18nProperties.getString(Strings.infoCaseIncidenceIncompatible), ContentMode.HTML);
            }
        } else {
            caseIncidenceNotPossibleLabel = new Label(VaadinIcons.INFO_CIRCLE.getHtml() + " " + String.format(I18nProperties.getString(Strings.infoCaseIncidenceMissingPopulationData), missingPopulationDataNames), ContentMode.HTML);
        }
        resultsLayout.addComponent(caseIncidenceNotPossibleLabel);
        caseIncidenceNotPossibleLabel.setWidth(100, Unit.PERCENTAGE);
        CssStyles.style(caseIncidenceNotPossibleLabel, CssStyles.VSPACE_TOP_4);
    }
    StatisticsVisualizationChartType chartType = visualizationComponent.getVisualizationChartType();
    StatisticsCaseAttribute xAxisAttribute = visualizationComponent.getColumnsAttribute();
    StatisticsCaseSubAttribute xAxisSubAttribute = visualizationComponent.getColumnsSubAttribute();
    StatisticsCaseAttribute seriesAttribute = visualizationComponent.getRowsAttribute();
    StatisticsCaseSubAttribute seriesSubAttribute = visualizationComponent.getRowsSubAttribute();
    HighChart chart = new HighChart();
    chart.setWidth(100, Unit.PERCENTAGE);
    chart.setHeight(580, Unit.PIXELS);
    StringBuilder hcjs = new StringBuilder();
    hcjs.append("var options = {").append("chart:{ " + " ignoreHiddenSeries: false, " + " type: '");
    switch(chartType) {
        case COLUMN:
        case STACKED_COLUMN:
            hcjs.append("column");
            break;
        case LINE:
            hcjs.append("line");
            break;
        case PIE:
            hcjs.append("pie");
            break;
        default:
            throw new IllegalArgumentException(chartType.toString());
    }
    hcjs.append("', " + " backgroundColor: 'transparent' " + "}," + "credits:{ enabled: false }," + "exporting:{ " + " enabled: true," + " buttons:{ contextButton:{ theme:{ fill: 'transparent' } } }" + "}," + "title:{ text: '' },");
    CaseCountOrIncidence dataStyle = showCaseIncidence && caseIncidencePossible ? CaseCountOrIncidence.CASE_INCIDENCE : CaseCountOrIncidence.CASE_COUNT;
    TreeMap<StatisticsGroupingKey, String> xAxisCaptions = new TreeMap<>(new StatisticsKeyComparator());
    TreeMap<StatisticsGroupingKey, String> seriesCaptions = new TreeMap<>(new StatisticsKeyComparator());
    boolean appendUnknownXAxisCaption = false;
    if (seriesAttribute != null || xAxisAttribute != null) {
        // Build captions for x-axis and/or series
        for (StatisticsCaseCountDto row : resultData) {
            if (xAxisAttribute != null) {
                if (!StatisticsHelper.isNullOrUnknown(row.getColumnKey())) {
                    xAxisCaptions.putIfAbsent((StatisticsGroupingKey) row.getColumnKey(), row.getColumnKey().toString());
                } else {
                    appendUnknownXAxisCaption = true;
                }
            }
            if (seriesAttribute != null) {
                if (!StatisticsHelper.isNullOrUnknown(row.getRowKey())) {
                    seriesCaptions.putIfAbsent((StatisticsGroupingKey) row.getRowKey(), row.getRowKey().toString());
                }
            }
        }
    }
    if (chartType != StatisticsVisualizationChartType.PIE) {
        hcjs.append("xAxis: { categories: [");
        if (xAxisAttribute != null) {
            xAxisCaptions.forEach((key, value) -> {
                hcjs.append("'").append(StringEscapeUtils.escapeEcmaScript(xAxisCaptions.get(key))).append("',");
            });
            if (appendUnknownXAxisCaption) {
                hcjs.append("'").append(getEscapedFragment(StatisticsHelper.NOT_SPECIFIED)).append("'");
            }
        } else if (seriesAttribute != null) {
            hcjs.append("'").append(seriesSubAttribute != null ? seriesSubAttribute.toString() : seriesAttribute.toString()).append("'");
        } else {
            hcjs.append("'").append(getEscapedFragment(StatisticsHelper.TOTAL)).append("'");
        }
        int numberOfCategories = xAxisAttribute != null ? appendUnknownXAxisCaption ? xAxisCaptions.size() + 1 : xAxisCaptions.size() : 1;
        hcjs.append("], min: 0, max: " + (numberOfCategories - 1) + "},");
        hcjs.append("yAxis: { min: 0, title: { text: '").append(dataStyle).append("' },").append("allowDecimals: false, softMax: ").append(showCaseIncidence && caseIncidencePossible ? 1 : 10).append(", stackLabels: { enabled: true, ").append("style: {fontWeight: 'normal', textOutline: '0', gridLineColor: '#000000', color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray' } } },");
        hcjs.append("tooltip: { headerFormat: '<b>{point.x}</b><br/>', pointFormat: '{series.name}: {point.y}");
        if (chartType == StatisticsVisualizationChartType.STACKED_COLUMN) {
            hcjs.append("<br/>").append(I18nProperties.getCaption(Captions.total) + ": {point.stackTotal}");
        }
        hcjs.append("'},");
    }
    hcjs.append("legend: { verticalAlign: 'top', backgroundColor: 'transparent', align: 'left', " + "borderWidth: 0, shadow: false, margin: 30, padding: 0 },");
    hcjs.append("colors: ['#FF0000','#6691C4','#ffba08','#519e8a','#ed254e','#39a0ed','#FF8C00','#344055','#D36135','#82d173'],");
    if (chartType == StatisticsVisualizationChartType.STACKED_COLUMN || chartType == StatisticsVisualizationChartType.COLUMN) {
        hcjs.append("plotOptions: { column: { borderWidth: 0, ");
        if (chartType == StatisticsVisualizationChartType.STACKED_COLUMN) {
            hcjs.append("stacking: 'normal', ");
        }
        // @formatter:off
        hcjs.append("groupPadding: 0.05, pointPadding: 0, " + "dataLabels: {" + "enabled: true," + "formatter: function() { if (this.y > 0) return this.y; }," + "color: '#444'," + "backgroundColor: 'rgba(255, 255, 255, 0.75)'," + "borderRadius: 3," + "padding: 3," + "style:{textOutline:'none'}" + "} } },");
    // @formatter:on
    }
    hcjs.append("series: [");
    if (seriesAttribute == null && xAxisAttribute == null) {
        hcjs.append("{ name: '").append(dataStyle).append("', dataLabels: { allowOverlap: false }").append(", data: [['").append(dataStyle).append("',");
        if (!showCaseIncidence || !caseIncidencePossible) {
            hcjs.append(resultData.get(0).getCaseCount().toString());
        } else {
            hcjs.append(resultData.get(0).getIncidence(incidenceDivisor));
        }
        hcjs.append("]]}");
    } else if (visualizationComponent.getVisualizationChartType() == StatisticsVisualizationChartType.PIE) {
        hcjs.append("{ name: '").append(dataStyle).append("', dataLabels: { allowOverlap: false }").append(", data: [");
        TreeMap<StatisticsGroupingKey, StatisticsCaseCountDto> seriesElements = new TreeMap<>(new StatisticsKeyComparator());
        StatisticsCaseCountDto unknownSeriesElement = null;
        for (StatisticsCaseCountDto row : resultData) {
            Object seriesId = row.getRowKey();
            if (StatisticsHelper.isNullOrUnknown(seriesId)) {
                unknownSeriesElement = row;
            } else {
                seriesElements.put((StatisticsGroupingKey) seriesId, row);
            }
        }
        seriesElements.forEach((key, value) -> {
            Object seriesValue;
            if (!showCaseIncidence || !caseIncidencePossible) {
                seriesValue = value.getCaseCount();
            } else {
                seriesValue = value.getIncidence(incidenceDivisor);
            }
            Object seriesId = value.getRowKey();
            hcjs.append("['").append(StringEscapeUtils.escapeEcmaScript(seriesCaptions.get(seriesId))).append("',").append(seriesValue).append("],");
        });
        if (unknownSeriesElement != null) {
            Object seriesValue;
            if (!showCaseIncidence || !caseIncidencePossible) {
                seriesValue = unknownSeriesElement.getCaseCount();
            } else {
                seriesValue = unknownSeriesElement.getIncidence(incidenceDivisor);
            }
            hcjs.append("['").append(dataStyle).append("',").append(seriesValue).append("],");
        }
        hcjs.append("]}");
    } else {
        Object seriesKey = null;
        TreeMap<StatisticsGroupingKey, String> seriesStrings = new TreeMap<>(new StatisticsKeyComparator());
        final StringBuilder currentSeriesString = new StringBuilder();
        final StringBuilder unknownSeriesString = new StringBuilder();
        final StringBuilder totalSeriesString = new StringBuilder();
        TreeMap<Integer, Number> currentSeriesValues = new TreeMap<>();
        for (StatisticsCaseCountDto row : resultData) {
            // Retrieve series caption of the current row
            Object rowSeriesKey;
            if (seriesAttribute != null) {
                if (!StatisticsHelper.isNullOrUnknown(row.getRowKey())) {
                    rowSeriesKey = row.getRowKey();
                } else {
                    rowSeriesKey = StatisticsHelper.VALUE_UNKNOWN;
                }
            } else {
                rowSeriesKey = StatisticsHelper.TOTAL;
            }
            // begin a new series
            if (!DataHelper.equal(seriesKey, rowSeriesKey)) {
                finalizeChartSegment(seriesKey, currentSeriesValues, unknownSeriesString, currentSeriesString, totalSeriesString, seriesStrings);
                // Append the start sequence of the next series String
                if (StatisticsHelper.isNullOrUnknown(rowSeriesKey)) {
                    seriesKey = StatisticsHelper.VALUE_UNKNOWN;
                    unknownSeriesString.append("{ name: '").append(getEscapedFragment(StatisticsHelper.NOT_SPECIFIED)).append("', dataLabels: { allowOverlap: false }, data: [");
                } else if (rowSeriesKey.equals(StatisticsHelper.TOTAL)) {
                    seriesKey = StatisticsHelper.TOTAL;
                    totalSeriesString.append("{name : '").append(getEscapedFragment(StatisticsHelper.TOTAL)).append("', dataLabels: { allowOverlap: false }, data: [");
                } else {
                    seriesKey = (StatisticsGroupingKey) row.getRowKey();
                    currentSeriesString.append("{ name: '").append(StringEscapeUtils.escapeEcmaScript(seriesCaptions.get(seriesKey))).append("', dataLabels: { allowOverlap: false }, data: [");
                }
            }
            Object value;
            if (!showCaseIncidence || !caseIncidencePossible) {
                value = row.getCaseCount();
            } else {
                value = row.getIncidence(incidenceDivisor);
            }
            if (xAxisAttribute != null) {
                Object xAxisId = row.getColumnKey();
                int captionPosition = StatisticsHelper.isNullOrUnknown(xAxisId) ? xAxisCaptions.size() : xAxisCaptions.headMap((StatisticsGroupingKey) xAxisId).size();
                currentSeriesValues.put(captionPosition, (Number) value);
            } else {
                currentSeriesValues.put(0, (Number) value);
            }
        }
        // Add the last series
        finalizeChartSegment(seriesKey, currentSeriesValues, unknownSeriesString, currentSeriesString, totalSeriesString, seriesStrings);
        seriesStrings.forEach((key, value) -> {
            hcjs.append(value);
        });
        // Add the "Unknown" series
        if (unknownSeriesString.length() > 0) {
            hcjs.append(unknownSeriesString.toString());
        }
        // Add the "Total" series
        if (totalSeriesString.length() > 0) {
            hcjs.append(totalSeriesString.toString());
        }
        // Remove last three characters to avoid invalid chart
        hcjs.delete(hcjs.length() - 3, hcjs.length());
        hcjs.append("]}");
    }
    hcjs.append("],");
    // @formatter:off
    hcjs.append("exporting: {\n" + "        buttons: {\n" + "            contextButton: {\n" + "                menuItems: [\n" + "                    'printChart',\n" + "                    'separator',\n" + "                    'downloadPNG',\n" + "                    'downloadJPEG',\n" + "                    'downloadPDF',\n" + "                    'downloadSVG',\n" + "                    'downloadCSV',\n" + "                    'downloadXLS'\n" + "                ]\n" + "            }\n" + "        }\n" + "    }");
    hcjs.append("};");
    // @formatter:on
    chart.setHcjs(hcjs.toString());
    resultsLayout.addComponent(chart);
    resultsLayout.setExpandRatio(chart, 1);
    if (showCaseIncidence && hasMissingPopulationData && caseIncidencePossible) {
        resultsLayout.addComponent(caseIncidenceNotPossibleLabel);
    }
}
Also used : Arrays(java.util.Arrays) TextField(com.vaadin.ui.TextField) Date(java.util.Date) I18nProperties(de.symeda.sormas.api.i18n.I18nProperties) EpiWeek(de.symeda.sormas.api.utils.EpiWeek) IntegerRange(de.symeda.sormas.api.IntegerRange) Alignment(com.vaadin.ui.Alignment) ReferenceDto(de.symeda.sormas.api.ReferenceDto) AgeGroup(de.symeda.sormas.api.AgeGroup) QuarterOfYear(de.symeda.sormas.api.QuarterOfYear) BigDecimal(java.math.BigDecimal) CaseOutcome(de.symeda.sormas.api.caze.CaseOutcome) ExportEntityName(de.symeda.sormas.ui.utils.ExportEntityName) StatisticsCaseAttribute(de.symeda.sormas.api.statistics.StatisticsCaseAttribute) CheckBox(com.vaadin.ui.CheckBox) CssStyles(de.symeda.sormas.ui.utils.CssStyles) Page(com.vaadin.server.Page) Quarter(de.symeda.sormas.api.Quarter) Year(de.symeda.sormas.api.Year) GeoLatLon(de.symeda.sormas.api.geo.GeoLatLon) VaadinIcons(com.vaadin.icons.VaadinIcons) LeafletMap(de.symeda.sormas.ui.map.LeafletMap) UserRole(de.symeda.sormas.api.user.UserRole) LeafletMapUtil(de.symeda.sormas.ui.map.LeafletMapUtil) RoundingMode(java.math.RoundingMode) ValoTheme(com.vaadin.ui.themes.ValoTheme) DownloadUtil(de.symeda.sormas.ui.utils.DownloadUtil) StatisticsGroupingKey(de.symeda.sormas.api.statistics.StatisticsGroupingKey) StatisticsKeyComparator(de.symeda.sormas.api.statistics.StatisticsHelper.StatisticsKeyComparator) Sex(de.symeda.sormas.api.person.Sex) HtmlHelper(de.symeda.sormas.api.utils.HtmlHelper) HighChart(de.symeda.sormas.ui.highcharts.HighChart) CommunityReferenceDto(de.symeda.sormas.api.infrastructure.community.CommunityReferenceDto) List(java.util.List) Type(com.vaadin.ui.Notification.Type) TokenizableValue(de.symeda.sormas.ui.statistics.StatisticsFilterElement.TokenizableValue) RadioButtonGroup(com.vaadin.ui.RadioButtonGroup) Descriptions(de.symeda.sormas.api.i18n.Descriptions) RegionReferenceDto(de.symeda.sormas.api.infrastructure.region.RegionReferenceDto) StreamResource(com.vaadin.server.StreamResource) FacadeProvider(de.symeda.sormas.api.FacadeProvider) VerticalLayout(com.vaadin.ui.VerticalLayout) CaseMeasure(de.symeda.sormas.api.CaseMeasure) CaseClassification(de.symeda.sormas.api.caze.CaseClassification) LeafletPolygon(de.symeda.sormas.ui.map.LeafletPolygon) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Calendar(java.util.Calendar) CollectionUtils(org.apache.commons.collections.CollectionUtils) Notification(com.vaadin.ui.Notification) Label(com.vaadin.ui.Label) StatisticsCaseCriteria(de.symeda.sormas.api.statistics.StatisticsCaseCriteria) AbstractOrderedLayout(com.vaadin.ui.AbstractOrderedLayout) StatisticsVisualizationChartType(de.symeda.sormas.ui.statistics.StatisticsVisualizationType.StatisticsVisualizationChartType) Month(de.symeda.sormas.api.Month) ButtonHelper(de.symeda.sormas.ui.utils.ButtonHelper) ContentMode(com.vaadin.shared.ui.ContentMode) Validations(de.symeda.sormas.api.i18n.Validations) DataHelper(de.symeda.sormas.api.utils.DataHelper) DashboardMapComponent(de.symeda.sormas.ui.dashboard.map.DashboardMapComponent) DistrictReferenceDto(de.symeda.sormas.api.infrastructure.district.DistrictReferenceDto) StringEscapeUtils(org.apache.commons.text.StringEscapeUtils) FacilityReferenceDto(de.symeda.sormas.api.infrastructure.facility.FacilityReferenceDto) Captions(de.symeda.sormas.api.i18n.Captions) StatisticsCaseCountDto(de.symeda.sormas.api.statistics.StatisticsCaseCountDto) Button(com.vaadin.ui.Button) StatisticsCaseSubAttribute(de.symeda.sormas.api.statistics.StatisticsCaseSubAttribute) Disease(de.symeda.sormas.api.Disease) TreeMap(java.util.TreeMap) HorizontalLayout(com.vaadin.ui.HorizontalLayout) FileDownloader(com.vaadin.server.FileDownloader) StatisticsHelper(de.symeda.sormas.api.statistics.StatisticsHelper) MonthOfYear(de.symeda.sormas.api.MonthOfYear) Comparator(java.util.Comparator) Strings(de.symeda.sormas.api.i18n.Strings) Collections(java.util.Collections) StatisticsVisualizationChartType(de.symeda.sormas.ui.statistics.StatisticsVisualizationType.StatisticsVisualizationChartType) StatisticsKeyComparator(de.symeda.sormas.api.statistics.StatisticsHelper.StatisticsKeyComparator) Label(com.vaadin.ui.Label) HighChart(de.symeda.sormas.ui.highcharts.HighChart) TreeMap(java.util.TreeMap) StatisticsCaseSubAttribute(de.symeda.sormas.api.statistics.StatisticsCaseSubAttribute) StatisticsGroupingKey(de.symeda.sormas.api.statistics.StatisticsGroupingKey) StatisticsCaseCountDto(de.symeda.sormas.api.statistics.StatisticsCaseCountDto) StatisticsCaseAttribute(de.symeda.sormas.api.statistics.StatisticsCaseAttribute)

Aggregations

VaadinIcons (com.vaadin.icons.VaadinIcons)1 FileDownloader (com.vaadin.server.FileDownloader)1 Page (com.vaadin.server.Page)1 StreamResource (com.vaadin.server.StreamResource)1 ContentMode (com.vaadin.shared.ui.ContentMode)1 AbstractOrderedLayout (com.vaadin.ui.AbstractOrderedLayout)1 Alignment (com.vaadin.ui.Alignment)1 Button (com.vaadin.ui.Button)1 CheckBox (com.vaadin.ui.CheckBox)1 HorizontalLayout (com.vaadin.ui.HorizontalLayout)1 Label (com.vaadin.ui.Label)1 Notification (com.vaadin.ui.Notification)1 Type (com.vaadin.ui.Notification.Type)1 RadioButtonGroup (com.vaadin.ui.RadioButtonGroup)1 TextField (com.vaadin.ui.TextField)1 VerticalLayout (com.vaadin.ui.VerticalLayout)1 ValoTheme (com.vaadin.ui.themes.ValoTheme)1 AgeGroup (de.symeda.sormas.api.AgeGroup)1 CaseMeasure (de.symeda.sormas.api.CaseMeasure)1 Disease (de.symeda.sormas.api.Disease)1