Skip to content

Staging #142

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Apr 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
413 changes: 413 additions & 0 deletions src/assets/js/indicatorHandler.js

Large diffs are not rendered by default.

244 changes: 67 additions & 177 deletions src/assets/js/signal_sets.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const indicatorHandler = new IndicatorHandler();

function initSelect2(elementId, data) {
$(`#${elementId}`).select2({
data: data,
Expand All @@ -15,73 +17,34 @@ function showWarningAlert(warningMessage, slideUpTime = 2000) {
});
}

function checkGeoCoverage(geoType, geoValue) {
var notCoveredSignals = [];
$.ajax({
url: "epidata/covidcast/geo_coverage/",
type: 'GET',
async: false,
data: {
'geo': `${geoType}:${geoValue}`
},
success: function (result) {
checkedSignalMembers.forEach(signal => {
var covered = result["epidata"].some(
e => (e.source === signal.data_source && e.signal === signal.signal)
)
if (!covered) {
notCoveredSignals.push(signal);
}
})
}
})
return notCoveredSignals;
}



function plotData() {
var dataSets = {};
var geographicValues = $('#geographic_value').select2('data');
checkedSignalMembers.forEach((signal) => {
geographicValues.forEach((geoValue) => {
var geographicValue = (typeof geoValue.id === 'string') ? geoValue.id.toLowerCase() : geoValue.id;
var geographicType = geoValue.geoType;
var epivisCustomTitle;
if (signal["member_short_name"]) {
epivisCustomTitle = `${signal["signal_set_short_name"]}:${signal["member_short_name"]} : ${geoValue.text}`
} else {
epivisCustomTitle = `${signal["signal_set_short_name"]} : ${geoValue.text}`
async function checkGeoCoverage(geoType, geoValue) {
const notCoveredSignals = [];

try {
const result = await $.ajax({
url: "epidata/covidcast/geo_coverage/",
type: 'GET',
data: {
'geo': `${geoType}:${geoValue}`
}
dataSets[`${signal["signal"]}_${geographicValue}`] = {
color: '#'+(Math.random() * 0xFFFFFF << 0).toString(16).padStart(6, '0'),
title: "value",
params: {
_endpoint: signal["_endpoint"],
data_source: signal["data_source"],
signal: signal["signal"],
time_type: signal["time_type"],
geo_type: geographicType,
geo_value: geographicValue,
custom_title: epivisCustomTitle
}
});

checkedSignalMembers.filter(signal => signal["_endpoint"] === "covidcast").forEach(signal => {
const covered = result["epidata"].some(
e => (e.source === signal.data_source && e.signal === signal.signal)
);
if (!covered) {
notCoveredSignals.push(signal);
}
})
});

});

var requestParams = [];
for (var key in dataSets) {
requestParams.push(dataSets[key]);
return notCoveredSignals;
} catch (error) {
console.error('Error fetching geo coverage:', error);
return notCoveredSignals;
}

var urlParamsEncoded = btoa(`{"datasets":${JSON.stringify(requestParams)}}`);

var linkToEpivis = `${epiVisUrl}#${urlParamsEncoded}`
window.open(linkToEpivis, '_blank').focus();
}


// Function to update the modal content
function updateSelectedSignals(dataSource, signalDisplayName, signalSet, signal) {
var selectedSignalsList = document.getElementById('selectedSignalsList');
Expand Down Expand Up @@ -115,6 +78,7 @@ function addSelectedSignal(element) {
document.getElementById(`${element.dataset.datasource}_${element.dataset.signal}`).remove();
}

indicatorHandler.indicators = checkedSignalMembers;

if (checkedSignalMembers.length > 0) {
$("#showSelectedSignalsButton").show();
Expand All @@ -123,6 +87,33 @@ function addSelectedSignal(element) {
}
}

$("#showSelectedSignalsButton").click(function() {
alertPlaceholder.innerHTML = "";
if (!indicatorHandler.checkForCovidcastIndicators()) {
$("#geographic_value").prop("disabled", true);
} else {
$("#geographic_value").prop("disabled", false);
}
$('#geographic_value').select2("data").forEach(geo => {
checkGeoCoverage(geo.geoType, geo.id).then((notCoveredSignals) => {
if (notCoveredSignals.length > 0) {
showNotCoveredGeoWarningMessage(notCoveredSignals, geo.text);
}
})
});
var otherEndpointLocationsWarning = `<div class="alert alert-info" data-mdb-alert-init role="alert">` +
` <div>Please, note that some indicator sets may require to select location(s) that is/are different from location above.<br> `
nonCovidcastSignalSets = [...new Set(checkedSignalMembers.filter(signal => signal["_endpoint"] != "covidcast").map((signal) => signal["signal_set"]))];
otherEndpointLocationsWarning += `Different location is required for following signal set(s): ${nonCovidcastSignalSets.join(", ")}`
otherEndpointLocationsWarning += `</div></div>`
if (indicatorHandler.getFluviewIndicators().length > 0) {
$("#differentLocationNote").html(otherEndpointLocationsWarning)
if (document.getElementsByName("fluviewRegions").length === 0) {
indicatorHandler.showFluviewRegions();
}
}
});

// Add an event listener to each 'bulk-select' element
let bulkSelectDivs = document.querySelectorAll('.bulk-select');
bulkSelectDivs.forEach(div => {
Expand Down Expand Up @@ -254,116 +245,6 @@ function format (signalSetId, relatedSignals, signalSetDescription) {
return data;
}


function exportData() {
var geographicValues = $('#geographic_value').select2('data');
geographicValues = Object.groupBy(geographicValues, ({ geoType }) => [geoType])
var geoTypes = Object.keys(geographicValues);

var startDate = document.getElementById('start_date').value;
var endDate = document.getElementById('end_date').value;

var manualDataExport = "To download data, please click on the link or copy/paste command into your terminal: \n\n"
var requests = [];

checkedSignalMembers.forEach((signal) => {
geoTypes.forEach((geoType) => {
var geoValues = geographicValues[geoType].map((el) => (typeof el.id === 'string') ? el.id.toLowerCase() : el.id).join(",");
if (signal["time_type"] === "week") {
var request = $.ajax({
url: "get_epiweek/",
type: 'POST',
async: true,
data: {
csrfmiddlewaretoken: csrf_token,
start_date: startDate,
end_date: endDate,
},
success: function (result) {
var exportUrl = `https://api.delphi.cmu.edu/epidata/covidcast/csv?signal=${signal["data_source"]}:${signal["signal"]}&start_day=${result.start_date}&end_day=${result.end_date}&geo_type=${geoType}&geo_values=${geoValues}`;
manualDataExport += `wget --content-disposition <a href="${exportUrl}">${exportUrl}</a>\n`
}
})
requests.push(request);
} else {
var exportUrl = `https://api.delphi.cmu.edu/epidata/covidcast/csv?signal=${signal["data_source"]}:${signal["signal"]}&start_day=${startDate}&end_day=${endDate}&geo_type=${geoType}&geo_values=${geoValues}`;
manualDataExport += `wget --content-disposition <a href="${exportUrl}">${exportUrl}</a>\n`
}
});
});
$.when.apply($, requests).then(function() {
$('#modeSubmitResult').html(manualDataExport);
})

}

function previewData() {
var geographicValues = $('#geographic_value').select2('data');
geographicValues = Object.groupBy(geographicValues, ({ geoType }) => [geoType])
var geoTypes = Object.keys(geographicValues);
var previewExample = [];
var requests = [];

var startDate = document.getElementById("start_date").value;
var endDate = document.getElementById("end_date").value;

checkedSignalMembers.forEach((signal) => {
var timeValues;

if (signal["time_type"] === "week") {
$.ajax({
url: "get_epiweek/",
type: 'POST',
async: false,
data: {
csrfmiddlewaretoken: csrf_token,
start_date: startDate,
end_date: endDate,
},
success: function (result) {
timeValues = `${result.start_date}-${result.end_date}`;
}
})
};

var requestSent = false;
if (!requestSent) {
geoTypes.forEach((geoType) => {
var geoValues = geographicValues[geoType].map((el) => (typeof el.id === 'string') ? el.id.toLowerCase() : el.id).join(",");
$('#loader').show();
timeValues = signal["time_type"] === "week" ? timeValues : `${startDate}--${endDate}`;
var request = $.ajax({
url: "epidata/covidcast/",
type: 'GET',
async: true,
data: {
'time_type': signal["time_type"],
'time_values': timeValues,
'data_source': signal["data_source"],
'signal': signal["signal"],
'geo_type': geoType,
'geo_values': geoValues
},
success: function (result) {
if (result["epidata"].length != 0) {
previewExample.push({epidata: result["epidata"][0], result: result["result"], message: result["message"]})
} else {
previewExample.push({epidata: result["epidata"], result: result["result"], message: result["message"]})
}
}
})
requests.push(request);
})
}
})
$.when.apply($, requests).then(function() {
$('#loader').hide();
$('#modeSubmitResult').html(JSON.stringify(previewExample, null, 2));
requestSent = true;
})
}


// Plot/Export/Preview data block

var currentMode = 'epivis';
Expand Down Expand Up @@ -439,22 +320,31 @@ function showNotCoveredGeoWarningMessage(notCoveredSignals, geoValue) {

$('#geographic_value').on('select2:select', function (e) {
var geo = e.params.data;
var notCoveredSignals = checkGeoCoverage(geo.geoType, geo.id)
if (notCoveredSignals.length > 0) {
showNotCoveredGeoWarningMessage(notCoveredSignals, geo.text);
checkGeoCoverage(geo.geoType, geo.id).then((notCoveredSignals) => {
if (notCoveredSignals.length > 0) {
showNotCoveredGeoWarningMessage(notCoveredSignals, geo.text);
}
}
);
});


function submitMode(event) {
event.preventDefault();
var geographicValues = $('#geographic_value').select2('data');
if (indicatorHandler.checkForCovidcastIndicators()) {
if (geographicValues.length === 0) {
appendAlert("Please select at least one geographic location", "warning")
return;
}
}

if (currentMode === 'epivis') {
plotData();
indicatorHandler.plotData();
} else if (currentMode === 'export') {
exportData();
indicatorHandler.exportData();
} else {
previewData();
indicatorHandler.previewData();
}
}

Expand Down
13 changes: 12 additions & 1 deletion src/datasources/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,21 @@ def process_links(row, dua_column_name="DUA", link_column_name="Link"):
links.append(link.id)
else:
for match in matches:
link, _ = Link.objects.get_or_create(url=match[1], defaults={'link_type': match[0], })
link, _ = Link.objects.get_or_create(
url=match[1],
defaults={
"link_type": match[0],
},
)
links.append(link.id)
row["Links"] = links


def process_datasource_name(row):
if row["Name"]:
row["Name"] = row["Name"].capitalize()


def process_datasources(row):
datasource, _ = DataSource.objects.get_or_create(
name=row["DB Source"],
Expand Down Expand Up @@ -67,5 +77,6 @@ class Meta:
skip_unchanged = True

def before_import_row(self, row, **kwargs):
process_datasource_name(row)
process_links(row)
process_datasources(row)
Loading
Loading