border_tch_agent/sac/actor/
config.rs

1use crate::{opt::OptimizerConfig, util::OutDim};
2use anyhow::Result;
3use serde::{de::DeserializeOwned, Deserialize, Serialize};
4use std::{
5    fs::File,
6    io::{BufReader, Write},
7    path::Path,
8};
9
10#[allow(clippy::upper_case_acronyms)]
11#[derive(Debug, Deserialize, Serialize, PartialEq, Clone)]
12/// Configuration of [`Actor`](super::Actor).
13pub struct ActorConfig<P: OutDim> {
14    pub pi_config: Option<P>,
15    pub opt_config: OptimizerConfig,
16}
17
18impl<P: OutDim> Default for ActorConfig<P> {
19    fn default() -> Self {
20        Self {
21            pi_config: None,
22            opt_config: OptimizerConfig::Adam { lr: 0.0 },
23        }
24    }
25}
26
27impl<P> ActorConfig<P>
28where
29    P: DeserializeOwned + Serialize + OutDim,
30{
31    /// Sets configurations for action-value function.
32    pub fn pi_config(mut self, v: P) -> Self {
33        self.pi_config = Some(v);
34        self
35    }
36
37    /// Sets output dimension of the model.
38    pub fn out_dim(mut self, v: i64) -> Self {
39        match &mut self.pi_config {
40            None => {}
41            Some(pi_config) => pi_config.set_out_dim(v),
42        };
43        self
44    }
45
46    /// Sets optimizer configuration.
47    pub fn opt_config(mut self, v: OptimizerConfig) -> Self {
48        self.opt_config = v;
49        self
50    }
51
52    /// Constructs [ActorConfig] from YAML file.
53    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
54        let file = File::open(path)?;
55        let rdr = BufReader::new(file);
56        let b = serde_yaml::from_reader(rdr)?;
57        Ok(b)
58    }
59
60    /// Saves [ActorConfig].
61    pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
62        let mut file = File::create(path)?;
63        file.write_all(serde_yaml::to_string(&self)?.as_bytes())?;
64        Ok(())
65    }
66}