Skip to content
Snippets Groups Projects
Commit a1951479 authored by Udo Eisenbarth's avatar Udo Eisenbarth :speech_balloon:
Browse files

Implement first deserialization code for OpticRef

Added corresponding example....not working yet.
parent 8305aec4
No related branches found
No related tags found
1 merge request!16Implement basic serialization / deserialization of OPOSSUM models
Pipeline #7534 passed
......@@ -23,7 +23,7 @@ fn main() -> Result<(), OpossumError> {
nested_group.map_input_port(nested_g_n1, "front", "in1")?;
nested_group.map_output_port(nested_g_n2, "rear", "out1")?;
println!("{}", serde_yaml::to_string(&group1).unwrap());
let nested_group_index = group1.add_node(nested_group);
group1.connect_nodes(nested_group_index, "out1", g1_n1, "front")?;
......@@ -38,8 +38,10 @@ fn main() -> Result<(), OpossumError> {
let scene_g1 = scenery.add_node(group1);
let scene_g2 = scenery.add_node(group2);
// set_output_port
scenery.connect_nodes(scene_g1, "out1", scene_g2, "in1")?;
println!("{}", serde_yaml::to_string(&scenery).unwrap());
let path = "graph_group.dot";
let mut output = File::create(path).unwrap();
write!(output, "{}", scenery.to_dot("LR")?).unwrap();
......
use std::{cell::RefCell, rc::Rc};
use opossum::{optical::OpticRef, nodes::Dummy, error::OpossumError};
fn main() -> Result<(), OpossumError>{
let optic_ref=OpticRef(Rc::new(RefCell::new(Dummy::default())));
let serialized= serde_yaml::to_string(&optic_ref).unwrap();
println!("serialized:\n{}", serialized);
let restored_ref = serde_yaml::from_str::<OpticRef>(&serialized).unwrap();
println!("restored:\n{:?}", restored_ref);
Ok(())
}
\ No newline at end of file
//! Data structures containing the light information flowing between [`Opticals`](crate::optical::Optical).
use serde_derive::Serialize;
use serde_derive::{Serialize, Deserialize};
use std::fmt::Display;
use uom::fmt::DisplayStyle::Abbreviation;
use uom::si::{energy::joule, f64::Energy};
......@@ -10,7 +10,7 @@ use crate::spectrum::Spectrum;
/// [`AnalyzerType`](crate::analyzer::AnalyzerType). For example, an energy analysis ([`LightData::Energy`]) only
/// contains a [`Spectrum`] information, while a geometric analysis ([`LightData::Geometric]) constains a set of optical
/// ray data.
#[derive(Debug, Clone, Serialize)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LightData {
/// data type used for energy analysis.
Energy(DataEnergy),
......@@ -44,12 +44,12 @@ impl Display for LightData {
}
}
}
#[derive(Debug, Clone, Serialize)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataEnergy {
pub spectrum: Spectrum,
}
#[derive(Debug, Clone, Serialize)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataGeometric {
_ray: i32,
}
use petgraph::prelude::DiGraph;
use petgraph::stable_graph::NodeIndex;
use serde::ser::SerializeStruct;
use serde::Serialize;
use crate::analyzer::AnalyzerType;
use crate::dottable::Dottable;
use crate::error::OpossumError;
use crate::light::Light;
use crate::lightdata::LightData;
use crate::nodes::NodeGroup;
use crate::nodes::{Dummy, NodeGroup};
use crate::optic_ports::OpticPorts;
use crate::properties::{Properties, Property};
use core::fmt::Debug;
use petgraph::prelude::DiGraph;
use petgraph::stable_graph::NodeIndex;
use serde::de::{self, Deserialize, MapAccess, SeqAccess, Visitor};
use serde::ser::SerializeStruct;
use serde::Serialize;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
......@@ -132,25 +132,95 @@ impl Serialize for OpticRef {
}
}
#[cfg(test)]
mod test {
// #[test]
// #[ignore]
// fn to_dot() {
// let node = OpticNode::new("Test", Dummy::default());
// assert_eq!(
// node.to_dot("i0", "".to_owned()).unwrap(),
// " i0 [label=\"Test\"]\n".to_owned()
// )
// }
// #[test]
// #[ignore]
// fn to_dot_inverted() {
// let mut node = OpticNode::new("Test", Dummy::default());
// node.set_inverted(true);
// assert_eq!(
// node.to_dot("i0", "".to_owned()).unwrap(),
// " i0 [label=\"Test(inv)\"]\n".to_owned()
// )
// }
impl<'de> Deserialize<'de> for OpticRef {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
enum Field {
NodeType,
Properties,
}
const FIELDS: &'static [&'static str] = &["type", "properties"];
impl<'de> Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct FieldVisitor;
impl<'de> Visitor<'de> for FieldVisitor {
type Value = Field;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("`type` or `properties`")
}
fn visit_str<E>(self, value: &str) -> std::result::Result<Field, E>
where
E: de::Error,
{
match value {
"type" => Ok(Field::NodeType),
"properties" => Ok(Field::Properties),
_ => Err(de::Error::unknown_field(value, FIELDS)),
}
}
}
deserializer.deserialize_identifier(FieldVisitor)
}
}
struct OpticRefVisitor;
impl<'de> Visitor<'de> for OpticRefVisitor {
type Value = OpticRef;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a struct OpticRef")
}
fn visit_seq<A>(self, mut seq: A) -> std::result::Result<OpticRef, A::Error>
where
A: SeqAccess<'de>,
{
let _node_type = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(0, &self))?;
let _properties = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(1, &self))?;
Ok(OpticRef(Rc::new(RefCell::new(Dummy::default()))))
}
fn visit_map<A>(self, mut map: A) -> std::result::Result<OpticRef, A::Error>
where
A: MapAccess<'de>,
{
let mut node_type = None;
let mut properties = None;
while let Some(key) = map.next_key()? {
match key {
Field::NodeType => {
if node_type.is_some() {
return Err(de::Error::duplicate_field("type"));
}
node_type = Some(map.next_value()?);
}
Field::Properties => {
if properties.is_some() {
return Err(de::Error::duplicate_field("properties"));
}
properties = Some(map.next_value()?);
}
}
}
let _node_type = node_type.ok_or_else(|| de::Error::missing_field("type"))?;
let _nanos = properties.ok_or_else(|| de::Error::missing_field("properties"))?;
Ok(OpticRef(Rc::new(RefCell::new(Dummy::default()))))
}
}
deserializer.deserialize_struct("OpticRef", FIELDS, OpticRefVisitor)
}
}
......@@ -37,7 +37,7 @@ impl Serialize for Properties {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer {
serializer.serialize_newtype_struct("hallo", &self.props)
serializer.serialize_newtype_struct("properties", &self.props)
}
}
#[derive(Debug, Clone)]
......@@ -49,7 +49,7 @@ impl Serialize for Property {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer {
serializer.serialize_newtype_struct("hallo", &self.prop)
serializer.serialize_newtype_struct("property", &self.prop)
}
}
#[non_exhaustive]
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment