use crate::core::graph_dto::CoreGraphDTO;
use crate::error::{PanGraphXError, PanResult};
use gbz_construct::sequences::Sequences;
use gbz_construct::{FullPathName, GBWT, GBWTBuilder, GBZ, GraphBuilder, Tags, support};
use rayon::prelude::*;
use simple_sds::serialize::SerializeVersion;
use std::collections::HashMap;
use std::io::Write;
pub(super) const GBZ_SERIALIZE_VERSION: usize = 2;
pub(super) const GBWT_BUFFER_SIZE: usize = 1 << 20;
pub(super) fn write(graph: &CoreGraphDTO, mut writer: &mut dyn Write) -> PanResult<()> {
let gbz = build_gbz(graph)?;
gbz.serialize_version(&mut writer, GBZ_SERIALIZE_VERSION)?;
Ok(())
}
pub(super) fn build_gbz(graph: &CoreGraphDTO) -> PanResult<GBZ> {
let first_visited = graph
.paths()
.par_iter()
.filter_map(|path| path.steps.par_iter().map(|step| step.node_id()).min())
.min()
.ok_or_else(|| {
PanGraphXError::Serialize("GBZ cannot store a graph without path steps".to_string())
})?;
let segment_names = graph
.node_name_map()
.filter(|map| !names_are_gbz_ids(map, graph.nodes().len()));
let skipped_nodes = if segment_names.is_some() {
first_visited
} else {
0
};
let gbwt = build_gbwt(graph, skipped_nodes)?;
let mut graph_builder = GraphBuilder::new();
if let Some(name_map) = segment_names {
for (id, node) in graph.nodes().iter().enumerate().skip(skipped_nodes) {
let name = name_map
.get(&id)
.ok_or_else(|| PanGraphXError::Serialize(format!("Missing name for node {id}")))?;
let name = std::str::from_utf8(name).map_err(|e| {
PanGraphXError::Serialize(format!("Invalid UTF-8 segment name: {e}"))
})?;
graph_builder
.translate_segment(name, &node.sequence, 0)
.map_err(PanGraphXError::Serialize)?;
}
} else {
for (id, node) in graph.nodes().iter().enumerate() {
graph_builder
.add_node(id + 1, &node.sequence)
.map_err(PanGraphXError::Serialize)?;
}
}
let sequences =
Sequences::from_graph(&gbwt, &graph_builder).map_err(PanGraphXError::Serialize)?;
drop(graph_builder);
GBZ::from_parts(gbwt, sequences, Tags::new()).map_err(PanGraphXError::Serialize)
}
fn build_gbwt(graph: &CoreGraphDTO, skipped_nodes: usize) -> PanResult<GBWT> {
let mut gbwt_builder = GBWTBuilder::new(true, true, GBWT_BUFFER_SIZE);
let mut encoded_path = Vec::new();
for path in graph.paths() {
let contig_name = std::str::from_utf8(&path.name)
.map_err(|e| PanGraphXError::Serialize(format!("Invalid UTF-8 path name: {e}")))?;
encoded_path.clear();
for step in &path.steps {
encoded_path.push(support::encode_node(
step.node_id() - skipped_nodes + 1,
step.orientation().into(),
));
}
gbwt_builder
.insert(&encoded_path, Some(FullPathName::generic(contig_name)))
.map_err(PanGraphXError::Serialize)?;
}
gbwt_builder.build().map_err(PanGraphXError::Serialize)
}
pub(super) fn names_are_gbz_ids(name_map: &HashMap<usize, Vec<u8>>, node_count: usize) -> bool {
let mut buf = itoa::Buffer::new();
(0..node_count).all(|id| {
name_map
.get(&id)
.is_some_and(|name| name.as_slice() == buf.format(id + 1).as_bytes())
})
}