muse2/input/
agent.rs

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
//! Code for reading in agent-related data from CSV files.
use super::*;
use crate::agent::{Agent, DecisionRule, SearchSpace};
use crate::commodity::Commodity;
use crate::process::Process;
use crate::region::RegionSelection;
use anyhow::{ensure, Context, Result};
use serde::Deserialize;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::rc::Rc;

pub mod objective;
use objective::read_agent_objectives;
pub mod region;
use region::read_agent_regions;

const AGENT_FILE_NAME: &str = "agents.csv";

/// An agent in the simulation
#[derive(Debug, Deserialize, PartialEq, Clone)]
struct AgentRaw {
    /// A unique identifier for the agent.
    id: Rc<str>,
    /// A text description of the agent.
    description: String,
    /// The commodity that the agent produces (could be a service demand too).
    commodity_id: String,
    /// The proportion of the commodity production that the agent is responsible for.
    #[serde(deserialize_with = "deserialise_proportion_nonzero")]
    commodity_portion: f64,
    /// The processes that the agent will consider investing in. Expressed as process IDs separated
    /// by semicolons or `None`, meaning all processes.
    search_space: Option<String>,
    /// The decision rule that the agent uses to decide investment.
    decision_rule: DecisionRule,
    /// The maximum capital cost the agent will pay.
    capex_limit: Option<f64>,
    /// The maximum annual operating cost (fuel plus var_opex etc) that the agent will pay.
    annual_cost_limit: Option<f64>,
}

/// Read agents info from various CSV files.
///
/// # Arguments
///
/// * `model_dir` - Folder containing model configuration files
/// * `commodities` - Commodities for the model
/// * `process_ids` - The possible valid process IDs
/// * `region_ids` - The possible valid region IDs
///
/// # Returns
///
/// A map of Agents, with the agent ID as the key
pub fn read_agents(
    model_dir: &Path,
    commodities: &HashMap<Rc<str>, Rc<Commodity>>,
    processes: &HashMap<Rc<str>, Rc<Process>>,
    region_ids: &HashSet<Rc<str>>,
) -> Result<HashMap<Rc<str>, Agent>> {
    let process_ids = processes.keys().cloned().collect();
    let mut agents = read_agents_file(model_dir, commodities, &process_ids)?;
    let agent_ids = agents.keys().cloned().collect();

    let mut agent_regions = read_agent_regions(model_dir, &agent_ids, region_ids)?;
    let mut objectives = read_agent_objectives(model_dir, &agents)?;

    for (id, agent) in agents.iter_mut() {
        agent.regions = agent_regions.remove(id).unwrap();
        agent.objectives = objectives.remove(id).unwrap();
    }

    Ok(agents)
}

/// Read agents info from the agents.csv file.
///
/// # Arguments
///
/// * `model_dir` - Folder containing model configuration files
/// * `commodities` - Commodities for the model
/// * `process_ids` - The possible valid process IDs
///
/// # Returns
///
/// A map of Agents, with the agent ID as the key
pub fn read_agents_file(
    model_dir: &Path,
    commodities: &HashMap<Rc<str>, Rc<Commodity>>,
    process_ids: &HashSet<Rc<str>>,
) -> Result<HashMap<Rc<str>, Agent>> {
    let file_path = model_dir.join(AGENT_FILE_NAME);
    let agents_csv = read_csv(&file_path)?;
    read_agents_file_from_iter(agents_csv, commodities, process_ids)
        .with_context(|| input_err_msg(&file_path))
}

/// Read agents info from an iterator.
fn read_agents_file_from_iter<I>(
    iter: I,
    commodities: &HashMap<Rc<str>, Rc<Commodity>>,
    process_ids: &HashSet<Rc<str>>,
) -> Result<HashMap<Rc<str>, Agent>>
where
    I: Iterator<Item = AgentRaw>,
{
    let mut agents = HashMap::new();
    for agent_raw in iter {
        let commodity = commodities
            .get(agent_raw.commodity_id.as_str())
            .context("Invalid commodity ID")?;

        // Parse search space string
        let search_space = match agent_raw.search_space {
            None => SearchSpace::AllProcesses,
            Some(processes) => {
                let mut set = HashSet::new();
                for id in processes.split(';') {
                    set.insert(process_ids.get_id(id)?);
                }

                SearchSpace::Some(set)
            }
        };

        let agent = Agent {
            id: Rc::clone(&agent_raw.id),
            description: agent_raw.description,
            commodity: Rc::clone(commodity),
            commodity_portion: agent_raw.commodity_portion,
            search_space,
            decision_rule: agent_raw.decision_rule,
            capex_limit: agent_raw.capex_limit,
            annual_cost_limit: agent_raw.annual_cost_limit,
            regions: RegionSelection::default(),
            objectives: Vec::new(),
        };

        ensure!(
            agents.insert(agent_raw.id, agent).is_none(),
            "Duplicate agent ID"
        );
    }

    Ok(agents)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::DecisionRule;
    use crate::commodity::{CommodityCostMap, CommodityType, DemandMap};
    use crate::region::RegionSelection;
    use crate::time_slice::TimeSliceLevel;
    use std::iter;

    #[test]
    fn test_read_agents_file_from_iter() {
        let process_ids = ["A".into(), "B".into(), "C".into()].into_iter().collect();
        let commodity = Rc::new(Commodity {
            id: "commodity1".into(),
            description: "A commodity".into(),
            kind: CommodityType::SupplyEqualsDemand,
            time_slice_level: TimeSliceLevel::Annual,
            costs: CommodityCostMap::new(),
            demand: DemandMap::new(),
        });
        let commodities = iter::once(("commodity1".into(), Rc::clone(&commodity))).collect();

        // Valid case
        let search_space = HashSet::from_iter(["A".into(), "B".into()]);
        let agent = AgentRaw {
            id: "agent".into(),
            description: "".into(),
            commodity_id: "commodity1".into(),
            commodity_portion: 1.0,
            search_space: Some("A;B".into()),
            decision_rule: DecisionRule::Single,
            capex_limit: None,
            annual_cost_limit: None,
        };
        let agent_out = Agent {
            id: "agent".into(),
            description: "".into(),
            commodity,
            commodity_portion: 1.0,
            search_space: SearchSpace::Some(search_space),
            decision_rule: DecisionRule::Single,
            capex_limit: None,
            annual_cost_limit: None,
            regions: RegionSelection::default(),
            objectives: Vec::new(),
        };
        let expected = HashMap::from_iter([("agent".into(), agent_out)]);
        let actual =
            read_agents_file_from_iter(iter::once(agent), &commodities, &process_ids).unwrap();
        assert_eq!(actual, expected);

        // Invalid commodity ID
        let agent = AgentRaw {
            id: "agent".into(),
            description: "".into(),
            commodity_id: "made_up_commodity".into(),
            commodity_portion: 1.0,
            search_space: None,
            decision_rule: DecisionRule::Single,
            capex_limit: None,
            annual_cost_limit: None,
        };
        assert!(read_agents_file_from_iter(iter::once(agent), &commodities, &process_ids).is_err());

        // Invalid process ID
        let agent = AgentRaw {
            id: "agent".into(),
            description: "".into(),
            commodity_id: "commodity1".into(),
            commodity_portion: 1.0,
            search_space: Some("A;D".into()),
            decision_rule: DecisionRule::Single,
            capex_limit: None,
            annual_cost_limit: None,
        };
        assert!(read_agents_file_from_iter(iter::once(agent), &commodities, &process_ids).is_err());

        // Duplicate agent ID
        let agents = [
            AgentRaw {
                id: "agent".into(),
                description: "".into(),
                commodity_id: "commodity1".into(),
                commodity_portion: 1.0,
                search_space: None,
                decision_rule: DecisionRule::Single,
                capex_limit: None,
                annual_cost_limit: None,
            },
            AgentRaw {
                id: "agent".into(),
                description: "".into(),
                commodity_id: "commodity1".into(),
                commodity_portion: 1.0,
                search_space: None,
                decision_rule: DecisionRule::Single,
                capex_limit: None,
                annual_cost_limit: None,
            },
        ];
        assert!(
            read_agents_file_from_iter(agents.into_iter(), &commodities, &process_ids).is_err()
        );
    }
}