zinzen 0.3.0

Algorithm for auto-scheduling time-constrained tasks on a timeline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use chrono::NaiveDateTime;
use serde::Deserialize;

use std::cmp::{max, min};
use std::fmt;
use std::ops::Add;
use std::vec;

use crate::models::activity::ActivityStatus::Impossible;
use crate::models::budget::{CalendarBudget, TimeBudget};
use crate::models::calendar_interval::CalIntStatus;
use crate::models::interval::Interval;
use crate::services::interval_helper;

use super::goal::Goal;
use super::{calendar::Calendar, time_grid};

/// A simple goal whose total duration exceeds this many slots is scheduled in
/// single-slot blocks (min_block_size = 1) instead of one contiguous block, so
/// the placer can fit it around other commitments. Historically "8 hours".
const MAX_CONTIGUOUS_SIMPLE_BLOCK_SLOTS: usize = 8 * time_grid::SLOTS_PER_HOUR;

#[derive(Clone)]
pub struct Activity {
    pub goal_id: String,
    pub activity_type: ActivityType,
    pub title: String,
    pub min_block_size: usize,
    pub max_block_size: usize,
    pub total_duration: usize,
    pub duration_left: usize,
    pub status: ActivityStatus,
    pub start: NaiveDateTime,
    pub deadline: Option<NaiveDateTime>,
    pub compatible_intervals: Vec<Interval>,
    pub incompatible_intervals: Vec<Interval>,
    pub flex: Option<usize>,
}
impl Activity {
    pub(crate) fn reset_compatible_intervals(&mut self) {
        self.compatible_intervals = vec![];
        self.flex = None;
    }
}
impl Activity {
    pub(crate) fn flex_read_only(&self) -> Option<usize> {
        self.flex
    }
}

impl Activity {
    pub(crate) fn remove_interval(&mut self, interval_to_remove: &Interval) {
        //Attention: also unclaim intervals with calendar separately!
        //This is done when recalculating flex - so suffice to register incompatible ones here
        let mut result: Vec<Interval> = Vec::with_capacity(self.compatible_intervals.len());
        for own_interval in &self.compatible_intervals {
            if interval_to_remove.end <= own_interval.start {
                //no more possible overlaps
                result.push(own_interval.clone());
                continue;
            }
            if interval_to_remove.start >= own_interval.end {
                //no overlap yet
                result.push(own_interval.clone());
                continue;
            }

            let overlap_start = max(interval_to_remove.start, own_interval.start);
            let overlap_end = min(interval_to_remove.end, own_interval.end);

            self.flex = None; //reset flex as this will be impacted by changing compatible intervals

            self.incompatible_intervals.push(Interval {
                //remove this - irrespective if anything unusable left over at beginning and/or end
                //merging this with possible unusable bits gives calendar extra work
                //keeping them separate will align with start/end of cal_intervals
                start: overlap_start,
                end: overlap_end,
            });

            if overlap_start == own_interval.start && overlap_end == own_interval.end {
                //total overlap
                continue;
            }

            //todo: many ifs could be collapsed a bit
            if overlap_start == own_interval.start {
                //something at end left over
                if own_interval.end - overlap_end >= self.min_block_size {
                    //something usable at end left over
                    result.push(Interval {
                        start: overlap_end,
                        end: own_interval.end,
                    });
                } else {
                    //nothing usable left over
                    self.incompatible_intervals.push(Interval {
                        start: overlap_end,
                        end: own_interval.end,
                    });
                }
                continue;
            }
            if overlap_end == own_interval.end {
                //something at beginning left over
                if overlap_start - own_interval.start >= self.min_block_size {
                    //something usable at the beginning left over
                    result.push(Interval {
                        start: own_interval.start,
                        end: overlap_start,
                    });
                } else {
                    //nothing usable left over - don't merge as calendar won't recognize them
                    self.incompatible_intervals.push(Interval {
                        start: own_interval.start,
                        end: overlap_start,
                    });
                }
                continue;
            }
            //only one option left : overlap in middle
            if overlap_start - own_interval.start >= self.min_block_size {
                //something usable at beginning left over
                result.push(Interval {
                    start: own_interval.start,
                    end: overlap_start,
                });
            } else {
                self.incompatible_intervals.push(Interval {
                    start: own_interval.start,
                    end: overlap_start,
                });
            }
            if own_interval.end - overlap_end >= self.min_block_size {
                //something usable at end left over
                result.push(Interval {
                    start: overlap_end,
                    end: own_interval.end,
                });
            } else {
                self.incompatible_intervals.push(Interval {
                    start: overlap_end,
                    end: own_interval.end,
                });
            }
        }
        self.compatible_intervals = result;
        if !self.incompatible_intervals.is_empty() {
            self.flex = None;
        }
    }
}

impl Activity {
    pub(crate) fn flex_reset(&mut self) {
        self.flex = None;
    }
}

impl Activity {
    pub fn mark_impossible(&mut self) {
        self.status = Impossible;
    }

    pub fn flex(&mut self) -> usize {
        if let Some(flex) = self.flex {
            crate::log_debug!("Flex {} from cache.", self.flex.unwrap());
            return flex;
        }

        //assume non-contiguous intervals
        let mut flex: usize = 0;
        for interval in &self.compatible_intervals {
            let interval_size = interval.end - interval.start;

            #[cfg(debug_assertions)]
            assert!(
                self.min_block_size <= interval_size,
                "Placer should remove+unregister INcompatible intervals before calling flex."
            );
            let interval_flex = interval_size - self.min_block_size + 1;
            flex += interval_flex;
        }
        self.flex = Some(flex);
        crate::log_debug!("Flex {} calculated.", flex);
        flex
    }

    pub(crate) fn get_simple_activities(goal: &Goal, calendar: &mut Calendar) -> Vec<Activity> {
        let (adjusted_goal_start, adjusted_goal_deadline) = goal.get_adj_start_deadline(calendar);
        let mut activities: Vec<Activity> = Vec::with_capacity(1);

        if let Some(mut activity_total_duration) = goal.min_duration {
            // Uniform block size: minDuration is both total and contiguous chunk size,
            // unless the total exceeds MAX_CONTIGUOUS_SIMPLE_BLOCK_SLOTS.
            let mut min_block_size = activity_total_duration;
            if activity_total_duration > MAX_CONTIGUOUS_SIMPLE_BLOCK_SLOTS {
                min_block_size = 1;
            }
            let max_block_size = min_block_size;

            let periods = calendar.get_periods_for(&goal.id);

            let mut adjusted_activity_deadline =
                adjusted_goal_deadline.unwrap_or(calendar.end_date_time); //regular case
            if goal.deadline.is_none() && !calendar.is_participating_in_a_budget(&goal.id) {
                //special case for simple goals without a deadline
                //they are allowed to be scheduled on the 'edge', crossing the calendar week boundary
                adjusted_activity_deadline = adjusted_goal_deadline.unwrap_or(
                    calendar
                        .end_date_time
                        .add(time_grid::slot_span(time_grid::SLOTS_PER_DAY as i64)),
                );
            };

            let compatible_intervals: Vec<Interval> = interval_helper::get_compatible_intervals(
                calendar,
                periods,
                adjusted_goal_start,
                adjusted_activity_deadline,
                &goal.not_on.clone(),
            );

            let mut already_placed_for_goal_id: usize = 0;
            for cal_interval in &calendar.intervals {
                match &cal_interval.status {
                    CalIntStatus::Claimable(_) => {}
                    CalIntStatus::Occupied(_, goal_id) => {
                        if goal.id.eq(goal_id) {
                            already_placed_for_goal_id +=
                                cal_interval.interval.end - cal_interval.interval.start;
                        }
                    }
                }
            }

            if already_placed_for_goal_id >= activity_total_duration {
                return vec![];
            }
            activity_total_duration -= already_placed_for_goal_id;

            crate::log_dbg!(&compatible_intervals);
            let activity = Activity {
                goal_id: goal.id.clone(),
                activity_type: ActivityType::SimpleGoal,
                title: goal.title.clone(),
                min_block_size,
                max_block_size,
                total_duration: activity_total_duration,
                duration_left: activity_total_duration,
                status: ActivityStatus::Unprocessed,
                start: adjusted_goal_start,
                deadline: goal.deadline,
                compatible_intervals,
                incompatible_intervals: vec![],
                flex: None,
            };
            crate::log_dbg!(&activity);
            activities.push(activity);
        }

        activities
    }

    pub(crate) fn get_activities_to_get_to_min_day_budget(
        budget: &CalendarBudget,
        calendar: &Calendar,
        time_budget: &TimeBudget,
    ) -> Vec<Activity> {
        let mut activities: Vec<Activity> = Vec::with_capacity(1);
        let adjusted_goal_start = calendar.get_datetime_of(time_budget.calendar_start_index);
        let adjusted_goal_deadline = calendar.get_datetime_of(time_budget.calendar_end_index);

        let hours_to_schedule = time_budget.min_scheduled - time_budget.scheduled;

        let compatible_intervals: Vec<Interval> = interval_helper::get_compatible_intervals(
            calendar,
            Some(&budget.periods),
            adjusted_goal_start,
            adjusted_goal_deadline,
            &None,
        );

        activities.push(Activity {
            goal_id: budget.budget_id.clone(),
            activity_type: ActivityType::GetToMinDayBudget,
            title: budget.title.clone(),
            min_block_size: 1,
            max_block_size: hours_to_schedule,
            total_duration: hours_to_schedule,
            duration_left: hours_to_schedule,
            status: ActivityStatus::Unprocessed,
            start: adjusted_goal_start,
            deadline: Some(adjusted_goal_deadline),
            compatible_intervals,
            incompatible_intervals: vec![],
            flex: None,
        });

        activities
    }

    pub fn get_activities_to_get_min_week_budget(
        budget: &CalendarBudget,
        calendar: &Calendar,
        time_budget: &TimeBudget,
    ) -> Vec<Activity> {
        let mut activities: Vec<Activity> = vec![];

        let adjusted_goal_start = calendar.get_datetime_of(time_budget.calendar_start_index);
        let adjusted_goal_deadline = calendar.get_datetime_of(time_budget.calendar_end_index);
        let max_hours = time_budget.max_scheduled - time_budget.scheduled;

        let compatible_intervals: Vec<Interval> = interval_helper::get_compatible_intervals(
            calendar,
            Some(&budget.periods),
            adjusted_goal_start,
            adjusted_goal_deadline,
            &None,
        );

        activities.push(Activity {
            goal_id: budget.budget_id.clone(),
            activity_type: ActivityType::GetToMinWeekBudget,
            title: budget.title.clone(),
            min_block_size: 1,
            max_block_size: max_hours,
            total_duration: max_hours,
            duration_left: max_hours,
            status: ActivityStatus::Unprocessed,
            start: adjusted_goal_start,
            deadline: Some(adjusted_goal_deadline),
            compatible_intervals,
            incompatible_intervals: vec![],
            flex: None,
        });

        activities
    }

    pub fn get_activities_to_top_up_week_budget(
        budget: &CalendarBudget,
        calendar: &Calendar,
        time_budget: &TimeBudget,
        max_per_week: usize,
    ) -> Vec<Activity> {
        let mut activities: Vec<Activity> = vec![];

        let max_hours = min(
            time_budget.max_scheduled - time_budget.scheduled,
            max_per_week,
        );

        if max_hours == 0 {
            return activities;
        }

        let adjusted_start =
            time_grid::datetime_at(calendar.start_date_time, time_budget.calendar_start_index);
        let adjusted_end = calendar.get_datetime_of(time_budget.calendar_end_index);

        let compatible_intervals: Vec<Interval> = interval_helper::get_compatible_intervals(
            calendar,
            Some(&budget.periods),
            adjusted_start,
            adjusted_end,
            &None,
        );

        activities.push(Activity {
            goal_id: budget.budget_id.clone(),
            activity_type: ActivityType::TopUpWeekBudget,
            title: budget.title.clone(),
            min_block_size: 1,
            max_block_size: max_hours,
            total_duration: max_hours,
            duration_left: max_hours,
            status: ActivityStatus::Unprocessed,
            start: adjusted_start,
            deadline: Some(adjusted_end),
            compatible_intervals,
            incompatible_intervals: vec![],
            flex: None,
        });

        activities
    }
}

#[derive(Debug, PartialEq, Clone, Deserialize, Hash)]
pub enum ActivityStatus {
    Unprocessed,
    Processed,
    Scheduled,
    Impossible,
    Postponed,
    BestEffort,
}

#[derive(Clone, Debug, PartialEq, Hash)]
pub enum ActivityType {
    SimpleGoal,
    GetToMinDayBudget,
    GetToMinWeekBudget,
    TopUpWeekBudget,
}

impl fmt::Debug for Activity {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f)?;
        writeln!(f, "title: {:?}", self.title)?;
        writeln!(f, "status:{:?}", self.status)?;
        writeln!(f, "total duration: {:?}", self.total_duration)?;
        writeln!(f, "duration left: {:?}", self.duration_left)?;
        write!(f, "flex:{:?}", self.flex_read_only())?;
        for interval in &self.compatible_intervals {
            write!(f, "\nInterval :{:?}", interval)?;
        }
        Ok(())
    }
}