Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import io.micronaut.core.annotation.Introspected;
import lombok.Getter;
import lombok.ToString;
import org.breedinginsight.api.model.v1.request.query.FilterRequest;
import org.breedinginsight.api.model.v1.request.query.SearchRequest;
import org.breedinginsight.brapi.v1.model.request.query.BrapiQuery;
Expand All @@ -14,6 +15,7 @@

@Getter
@Introspected
@ToString
public class ExperimentExportQuery {
private FileType fileExtension;
private String dataset;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
Expand Down Expand Up @@ -99,6 +100,8 @@ public DownloadFile exportObservations(
Program program,
UUID experimentId,
ExperimentExportQuery params) throws IOException, DoesNotExistException, ApiException {
String logHash = UUID.randomUUID().toString();
log.debug(logHash + ": exporting experiment: "+experimentId+", params: " + params);
StreamedFile downloadFile;
boolean isDataset = false;
List<BrAPIObservation> dataset = new ArrayList<>();
Expand All @@ -110,6 +113,7 @@ public DownloadFile exportObservations(
FileType fileType = params.getFileExtension();

// get requested environments for the experiment
log.debug(logHash + ": fetching environments for export");
List<BrAPIStudy> expStudies = studyDAO.getStudiesByExperimentID(experimentId, program);
if (!requestedEnvIds.isEmpty()) {
expStudies = expStudies
Expand All @@ -120,6 +124,7 @@ public DownloadFile exportObservations(
expStudies.forEach(study -> studyByDbId.putIfAbsent(study.getStudyDbId(), study));

// get the OUs for the requested environments
log.debug(logHash + ": fetching OUs for export");
List<BrAPIObservationUnit> ous = new ArrayList<>();
Map<String, BrAPIObservationUnit> ouByOUDbId = new HashMap<>();
try {
Expand All @@ -129,21 +134,23 @@ public DownloadFile exportObservations(
ous.addAll(studyOUs);
}
} catch (ApiException err) {
log.error("Error fetching observation units for a study by its DbId" +
log.error(logHash + ": Error fetching observation units for a study by its DbId" +
Utilities.generateApiExceptionLogMessage(err), err);
}

// make columns present in all exports
List<Column> columns = ExperimentFileColumns.getOrderedColumns();

// add columns for requested dataset obsvars and timestamps
log.debug(logHash + ": fetching experiment for export");
BrAPITrial experiment = getExperiment(program, experimentId);
if ((StringUtils.isBlank(params.getDataset()) || "observations".equalsIgnoreCase(params.getDataset())) &&
experiment.getAdditionalInfo().getAsJsonObject().get(BrAPIAdditionalInfoFields.OBSERVATION_DATASET_ID) != null) {
String obsDatasetId = experiment
.getAdditionalInfo().getAsJsonObject()
.get(BrAPIAdditionalInfoFields.OBSERVATION_DATASET_ID).getAsString();
isDataset = true;
log.debug(logHash + ": fetching dataset observation variables for export");
obsVars = getDatasetObsVars(obsDatasetId, program);

// make additional columns in the export for each obs variable and obs variable timestamp
Expand All @@ -153,12 +160,19 @@ public DownloadFile exportObservations(

// make export rows from any observations
if (isDataset) {
log.debug(logHash + ": fetching observations for export");
dataset = observationDAO.getObservationsByTrialDbId(List.of(experiment.getTrialDbId()), program);
}
if (!requestedEnvIds.isEmpty()) {
log.debug(logHash + ": filtering observations to only requested environments for export");
dataset = filterDatasetByEnvironment(dataset, requestedEnvIds, studyByDbId);
}

log.debug(logHash + ": fetching program's germplasm for export");
List<BrAPIGermplasm> programGermplasm = germplasmDAO.getGermplasmsByDBID(ouByOUDbId.values().stream().map(BrAPIObservationUnit::getGermplasmDbId).collect(Collectors.toList()), program.getId());
Map<String, BrAPIGermplasm> programGermplasmByDbId = programGermplasm.stream().collect(Collectors.toMap(BrAPIGermplasm::getGermplasmDbId, Function.identity()));

log.debug(logHash + ": populating rows for export");
// update rowByOUId
addBrAPIObsToRecords(
dataset,
Expand All @@ -168,19 +182,21 @@ public DownloadFile exportObservations(
studyByDbId,
rowByOUId,
params.isIncludeTimestamps(),
obsVars
obsVars,
programGermplasmByDbId
);

// make export rows for OUs without observations
if (rowByOUId.size() < ous.size()) {
for (BrAPIObservationUnit ou: ous) {
String ouId = getOUId(ou);
if (!rowByOUId.containsKey(ouId)) {
rowByOUId.put(ouId, createExportRow(experiment, program, ou, studyByDbId));
rowByOUId.put(ouId, createExportRow(experiment, program, ou, studyByDbId, programGermplasmByDbId));
}
}
}

log.debug(logHash + ": writing data to file for export");
// write export data to requested file format
List<Map<String, Object>> exportRows = new ArrayList<>(rowByOUId.values());
if (fileType.equals(FileType.CSV)){
Expand All @@ -191,7 +207,10 @@ public DownloadFile exportObservations(

String envFilenameFragment = params.getEnvironments() == null ? "All Environments" : params.getEnvironments();
String fileName = makeFileName(experiment, program, envFilenameFragment) + fileType.getExtension();
return new DownloadFile(fileName, downloadFile);
DownloadFile retFile = new DownloadFile(fileName, downloadFile);

log.debug(logHash + ": completed export of experiment: " + experimentId + ", params: " + params);
return retFile;
}

private void addBrAPIObsToRecords(
Expand All @@ -202,7 +221,8 @@ private void addBrAPIObsToRecords(
Map<String, BrAPIStudy> studyByDbId,
Map<String, Map<String, Object>> rowByOUId,
boolean includeTimestamp,
List<BrAPIObservationVariable> obsVars) throws ApiException, DoesNotExistException {
List<BrAPIObservationVariable> obsVars,
Map<String, BrAPIGermplasm> programGermplasmByDbId) throws ApiException, DoesNotExistException {
Map<String, BrAPIObservationVariable> varByDbId = new HashMap<>();
obsVars.forEach(var -> varByDbId.put(var.getObservationVariableDbId(), var));
for (BrAPIObservation obs: dataset) {
Expand All @@ -220,7 +240,7 @@ private void addBrAPIObsToRecords(
} else {

// otherwise make a new row
Map<String, Object> row = createExportRow(experiment, program, ou, studyByDbId);
Map<String, Object> row = createExportRow(experiment, program, ou, studyByDbId, programGermplasmByDbId);
addObsVarDataToRow(row, obs, includeTimestamp, var, program);
rowByOUId.put(ouId, row);
}
Expand Down Expand Up @@ -291,7 +311,8 @@ private Map<String, Object> createExportRow(
BrAPITrial experiment,
Program program,
BrAPIObservationUnit ou,
Map<String, BrAPIStudy> studyByDbId) throws ApiException, DoesNotExistException {
Map<String, BrAPIStudy> studyByDbId,
Map<String, BrAPIGermplasm> programGermplasmByDbId) throws ApiException, DoesNotExistException {
HashMap<String, Object> row = new HashMap<>();

// get OU id, germplasm, and study
Expand All @@ -300,7 +321,7 @@ private Map<String, Object> createExportRow(
String.format("%s/%s", referenceSource, ExternalReferenceSource.OBSERVATION_UNITS.getName()))
.orElseThrow(() -> new RuntimeException("observation unit id not found"));
String ouId = ouXref.getReferenceID();
BrAPIGermplasm germplasm = germplasmDAO.getGermplasmByDBID(ou.getGermplasmDbId(), program.getId())
BrAPIGermplasm germplasm = Optional.ofNullable(programGermplasmByDbId.get(ou.getGermplasmDbId()))
.orElseThrow(() -> new DoesNotExistException("Germplasm not returned from BrAPI service"));
BrAPIStudy study = studyByDbId.get(ou.getStudyDbId());

Expand Down