ravenous-tools/crates/graphs/src/graphs.rs

389 lines
12 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! The module `graphs` is responsible for exporting graphs based on CSV data
//!
//! # Usage
//!
//! - [`make_graphs`]: The main action dispatcher for graph generation and removal.
use charts_rs::{
Box, Color, RadarChart, RadarIndicator, Series, get_or_try_init_fonts, svg_to_png_with_size,
};
use cli_parser::Config;
use config::graph::{FinalClassRadar, GraphConfig, GraphTargetType, LoadedClassRadar, RawRow};
use glob::glob;
use serde::{Deserialize, Serialize};
use std::{
fs::File,
io::{Read, Write},
iter,
path::{Path, PathBuf},
process::Command,
};
use anyhow::{Context, Result};
/// Main action dispatch for the graph make
pub fn make_graphs(args: &GraphConfig, _config: &Config) -> Result<()> {
// Choose action to do
match args.target {
GraphTargetType::Load => load_graph(args),
GraphTargetType::Generate => gen_graph(args),
GraphTargetType::Remove => del_graphs(args),
GraphTargetType::Init => init_graph_config(args),
}
}
/// Initialize the config on the main directory
fn init_graph_config(_args: &GraphConfig) -> Result<()> {
let mut f = File::create("graph_config.ron")?;
let theme = MiniTheme::new();
f.write_all(
ron::ser::to_string_pretty(&theme, ron::ser::PrettyConfig::default())
.context("Converting to toml")?
.as_bytes(),
)
.context("Writing to file")?;
Ok(())
}
/// Load the config if given of the default config if none
fn load_graph_config(args: &GraphConfig) -> Result<MiniTheme> {
if let Some(c) = &args.config {
println!("[INFO] Reading config {}", c);
let mut f = File::open(c).context("Opening config")?;
let mut buf = String::new();
f.read_to_string(&mut buf).context("Reading the config")?;
Ok(ron::from_str(buf.as_str()).context("Deserializing config")?)
} else {
println!("[INFO] Loading default config");
Ok(MiniTheme::new())
}
}
/// Delete the existing graphs
fn del_graphs(args: &GraphConfig) -> Result<()> {
let mut cmd = Command::new("rm");
cmd.args(
glob("Images/Radar/*.svg")?
.map(|v| v.unwrap().to_str().unwrap().to_string())
.collect::<Vec<String>>(),
);
if args.all {
cmd.args(
glob("Images/Radar/*.png")?
.map(|v| v.unwrap().to_str().unwrap().to_string())
.collect::<Vec<String>>(),
);
}
if let Err(e) = cmd.output() {
println!(
"[ERRR] An error has occured when executing the remove target \n {:#?}",
e
)
}
Ok(())
}
/// Load graph data from classes
fn load_graph(args: &GraphConfig) -> Result<()> {
let _ = args;
// load_categories_from_tsv("./test.csv")?;
generate_csv()?;
Ok(())
}
///Generate the graph and save it
fn gen_graph(args: &GraphConfig) -> Result<()> {
// Import CSV
let data = include_bytes!("../../../data/lmroman8-regular.ttf") as &[u8];
get_or_try_init_fonts(Some(vec![data])).unwrap();
let csv = import_csv(args)?;
let maxv = &csv.max;
let cfg = load_graph_config(args)?;
for graph in csv.values {
let path_svg = format!("{}/{}.svg", args.destination, graph.name);
let path_png = format!("{}/{}.png", args.destination, graph.name);
println!("[INFO] Processing {}", path_svg);
let mut f = File::create(&path_svg)?;
let mut r = RadarChart::new([graph].to_vec(), maxv.to_vec());
cfg.apply_to(&mut r);
println!("Writing to {}", path_svg);
let context = r.svg().context("Converting to SVG")?;
f.write_all(context.as_bytes())?;
let png = svg_to_png_with_size(&context, Some(860), Some(560)).context("Writing png")?;
let mut f = File::create(path_png)?;
f.write_all(&png).context("Writing png")?;
}
Ok(())
}
/// Import the default csv
fn import_csv(args: &GraphConfig) -> Result<GraphValues> {
let file = File::open(&args.origin)
.context("Opening the radar file")
.unwrap();
let rdr = csv::ReaderBuilder::new().from_reader(file);
cleanup_csv(rdr)
}
/// Generate the csv from all the classes
fn generate_csv() -> Result<()> {
// Acquire the data from all classes
let list_class = list_dir("Tables/??? - *.tsv");
let mut final_class_list = Vec::with_capacity(list_class.len() + 1);
// Very ugly space reservation for the last operation, need to check if no way of skipping an element is possible
final_class_list.push(FinalClassRadar::default());
for single_class in list_class {
let class_name = &single_class
.file_name()
.context("Extracting old name")?
.to_str()
.context("Generating new name")?[12..]
.strip_suffix(".tsv")
.context("Stripping extention")?;
let categories =
load_categories_from_tsv(single_class.clone()).context("Loading from csv")?;
final_class_list.push(FinalClassRadar::from_radar_with_name(
class_name.to_string(),
categories,
))
}
// Calculate all the max values
final_class_list[0] = final_class_list
.iter()
.fold(FinalClassRadar::default_for_acc(), |a, b| a.find_max(b));
let mut wtr = csv::WriterBuilder::new()
.has_headers(true)
.from_path("Images/Radar/radar.csv")
.context("Creating CSV output file")?;
// println!("{:?}", final_class_list);
for cv in &final_class_list {
wtr.serialize(cv).context("Writing CSV record")?;
}
wtr.flush().context("Flushing CSV writer")?;
Ok(())
}
/// Reads a TSV file that either has the header line shown above or
/// just raw data rows, and returns a `Vec<Categories>`.
pub fn load_categories_from_tsv<P: AsRef<Path>>(path: P) -> Result<LoadedClassRadar> {
// `has_headers(false)` tells the csv crate to *not* treat the first row as a header.
// We’ll do the header check ourselves.
let file = File::open(path)?;
let mut rdr = csv::ReaderBuilder::new()
.has_headers(false)
.delimiter(b'\t')
.double_quote(false)
.escape(Some(b'\\'))
.flexible(true)
.comment(Some(b'#'))
.from_reader(file);
let mut sum = LoadedClassRadar::default();
for result in rdr.deserialize() {
let result: RawRow = result?;
if result.technique.starts_with("Tier ") {
// Getto way of knowing we have a new tier, that we ignore
} else if (result.technique == "Technique") | result.technique.is_empty() {
// Skip this entry
} else {
sum = sum + result.into();
}
}
Ok(sum)
}
/// The data for all graphs
struct GraphValues {
/// The max values of a graph
// max: Vec<(String, f32)>,
max: Vec<RadarIndicator>,
/// The list of all character and associated values
// values: Vec<(String, Vec<f32>)>,
values: Vec<Series>,
}
/// Cleanup the given csv to output usable data
fn cleanup_csv(mut rdr: csv::Reader<File>) -> Result<GraphValues> {
let headers = rdr.headers().context("Opening headers")?;
// Making the max/base vec
// Gathering all the different category names
let headers = headers
.iter()
.filter(|v| !v.is_empty())
.skip(1)
.map(|v| v.to_string())
.collect::<Vec<String>>();
// Gather all the different categories
let mut rdr = rdr.records();
// Calculate the max values
let maxvals: Vec<f32> = rdr
.next()
.context("Gathering max values")??
.iter()
.map(|v| v.parse::<f32>().unwrap_or(0.0))
.skip(1)
.collect();
// Calculate all the values of all graphs
let mut res = Vec::new();
for line in rdr {
let line = line.context("Parsing table lines")?;
let name = line
.get(0)
.context("Fetching name for character")?
.to_string()
.replace(" ", "_")
.replace("î", "i")
.to_lowercase()
.replace("é", "e");
let vals: Vec<f32> = line
.iter()
.skip(1)
.enumerate()
.map(|(i, v)| {
v.parse::<f32>().unwrap_or(0.0) * 5.0
/ maxvals.get(i).context("Fetching max value").unwrap()
})
.collect();
res.push(Series::new(name, vals));
}
Ok(GraphValues {
max: headers
.iter()
.map(|v| v.to_owned())
.zip(iter::repeat(5.0f32))
.map(|(name, max)| RadarIndicator { name, max })
.collect::<Vec<RadarIndicator>>(),
values: res,
})
}
impl MiniTheme {
/// The default theme for out tool
pub fn new() -> Self {
Self {
font_family: "Latin Modern Roman".to_string(),
margin: Box {
left: 10.0,
top: 20.0,
right: 90.0,
bottom: 60.0,
},
width: 860.0,
height: 560.0,
grid_stroke_color: Color {
r: 77,
g: 69,
b: 57,
a: 255,
},
grid_stroke_width: 2.5,
series_stroke_width: 5.0,
series_label_font_size: 60.0,
series_label_font_color: Color {
r: 75,
g: 61,
b: 68,
a: 255,
},
series_colors: [Color {
r: 179,
g: 165,
b: 85,
a: 255,
}]
.to_vec(),
legend_show: Some(false),
}
}
/// Apply our super custom theme to the graph
pub(super) fn apply_to(&self, r: &mut RadarChart) {
r.font_family = self.font_family.clone();
r.margin = self.margin.clone();
r.width = self.width;
r.height = self.height;
r.grid_stroke_color = self.grid_stroke_color;
r.grid_stroke_width = self.grid_stroke_width;
r.series_stroke_width = self.series_stroke_width;
r.series_label_font_size = self.series_label_font_size;
r.series_label_font_color = self.series_label_font_color;
r.series_colors = self.series_colors.clone();
r.legend_show = self.legend_show;
}
}
#[allow(missing_docs, clippy::missing_docs_in_private_items)]
#[derive(Serialize, Deserialize)]
pub struct MiniTheme {
pub font_family: String,
pub margin: Box,
pub width: f32,
pub height: f32,
pub legend_show: Option<bool>,
// pub background_color: Color,
pub grid_stroke_color: Color,
pub grid_stroke_width: f32,
pub series_stroke_width: f32,
pub series_label_font_size: f32,
pub series_label_font_color: Color,
pub series_colors: Vec<Color>,
// pub title_font_size: f32,
// pub title_font_color: Color,
// pub title_font_weight: Option<String>,
// pub title_margin: Option<Box>,
// pub title_align: Align,
// pub title_height: f32,
// pub sub_title_font_size: f32,
// pub sub_title_font_color: Color,
// pub sub_title_margin: Option<Box>,
// pub sub_title_align: Align,
// pub sub_title_height: f32,
// pub legend_font_size: f32,
// pub legend_font_color: Color,
// pub legend_align: Align,
// pub legend_margin: Option<Box>,
// pub x_axis_font_size: f32,
// pub x_axis_stroke_color: Color,
// pub x_axis_font_color: Color,
// pub x_axis_name_gap: f32,
// pub x_axis_height: f32,
// pub y_axis_font_size: f32,
// pub y_axis_font_color: Color,
// pub y_axis_stroke_color: Color,
// pub y_axis_split_number: usize,
// pub y_axis_name_gap: f32,
// pub table_header_color: Color,
// pub table_body_colors: Vec<Color>,
// pub table_border_color: Color,
}
/// List all files matching a pattern in the given directory
#[inline]
fn list_dir(pattern: &str) -> Vec<PathBuf> {
// println!("{}", pattern);
// println!("{:?}", glob(pattern));
glob(pattern)
.expect("Failed to read glob pattern")
.flatten()
.collect()
}