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
use std::collections::HashMap;
use std::marker::PhantomData;
use std::mem::take;
use std::path::Path;

use anyhow::Result;
use log::*;

use super::{Dedup, Interaction, Key};
use crate::arrow::*;
use crate::io::{file_size, ObjectWriter};
use crate::util::logging::item_progress;
use crate::util::Timer;

/// Record for a single output action.
#[derive(TableRow, Debug)]
pub struct TimestampActionRecord {
    pub user: i32,
    pub item: i32,
    pub first_time: i64,
    pub last_time: i64,
    pub last_rating: Option<f32>,
    pub nactions: i32,
}

/// Record for a single output action without time.
#[derive(TableRow, Debug)]
pub struct TimelessActionRecord {
    pub user: i32,
    pub item: i32,
    pub nactions: i32,
}

#[derive(PartialEq, Clone, Debug)]
pub struct ActionInstance {
    timestamp: i64,
    rating: Option<f32>,
}

/// Collapse a sequence of actions into an action record.
pub trait FromActionSet {
    fn create(user: i32, item: i32, actions: Vec<ActionInstance>) -> Self;
}

impl FromActionSet for TimestampActionRecord {
    fn create(user: i32, item: i32, actions: Vec<ActionInstance>) -> Self {
        let mut vec = actions;
        if vec.len() == 1 {
            // fast path
            let act = &vec[0];
            TimestampActionRecord {
                user,
                item,
                first_time: act.timestamp,
                last_time: act.timestamp,
                last_rating: act.rating,
                nactions: 1,
            }
        } else {
            vec.sort_unstable_by_key(|a| a.timestamp);
            let first = &vec[0];
            let last = &vec[vec.len() - 1];
            let rates = vec.iter().flat_map(|a| a.rating).collect::<Vec<f32>>();
            let last_rating = if rates.len() > 0 {
                Some(rates[rates.len() - 1])
            } else {
                None
            };

            TimestampActionRecord {
                user,
                item,
                first_time: first.timestamp,
                last_time: last.timestamp,
                last_rating,
                nactions: vec.len() as i32,
            }
        }
    }
}

impl FromActionSet for TimelessActionRecord {
    fn create(user: i32, item: i32, actions: Vec<ActionInstance>) -> Self {
        TimelessActionRecord {
            user,
            item,
            nactions: actions.len() as i32,
        }
    }
}

/// Action deduplicator.
pub struct ActionDedup<R>
where
    R: FromActionSet + TableRow,
{
    _phantom: PhantomData<R>,
    table: HashMap<Key, Vec<ActionInstance>>,
}

impl<R> Default for ActionDedup<R>
where
    R: FromActionSet + TableRow + 'static,
{
    fn default() -> ActionDedup<R> {
        ActionDedup {
            _phantom: PhantomData,
            table: HashMap::new(),
        }
    }
}

impl<I: Interaction, R> Dedup<I> for ActionDedup<R>
where
    R: FromActionSet + TableRow + Send + Sync + 'static,
{
    fn add_interaction(&mut self, act: I) -> Result<()> {
        self.record(
            act.get_user(),
            act.get_item(),
            act.get_timestamp(),
            act.get_rating(),
        );
        Ok(())
    }

    fn save(&mut self, path: &Path) -> Result<usize> {
        self.write_actions(path)
    }
}

impl<R> ActionDedup<R>
where
    R: FromActionSet + TableRow + Send + Sync + 'static,
{
    /// Add an action to the deduplicator.
    pub fn record(&mut self, user: i32, item: i32, timestamp: i64, rating: Option<f32>) {
        let k = Key::new(user, item);
        // get the vector for this user/item pair
        let vec = self.table.entry(k).or_insert_with(|| Vec::with_capacity(1));
        // and insert our records!
        vec.push(ActionInstance { timestamp, rating });
    }

    /// Save the rating table disk.
    pub fn write_actions<P: AsRef<Path>>(&mut self, path: P) -> Result<usize> {
        let path = path.as_ref();
        info!(
            "writing {} deduplicated actions to {}",
            friendly::scalar(self.table.len()),
            path.display()
        );
        let mut writer = TableWriter::open(path)?;
        let timer = Timer::new();
        let n = self.table.len() as u64;
        let pb = item_progress(n, "writing actions");

        // we're going to consume the hashtable.
        let table = take(&mut self.table);
        for (k, vec) in pb.wrap_iter(table.into_iter()) {
            let record = R::create(k.user, k.item, vec);
            writer.write_object(record)?;
        }

        let rv = writer.finish()?;

        info!(
            "wrote {} actions in {}, file is {}",
            friendly::scalar(n),
            timer.human_elapsed(),
            friendly::bytes(file_size(path)?)
        );

        Ok(rv)
    }
}