use of org.sagebionetworks.bridge.models.schedules2.adherence.AdherenceState in project BridgeServer2 by Sage-Bionetworks.
the class EventStreamAdherenceReportGenerator method generate.
public EventStreamAdherenceReport generate(AdherenceState state) {
LocalDate earliestDate = LATEST_LOCAL_DATE;
LocalDate latestDate = EARLIEST_LOCAL_DATE;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
String earliestEventId = null;
for (TimelineMetadata meta : state.getMetadata()) {
if (meta.isTimeWindowPersistent()) {
continue;
}
int startDay = meta.getSessionInstanceStartDay();
int endDay = meta.getSessionInstanceEndDay();
String eventId = meta.getSessionStartEventId();
Integer daysSinceEvent = state.getDaysSinceEventById(eventId);
DateTime timestamp = state.getEventTimestampById(eventId);
LocalDate localDate = (timestamp == null) ? null : timestamp.toLocalDate();
LocalDate startDate = (localDate == null) ? null : localDate.plusDays(startDay);
LocalDate endDate = (localDate == null) ? null : localDate.plusDays(endDay);
// Produce one report for each event ID. Create them lazily as we find each eventId;
EventStream stream = state.getEventStreamById(eventId);
stream.setDaysSinceEvent(daysSinceEvent);
stream.setStudyBurstId(meta.getStudyBurstId());
stream.setStudyBurstNum(meta.getStudyBurstNum());
// Get the adherence information for this session instance and derive the state of the session
AdherenceRecord record = state.getAdherenceRecordByGuid(meta.getSessionInstanceGuid());
SessionCompletionState sessionState = calculateSessionState(record, startDay, endDay, daysSinceEvent);
// Retrieve the event stream. All items in this stream start on the same day, but can end on different days
EventStreamDay eventStreamDay = state.getEventStreamDayByKey(meta);
eventStreamDay.setStartDay(startDay);
eventStreamDay.setStartDate(startDate);
// Create a window entry (windows are flattened in the list of timeline metadata records...all session
// records in the metadata table are actually session window records)
EventStreamWindow windowEntry = new EventStreamWindow();
windowEntry.setSessionInstanceGuid(meta.getSessionInstanceGuid());
windowEntry.setTimeWindowGuid(meta.getTimeWindowGuid());
windowEntry.setEndDay(endDay);
windowEntry.setEndDate(endDate);
windowEntry.setState(sessionState);
eventStreamDay.addTimeWindow(windowEntry);
if (startDate != null && startDate.isBefore(earliestDate)) {
earliestDate = startDate;
earliestEventId = eventStreamDay.getStartEventId();
}
if (endDate != null && endDate.isAfter(latestDate)) {
latestDate = endDate;
}
if (min > startDay) {
min = startDay;
}
if (max < endDay) {
max = endDay;
}
}
DayRange dayRange = null;
if (min <= max) {
dayRange = new DayRange(min, max);
}
DateRange dateRange = null;
if (earliestDate.isBefore(latestDate)) {
dateRange = new DateRange(earliestDate, latestDate);
}
EventStreamAdherenceReport report = new EventStreamAdherenceReport();
report.setTimestamp(state.getNow());
report.setClientTimeZone(state.getClientTimeZone());
report.setAdherencePercent(state.calculateAdherencePercentage());
report.setDayRangeOfAllStreams(dayRange);
report.setDateRangeOfAllStreams(dateRange);
report.setEarliestEventId(earliestEventId);
for (String eventId : state.getStreamEventIds()) {
report.getStreams().add(state.getEventStreamById(eventId));
}
report.setProgression(calculateProgress(state, report.getStreams()));
return report;
}
use of org.sagebionetworks.bridge.models.schedules2.adherence.AdherenceState in project BridgeServer2 by Sage-Bionetworks.
the class StudyAdherenceReportGenerator method generate.
public StudyAdherenceReport generate(AdherenceState state) {
EventStreamAdherenceReport eventReport = EventStreamAdherenceReportGenerator.INSTANCE.generate(state);
LocalDate studyStartDate = getStudyStartDate(state, eventReport);
EventStream studyStream = new EventStream();
Set<String> unsetEventIds = new HashSet<>();
Set<String> unscheduledSessions = new HashSet<>();
Map<String, DateTime> eventTimestamps = new HashMap<>();
LocalDate todayLocal = state.getNow().toLocalDate();
// Remap all the event streams to one event stream — the study event stream
for (EventStream stream : eventReport.getStreams()) {
for (List<EventStreamDay> days : stream.getByDayEntries().values()) {
for (EventStreamDay oneDay : days) {
if (oneDay.getStartDate() != null) {
// Map this stream into the study stream
Integer numDays = Days.daysBetween(studyStartDate, oneDay.getStartDate()).getDays();
studyStream.addEntry(numDays, oneDay);
String eventId = oneDay.getStartEventId();
eventTimestamps.put(eventId, state.getEventTimestampById(eventId));
} else {
// Note for the report the events and sessions that are not applicable to this user
unsetEventIds.add(oneDay.getStartEventId());
unscheduledSessions.add(oneDay.getSessionName());
}
}
}
}
// study-wide progress
ParticipantStudyProgress progression = calculateProgress(state, ImmutableList.of(studyStream));
// Break this study stream down into weeks. TreeMap sorts the weeks by week number
Map<Integer, StudyReportWeek> weekMap = new TreeMap<>();
for (Map.Entry<Integer, List<EventStreamDay>> entry : studyStream.getByDayEntries().entrySet()) {
int week = entry.getKey() / 7;
// Day of week can be negative if the week was negative... just flip it
int dayOfWeek = Math.abs(entry.getKey() % 7);
StudyReportWeek oneWeek = weekMap.get(week);
if (oneWeek == null) {
oneWeek = new StudyReportWeek();
oneWeek.setStartDate(studyStartDate.plusDays(week * 7));
oneWeek.setWeekInStudy(week + 1);
weekMap.put(week, oneWeek);
}
List<EventStreamDay> days = oneWeek.getByDayEntries().get(dayOfWeek);
days.addAll(entry.getValue());
}
;
Collection<StudyReportWeek> weeks = weekMap.values();
StudyReportWeek currentWeek = null;
for (StudyReportWeek oneWeek : weeks) {
calculateRowsAndLabels(oneWeek, todayLocal);
// If there’s a day in this week that is “today”, set a flag for all day entries on that day
LocalDate firstDayOfWeek = oneWeek.getStartDate();
LocalDate lastDayOfWeek = oneWeek.getStartDate().plusDays(7);
if (BridgeUtils.isLocalDateInRange(firstDayOfWeek, lastDayOfWeek, todayLocal)) {
currentWeek = oneWeek;
for (List<EventStreamDay> days : oneWeek.getByDayEntries().values()) {
for (EventStreamDay oneDay : days) {
if (oneDay.getStartDate().isEqual(todayLocal)) {
days.forEach(day -> day.setToday(true));
}
}
}
}
// current one) but not the weeks after todayLocal.
if (BridgeUtils.isLocalDateInRange(oneWeek.getStartDate(), null, todayLocal)) {
int weekAdh = AdherenceUtils.calculateAdherencePercentage(oneWeek.getByDayEntries());
oneWeek.setAdherencePercent(weekAdh);
}
}
Integer adherence = null;
if (progression != ParticipantStudyProgress.NO_SCHEDULE) {
adherence = calculateAdherencePercentage(ImmutableList.of(studyStream));
}
NextActivity nextActivity = null;
if (currentWeek == null) {
nextActivity = getNextActivity(weeks, todayLocal);
}
DateRange dateRange = null;
if (eventReport.getDateRangeOfAllStreams() != null) {
dateRange = new DateRange(studyStartDate, eventReport.getDateRangeOfAllStreams().getEndDate());
}
for (StudyReportWeek oneWeek : weeks) {
for (List<EventStreamDay> days : oneWeek.getByDayEntries().values()) {
for (EventStreamDay oneDay : days) {
oneDay.setStudyBurstId(null);
oneDay.setStudyBurstNum(null);
oneDay.setSessionName(null);
oneDay.setWeek(null);
oneDay.setStartDay(null);
for (EventStreamWindow window : oneDay.getTimeWindows()) {
window.setEndDay(null);
// This cannot be removed, or the window will be removed from persisted collection
// window.setTimeWindowGuid(null);
}
}
}
}
StudyAdherenceReport report = new StudyAdherenceReport();
report.setDateRange(dateRange);
report.setWeeks(weeks);
report.setCurrentWeek(currentWeek);
report.setNextActivity(nextActivity);
report.setProgression(progression);
report.setAdherencePercent(adherence);
report.setEventTimestamps(eventTimestamps);
report.setUnsetEventIds(unsetEventIds);
report.setUnscheduledSessions(unscheduledSessions);
return report;
}
use of org.sagebionetworks.bridge.models.schedules2.adherence.AdherenceState in project BridgeServer2 by Sage-Bionetworks.
the class ParticipantScheduleGenerator method generate.
public ParticipantSchedule generate(AdherenceState state, Timeline timeline) {
Multimap<LocalDate, ScheduledSession> chronology = LinkedHashMultimap.create();
LocalDate earliestDate = LATEST_LOCAL_DATE;
LocalDate latestDate = EARLIEST_LOCAL_DATE;
Map<String, DateTime> eventTimestamps = new HashMap<>();
for (ScheduledSession schSession : timeline.getSchedule()) {
String eventId = schSession.getStartEventId();
DateTime eventTimestamp = state.getEventTimestampById(eventId);
if (eventTimestamp == null) {
continue;
}
LocalDate startDate = eventTimestamp.plusDays(schSession.getStartDay()).toLocalDate();
LocalDate endDate = eventTimestamp.plusDays(schSession.getEndDay()).toLocalDate();
eventTimestamps.put(eventId, eventTimestamp);
ScheduledSession.Builder builder = schSession.toBuilder();
builder.withStartDate(startDate);
builder.withEndDate(endDate);
if (startDate.isBefore(earliestDate)) {
earliestDate = startDate;
}
if (endDate.isAfter(latestDate)) {
latestDate = endDate;
}
for (ScheduledAssessment schAssessment : schSession.getAssessments()) {
ScheduledAssessment.Builder asmtBuilder = new ScheduledAssessment.Builder().withRefKey(schAssessment.getRefKey()).withInstanceGuid(schAssessment.getInstanceGuid());
builder.withScheduledAssessment(asmtBuilder.build());
}
// null these out, not useful
schSession.getTimeWindow().setGuid(null);
builder.withStartDay(null);
builder.withEndDay(null);
chronology.put(startDate, builder.build());
}
// chronology.size() is the total number of pairs, not the total number of keys (and thus correct).
List<ScheduledSession> scheduledSessions = Lists.newArrayListWithCapacity(chronology.size());
for (LocalDate date : chronology.keySet()) {
scheduledSessions.addAll(chronology.get(date));
}
scheduledSessions.sort(SCHEDULED_SESSION_COMPARATOR);
DateRange range = null;
if (earliestDate.isBefore(latestDate)) {
range = new DateRange(earliestDate, latestDate);
}
ParticipantSchedule schedule = new ParticipantSchedule();
schedule.setCreatedOn(state.getNow());
schedule.setClientTimeZone(state.getClientTimeZone());
schedule.setDateRange(range);
schedule.setSchedule(scheduledSessions);
schedule.setSessions(timeline.getSessions().stream().map(SessionInfo::createScheduleEntry).collect(toList()));
schedule.setAssessments(timeline.getAssessments());
schedule.setStudyBursts(timeline.getStudyBursts());
schedule.setEventTimestamps(eventTimestamps);
return schedule;
}
use of org.sagebionetworks.bridge.models.schedules2.adherence.AdherenceState in project BridgeServer2 by Sage-Bionetworks.
the class EventStreamAdherenceReportGeneratorTest method generate_metadataCopiedToReport.
@Test
public void generate_metadataCopiedToReport() throws Exception {
// We will focus on calculation of the completion states in the report, but here let's
// verify the metadata is being copied over into the report.
AdherenceState state = createState(NOW, META1, null, null);
EventStreamAdherenceReport report = INSTANCE.generate(state);
assertEquals(report.getTimestamp(), NOW.withZone(DateTimeZone.forID("America/Chicago")));
assertEquals(report.getAdherencePercent(), 100);
assertEquals(report.getStreams().size(), 1);
EventStream stream = report.getStreams().get(0);
assertEquals(stream.getStartEventId(), "sessionStartEventId");
assertEquals(stream.getStudyBurstId(), "studyBurstId");
assertEquals(stream.getStudyBurstNum(), Integer.valueOf(1));
assertEquals(stream.getByDayEntries().size(), 1);
assertEquals(stream.getByDayEntries().get(Integer.valueOf(13)).size(), 1);
EventStreamDay day = stream.getByDayEntries().get(Integer.valueOf(13)).get(0);
assertEquals(day.getSessionGuid(), "sessionGuid");
assertEquals(day.getSessionGuid(), "sessionGuid");
assertEquals(day.getStartDay(), (Integer) 13);
assertEquals(day.getTimeWindows().get(0).getSessionInstanceGuid(), "sessionInstanceGuid");
assertEquals(day.getTimeWindows().get(0).getTimeWindowGuid(), "timeWindowGuid");
assertEquals(day.getTimeWindows().get(0).getEndDay(), (Integer) 15);
assertEquals(day.getTimeWindows().get(0).getState(), NOT_APPLICABLE);
}
use of org.sagebionetworks.bridge.models.schedules2.adherence.AdherenceState in project BridgeServer2 by Sage-Bionetworks.
the class EventStreamAdherenceReportGeneratorTest method constructorUsesNowTimestampTimeZone.
@Test
public void constructorUsesNowTimestampTimeZone() {
StudyActivityEvent event = new StudyActivityEvent.Builder().withEventId("enrollment").withTimestamp(MODIFIED_ON).build();
AdherenceState.Builder builder = new AdherenceState.Builder();
builder.withMetadata(ImmutableList.of());
builder.withEvents(ImmutableList.of(event));
builder.withAdherenceRecords(ImmutableList.of());
builder.withNow(NOW);
AdherenceState state = builder.build();
assertEquals(state.getTimeZone().toString(), "-07:00");
}
Aggregations