use of de.symeda.sormas.api.statistics.StatisticsGroupingKey in project SORMAS-Project by hzi-braunschweig.
the class StatisticsFilterElement method createTokens.
protected List<TokenizableValue> createTokens(Collection<? extends StatisticsGroupingKey> groupingKeys) {
List<TokenizableValue> result = new ArrayList<>(groupingKeys.size());
int index = 0;
for (StatisticsGroupingKey groupingKey : groupingKeys) {
result.add(new TokenizableValue(groupingKey, index++));
}
return result;
}
use of de.symeda.sormas.api.statistics.StatisticsGroupingKey in project SORMAS-Project by hzi-braunschweig.
the class CaseStatisticsFacadeEjb method queryCaseCount.
@SuppressWarnings("unchecked")
@Override
public List<StatisticsCaseCountDto> queryCaseCount(StatisticsCaseCriteria caseCriteria, StatisticsCaseAttribute rowGrouping, StatisticsCaseSubAttribute rowSubGrouping, StatisticsCaseAttribute columnGrouping, StatisticsCaseSubAttribute columnSubGrouping, boolean includePopulation, boolean includeZeroValues, Integer populationReferenceYear) {
// case counts
Pair<String, List<Object>> caseCountQueryAndParams = buildCaseCountQuery(caseCriteria, rowGrouping, rowSubGrouping, columnGrouping, columnSubGrouping);
Query caseCountQuery = em.createNativeQuery(caseCountQueryAndParams.getKey().toString());
for (int i = 0; i < caseCountQueryAndParams.getValue().size(); i++) {
caseCountQuery.setParameter(i + 1, caseCountQueryAndParams.getValue().get(i));
}
Function<Integer, RegionReferenceDto> regionProvider = id -> regionFacade.getRegionReferenceById(id);
Function<Integer, DistrictReferenceDto> districtProvider = id -> districtFacade.getDistrictReferenceById(id);
Function<Integer, CommunityReferenceDto> communityProvider = id -> communityFacade.getCommunityReferenceById(id);
Function<Integer, FacilityReferenceDto> healthFacilityProvider = id -> facilityFacade.getFacilityReferenceById(id);
List<StatisticsCaseCountDto> caseCountResults = ((Stream<Object[]>) caseCountQuery.getResultStream()).map(result -> {
Object rowKey = "".equals(result[1]) ? null : result[1];
Object columnKey = "".equals(result[2]) ? null : result[2];
return new StatisticsCaseCountDto(result[0] != null ? ((Number) result[0]).intValue() : null, null, StatisticsHelper.buildGroupingKey(rowKey, rowGrouping, rowSubGrouping, regionProvider, districtProvider, communityProvider, healthFacilityProvider), StatisticsHelper.buildGroupingKey(columnKey, columnGrouping, columnSubGrouping, regionProvider, districtProvider, communityProvider, healthFacilityProvider));
}).collect(Collectors.toList());
if (includeZeroValues) {
List<StatisticsGroupingKey> allRowKeys;
if (rowGrouping != null) {
allRowKeys = (List<StatisticsGroupingKey>) caseCriteria.getFilterValuesForGrouping(rowGrouping, rowSubGrouping);
if (allRowKeys == null) {
allRowKeys = StatisticsHelper.getAttributeGroupingKeys(rowGrouping, rowSubGrouping, diseaseConfigurationFacade, caseFacade, regionFacade, districtFacade);
}
} else {
allRowKeys = Arrays.asList((StatisticsGroupingKey) null);
}
List<StatisticsGroupingKey> allColumnKeys;
if (columnGrouping != null) {
allColumnKeys = (List<StatisticsGroupingKey>) caseCriteria.getFilterValuesForGrouping(columnGrouping, columnSubGrouping);
if (allColumnKeys == null) {
allColumnKeys = StatisticsHelper.getAttributeGroupingKeys(columnGrouping, columnSubGrouping, diseaseConfigurationFacade, caseFacade, regionFacade, districtFacade);
}
} else {
allColumnKeys = Arrays.asList((StatisticsGroupingKey) null);
}
for (StatisticsGroupingKey rowKey : allRowKeys) {
for (StatisticsGroupingKey columnKey : allColumnKeys) {
StatisticsCaseCountDto zeroDto = new StatisticsCaseCountDto(0, null, rowKey, columnKey);
if (!caseCountResults.contains(zeroDto)) {
caseCountResults.add(zeroDto);
}
}
}
}
// population
if (includePopulation) {
Pair<String, List<Object>> populationQueryAndParams = buildPopulationQuery(caseCriteria, rowGrouping, rowSubGrouping, columnGrouping, columnSubGrouping, populationReferenceYear);
Query populationQuery = em.createNativeQuery(populationQueryAndParams.getKey().toString());
for (int i = 0; i < populationQueryAndParams.getValue().size(); i++) {
populationQuery.setParameter(i + 1, populationQueryAndParams.getValue().get(i));
}
List<StatisticsCaseCountDto> populationResults = ((Stream<Object[]>) populationQuery.getResultStream()).map(result -> {
Object rowKey = "".equals(result[1]) ? null : result[1];
Object columnKey = "".equals(result[2]) ? null : result[2];
return new StatisticsCaseCountDto(null, result[0] != null ? ((Number) result[0]).intValue() : null, StatisticsHelper.buildGroupingKey(rowKey, rowGrouping, rowSubGrouping, regionProvider, districtProvider, communityProvider, healthFacilityProvider), StatisticsHelper.buildGroupingKey(columnKey, columnGrouping, columnSubGrouping, regionProvider, districtProvider, communityProvider, healthFacilityProvider));
}).collect(Collectors.toList());
boolean rowIsPopulation = rowGrouping != null && rowGrouping.isPopulationData();
boolean columnIsPopulation = columnGrouping != null && columnGrouping.isPopulationData();
if (!populationResults.isEmpty()) {
assert ((populationResults.get(0).getRowKey() != null) == rowIsPopulation);
assert ((populationResults.get(0).getColumnKey() != null) == columnIsPopulation);
}
// add the population data to the case counts
// when a key is not a population data key, we use null instead
StatisticsCaseCountDto searchDto = new StatisticsCaseCountDto(null, null, null, null);
for (StatisticsCaseCountDto caseCountResult : caseCountResults) {
if (rowIsPopulation) {
searchDto.setRowKey(caseCountResult.getRowKey());
}
if (columnIsPopulation) {
searchDto.setColumnKey(caseCountResult.getColumnKey());
}
int index = populationResults.indexOf(searchDto);
if (index >= 0) {
caseCountResult.setPopulation(populationResults.get(index).getPopulation());
}
}
}
return caseCountResults;
}
use of de.symeda.sormas.api.statistics.StatisticsGroupingKey in project SORMAS-Project by hzi-braunschweig.
the class StatisticsFilterValuesElement method getFilterValues.
private List<TokenizableValue> getFilterValues() {
if (subAttribute != null) {
switch(subAttribute) {
case YEAR:
case QUARTER:
case MONTH:
case EPI_WEEK:
case QUARTER_OF_YEAR:
case MONTH_OF_YEAR:
case EPI_WEEK_OF_YEAR:
List<StatisticsGroupingKey> dateValues = StatisticsHelper.getTimeGroupingKeys(attribute, subAttribute, FacadeProvider.getCaseFacade());
return createTokens(dateValues);
case REGION:
return createTokens(FacadeProvider.getRegionFacade().getAllActiveByServerCountry());
case DISTRICT:
if (jurisdictionElement == null) {
return createTokens(FacadeProvider.getDistrictFacade().getAllActiveAsReference());
}
return createDistrictTokens(jurisdictionElement.getSelectedRegions());
case COMMUNITY:
if (jurisdictionElement == null) {
return new ArrayList<>();
}
return createCommunityTokens(jurisdictionElement.getSelectedDistricts());
case FACILITY:
if (jurisdictionElement == null) {
return new ArrayList<>();
}
List<TokenizableValue> selectedDistrictTokenizables = jurisdictionElement.getSelectedDistricts();
List<TokenizableValue> selectedCommunityTokenizables = jurisdictionElement.getSelectedCommunities();
if (CollectionUtils.isNotEmpty(selectedCommunityTokenizables)) {
List<FacilityReferenceDto> facilities = new ArrayList<>();
for (TokenizableValue selectedCommunityTokenizable : selectedCommunityTokenizables) {
CommunityReferenceDto selectedCommunity = (CommunityReferenceDto) selectedCommunityTokenizable.getValue();
facilities.addAll(FacadeProvider.getFacilityFacade().getActiveFacilitiesByCommunityAndType(selectedCommunity, jurisdictionElement.getFacilityType(), false, false));
}
return createTokens(facilities);
} else if (CollectionUtils.isNotEmpty(selectedDistrictTokenizables)) {
List<FacilityReferenceDto> facilities = new ArrayList<>();
for (TokenizableValue selectedDistrictTokenizable : selectedDistrictTokenizables) {
DistrictReferenceDto selectedDistrict = (DistrictReferenceDto) selectedDistrictTokenizable.getValue();
facilities.addAll(FacadeProvider.getFacilityFacade().getActiveFacilitiesByDistrictAndType(selectedDistrict, jurisdictionElement.getFacilityType(), false, false));
}
return createTokens(facilities);
} else {
return new ArrayList<>();
}
case PERSON_REGION:
return createTokens(FacadeProvider.getRegionFacade().getAllActiveByServerCountry());
case PERSON_DISTRICT:
if (residenceElement == null) {
return createTokens(FacadeProvider.getDistrictFacade().getAllActiveAsReference());
}
return createDistrictTokens(residenceElement.getSelectedRegions());
case PERSON_COMMUNITY:
if (residenceElement == null) {
return new ArrayList<>();
}
return createCommunityTokens(residenceElement.getSelectedDistricts());
case PERSON_CITY:
case PERSON_POSTCODE:
return new ArrayList<>();
default:
throw new IllegalArgumentException(this.toString());
}
} else {
switch(attribute) {
case SEX:
List<TokenizableValue> tokens = createTokens(Sex.values());
tokens.add(new TokenizableValue(I18nProperties.getCaption(Captions.notSpecified), tokens.size()));
return tokens;
case AGE_INTERVAL_1_YEAR:
case AGE_INTERVAL_5_YEARS:
case AGE_INTERVAL_CHILDREN_COARSE:
case AGE_INTERVAL_CHILDREN_FINE:
case AGE_INTERVAL_CHILDREN_MEDIUM:
case AGE_INTERVAL_BASIC:
List<StatisticsGroupingKey> ageIntervalValues = StatisticsHelper.getAgeIntervalGroupingKeys(attribute);
return createTokens(ageIntervalValues);
case DISEASE:
return createTokens(FacadeProvider.getDiseaseConfigurationFacade().getAllDiseases(true, true, true));
case CLASSIFICATION:
return createTokens(CaseClassification.values());
case OUTCOME:
return createTokens(CaseOutcome.values());
case REPORTING_USER_ROLE:
return createTokens(UserRole.values());
default:
throw new IllegalArgumentException(this.toString());
}
}
}
use of de.symeda.sormas.api.statistics.StatisticsGroupingKey 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);
}
}
Aggregations