Skip to content

[BioSerDe-13] - Initial bed serde implementation - #1

Merged
GabrielSimonetto merged 14 commits into
serdefrom
bed_serde
Sep 7, 2022
Merged

GabrielSimonetto merged 14 commits into
serdefrom
bed_serde

Conversation

@GabrielSimonetto

@GabrielSimonetto GabrielSimonetto commented Jul 3, 2022 •

Copy link
Copy Markdown

Twin PR on BioSerDe showcasing usage of this branch: umccr/BioSerDe#14

TODO:

  • - ser: impl Serialize for Record<3>
  • - ser: specialized Serializer (thanks roman!)
  • - ser: pub fn to_string(value: &T) -> Result
  • - de: pub fn from_reader(reader: &mut Reader) -> Vec<Record<3>>
  • - de: pub fn from_string(input: Into<&str>) -> Vec<Record<3>>
    --> solved by: let result: Vec<Record::<3>> = from_str(input).unwrap();
    --> doesn't work if string has whitespaces, as described by:
    --> test de::serde_tests::test_bed_deserialization_with_whitespaces ... ignored
  • - de: specialized Deserializer
  • - introduce Record generalizations
  • - review serialization display (is it ok to display backslashes?: "{\"chrom\":\"chr7\"...")
    --> Display doesn't display backslashes, it's Debug that does
  • - review error handling (TODO's on de.rs)

Comment thread noodles-bed/src/de.rs Resolved
Comment thread noodles-bed/src/ser.rs Resolved
@GabrielSimonetto

GabrielSimonetto commented Jul 13, 2022 •

Copy link
Copy Markdown
Author

Making an update on the current state of this PR, decisions needed, and troubles found.

  1. I am currently working on the task of introduce Record generalizations (Record<4>, Record<5>, Record<N>). But this PR is already big enough and it seems like the kind of stuff that could introduce a big change, should we merge this PR and then make a new PR with this change? Or should I just keep working here?

  2. I went a bit overbound on the tests, if any of them sounds like redundant we can remove them.

running 11 tests
test de::serde_tests::test_bed_deserialization_with_whitespaces ... ignored
test de::serde_tests::test_bed_single_deserialization ... ok
test de::serde_tests::test_bed_vec_deserialization ... ok
test de::serde_tests::test_de_enum ... ok
test de::serde_tests::test_de_struct ... ok
test de::serde_tests::test_from_reader_accept ... ok
test de::serde_tests::test_from_reader_reject ... ok
test ser::serde_tests::test_bed_single_serialization ... ok
test ser::serde_tests::test_bed_vec_serialization ... ok
test ser::serde_tests::test_enum ... ok
test ser::serde_tests::test_struct ... ok
  1. I am trying to understand how the from_reader function fits into our puzzle, it's particularly weird that it uses the "serialization format" defined by noodles, (which will read directly a .bed file, in the style of sequential fields (b"sq0\t7\t13\nsq0\t20\t34\n"), instead of the new keyword like format we are introducing here to allow for compatibility with the next formats, (r#"[{"chrom":"sq0","start":8,"end":13},{"chrom":"sq1","start":14,"end":18}]"#), so... did I make a blunder in using it directly? Should it be updated to read files which contain some insane .bed.bioserde format?)

  2. The deserializer currently has a limitation, which seems like it shouldn't be fixed right now, but will need our attention at some point: it fails to read strings with the presence of whitespaces, as decribed by the ignored test test_bed_deserialization_with_whitespaces

I've checked that json solves this using Read trait function like eat_char() and peek. But that would involve building the current Deserializer input: &'de str,
as some Read object, and I don't know if the complexity is desirable to us right now.

  1. There is a technical problem on the visit_seq function which I don't know how to solve yet, would love to hear some points on how to do it, the problem is that it's signature forces the return of a SeqAccess::Error
fn visit_seq<V>(self, mut seq: V) -> std::result::Result<Record<3>, V::Error>
where
    V: SeqAccess<'de>,
{

But, since we also need to return a Record<3> if successful, we are forced to check for the construction of specific bed types, in this case, Position, this has been solved by using unwrap, which could be present in the POC phase of this code, but not in the final deliverable.

We would love to convert a noodles error into the SeqAccess error, but it seem like there is no way to do it, which points to the fact that we shouldn't be checking for this kind of error in this function, but we also cannot check later, so how to do it?

// The code we would like to use
Ok(Record::<3>::builder()
    .set_reference_sequence_name(chrom)
    .set_start_position(Position::try_from(start).map_err(V::Error)?)
    .set_end_position(Position::try_from(end).map_err(V::Error)?)
    .build().map_err(V::Error)?)

@mmalenic mmalenic left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To answer some of the questions:

  1. Yes, I think a new PR might be good after closing this one.
  2. Tests are good, I think these are okay for now 🙂.
  3. I'm not sure exactly what you mean by this question, i.e. what do you mean by allowing for compatibility with the next formats? I think from_reader is okay as noodles is the library that we are using to parse the input data itself.
  4. It would be good to be able to use noodles as much as possible to do the parsing, rather than doing it manually or implementing it. I'm not sure how easy this is to accomplish though. It seems like noodles has FromStr implemented for struct fields/data types.
  5. See comment below.

Some additional thoughts:

  • Is it necessary to manually implement Deserialize? Shouldn't the derive macro do this for us? I think the main component that needs to be implemented is Deserializer, which maps the input into serde's data model. @multimeric @brainstorm, does that sound right?

Let me know if this helps, or if you have any other questions/concerns.

Comment thread noodles-bed/src/de.rs Resolved
Comment thread noodles-bed/src/de.rs Resolved
Comment thread noodles-bed/src/de.rs Resolved
@GabrielSimonetto

Copy link
Copy Markdown
Author

3. I'm not sure exactly what you mean by this question, i.e. what do you mean by allowing for compatibility with the next formats? I think from_reader is okay as noodles is the library that we are using to parse the input data itself.

What I mean is that it feels like it could be confusing that in the same de.rs we have deserializing functions that expect 2 different ways of representing a bed::Record:

    #[test]
    fn test_from_reader_accept() {
        let data = b"sq0\t7\t13\nsq0\t20\t34\n";
        let mut reader = Reader::new(&data[..]);
        let result = from_reader(&mut reader).unwrap();

    #[test]
    fn test_bed_single_deserialization() {
        let input = r#"{"chrom":"sq0","start":8,"end":13}"#;
        let result: Record::<3> = from_str(input).unwrap();

You can imagine that maybe an unitialized user using this functionality at some point may use to_reader, from_reader, to_str, from_str interchangeably, and it could be very confusing that these functions defined in the same de.rs actually use different definitions of representation.

what do you mean by allowing for compatibility with the next formats?

This is just my very convoluted way of saying that the second "keyword like" format we introduce in from_str is the BioSerDe proposal to hopefully translate information between formats in the future, at least that is my current understanding. In a world where BioSerDe isn't a project, I think the first format would be preferable since it seems more performatic.

I will answer the other comments shortly, just testing some things about them before answering

Comment thread noodles-bed/src/de.rs Resolved
@mmalenic

Copy link
Copy Markdown
Member

I don't think there should be two different ways of representing a bed::Record inde.rs. The first test should target an implementation of Deserializer, which maps the input data into Serde's data model. The second test should be handled by the JSON deserializer, which is already implemented. It should be possible to just automatically derive Deserialize and Serialize for bed::Record.

For example, considering second test, to convert #"{"chrom":"sq0","start":8,"end":13}"# to bed::Record, the process could approximately be:

  • The Deserialize implementation of bed::Record (which could be generated using a derive macro) is responsible for mapping the bed::Record into the Serde data model by passing a Visitor implementation to the JSON Deserializer. The Deserializer implementation for JSON is responsible for mapping the input data into the Serde data model by invoking exactly one of these Visitor methods (as described here).
  • To convert this to b"sq0\t7\t13\nsq0\t20\t34\n", the process might follow similar logic described here, using bed::Record's Serialize and Serializer:

    When serializing a data structure to some format, the Serialize implementation for the data structure is responsible for mapping the data structure into the Serde data model by invoking exactly one of the Serializer methods, while the Serializer implementation for the data format is responsible for mapping the Serde data model into the intended output representation.

  • There is a convenience crate that already does this conversion, called serde-transcode, as long as the relevant Serializer and Deserializer traits are present.

It might be a little bit confusing to think about this for bed::Record. JSON, and a lot of the supported Serde data formats are very general formats that can represent a lot of arbitrary data. However, some of the formats we are targeting are quite restricted, such as BED, which only takes a certain number of columns of a certain data type. I don't think this is too much of an issue though, because Serde can map formats arbitrarily, and any attempt to Deserialize/Serialize something unsupported can just return an Error (pretty much everything in Serde will return a Result). For example, Serde supports URL query strings, which are also somewhat restricted in what they can represent.

Let me know if this makes sense, or if I can elaborate on anything.

@GabrielSimonetto

Copy link
Copy Markdown
Author

4. It would be good to be able to use noodles as much as possible to do the parsing, rather than doing it manually or implementing it. I'm not sure how easy this is to accomplish though. It seems like noodles has FromStr implemented for struct fields/data types.

Wow, I hadn't noticed that. However, they are using the bed format definition.

However, I think you are onto something, in the spirit of your last comment, maybe we can just use the serde-json parser to solve this for us.

One thing that makes me apprehensive is that maybe we can get too tangled in external implementations. Maybe we will need to have our custom implementations in order to make optimizations in the future. But I am speaking out of ignorance, working on your suggestion will probably clarify some things out for me.

@mmalenic

mmalenic commented Jul 18, 2022 •

Copy link
Copy Markdown
Member

I think using serde-json will be a good idea for now. I believe one of the goals of Serde is to be as efficient and performant as possible, and I'm sure serde-json follows that reasoning (see here). Also, by using existing implementations, we can focus on just the unimplemented formats, utilizing work done by other authors.

@GabrielSimonetto

GabrielSimonetto commented Jul 19, 2022 •

Copy link
Copy Markdown
Author
  • Is it necessary to manually implement Deserialize? Shouldn't the derive macro do this for us? I think the main component that needs to be implemented is Deserializer, which maps the input into serde's data model. @multimeric @brainstorm, does that sound right?

I think I stumbled at some problems with that, at least for the bed format:

  • bed::record::Record uses 2 auxiliar structures which we would be forced to represent in the serialization, if derived directly.
pub struct Record<const N: u8> {
    standard_fields: StandardFields,
    optional_fields: OptionalFields,
}

// this would by default produce something like {standard_fields: {"chrom": ..., "start": ..., "end": ...}, "optional_fields": {...}}
  • deriving enum Field { Chrom, Start, End } works, but we are forced to use their string representation capitalized:
    fn test_bed_single_deserialization() {
        // let input = r#"{"chrom":"sq0","start":8,"end":13}"#; // this doesn't work anymore
        let input = r#"{"Chrom":"sq0","Start":8,"End":13}"#; // this does
        let result: Record::<3> = from_str(input).unwrap();

I stored this experiment on the extravagantly named ERASEME: showcasing derive for Deserialize, I will leave it there if it is useful to someone reviewing, and remove it before merging.

@GabrielSimonetto

GabrielSimonetto commented Jul 19, 2022 •

Copy link
Copy Markdown
Author
  • The Deserialize implementation of bed::Record (which could be generated using a derive macro) is responsible for mapping the bed::Record into the Serde data model by passing a Visitor implementation to the JSON Deserializer. The Deserializer implementation for JSON is responsible for mapping the input data into the Serde data model by invoking exactly one of these Visitor methods (as described here).

Actually I am a bit lost, could you give me an idea of how such a test would be made? To me it seems like we can test the high abstraction function (such as from_str), and the deserializer and visitor objects would be tested indirectly, since they are called inside of from_str, your idea is to test it on the low level?

To convert this to b"sq0\t7\t13\nsq0\t20\t34\n", the process might follow similar logic described here, using bed::Record's Serialize and Serializer:

I think I am understanding that we are thinking about a way to deal with both formats in relatively the same way. What I don't understand is how this would seem to the final user. Would there be functions to deal with the regular bed format and others to our convention? I understood that the serde-transcode suggestion is to link both serializers to be able to convert from one into the other, but I don't understand the final pipeline, do we aim to always read and write into files as the bed format, but print and represent internally as the bioserde keyword like manner?

If you could give me some examples of how these changes would show up to the user, that would be great (:

@mmalenic mmalenic left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check out the Serde derive attributes. This allows for a lot of added flexibility when using the derive macro, without implementing Deserialize or Serialize manually.

Comment thread noodles-bed/src/de.rs
use crate::{Record, reader::Reader, error::{Error, Result}};

const FIELDS: &'static [&'static str] = &["chrom", "start", "end"];
enum Field { Chrom, Start, End }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One approach to allow lowercase deserialisation is to use the rename_all container attribute. This works for serialisation too.

#[derive(Deserialize, Debug)]
#[serde(rename_all = "lowercase")]
enum Field { Chrom, Start, End }

Note, fields can be renamed arbitrarily using the rename field attribute, or multiple valid names can be assigned using alias.

Comment thread noodles-bed/src/de.rs
VariantAccess, Visitor,
};

use crate::{Record, reader::Reader, error::{Error, Result}};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bed::Record can be changed in record.rs.

/// A BED record.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Record<const N: u8> {
standard_fields: StandardFields,
optional_fields: OptionalFields,
}

For example, to ignore the two extra structs, use the flatten field attribute. This means that during serialisation/deserialisation, standard_fields and optional_fields won't be present. See the example here.

/// A BED record.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Record<const N: u8> {
    #[serde(flatten)]
    standard_fields: StandardFields,
    #[serde(flatten)]
    optional_fields: OptionalFields,
}

@mmalenic mmalenic left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To me it seems like we can test the high abstraction function (such as from_str)

Yep, that's what I meant. Testing public, or user-facing functions (such as from_str) is okay for now. A test could test the visitor functions if we wanted to be sure of some behaviour, but I don't think that's necessary for now.

What I don't understand is how this would seem to the final user. Would there be functions to deal with the regular bed format and others to our convention? I understood that the serde-transcode suggestion is to link both serializers to be able to convert from one into the other, but I don't understand the final pipeline, do we aim to always read and write into files as the bed format, but print and represent internally as the bioserde keyword like manner?

To the user, b"sq0\t7\t13\nsq0\t20\t34\n" would be deserialized into a bed::Record using the Deserializer implemented in this PR, whereas r#"{"chrom":"sq0","start":8,"end":13}"# would be deserialized into a bed::Record using serde_json. The bed::Record struct stays the same, and what changes is the Deserializer. Since the first representation is the standard BED file format, it would use the Deserializer implemented here, whereas the second representation is a JSON representation of BED, so it would use the serde_json Deserializer.

Serialization is similar; a bed::Record would be serialized using the Serializer implemented here if the user wants the output to be in the standard BED file format, and it would use the serde_json Serializer if they want the output to be in the JSON representation of BED.

Note, in all these cases Serialize and Deserialize don't need to be implemented manually, as these traits are used for mapping between the Serde data model and the struct itself, not the input and output files. Also, the Deserializer and Serializer would not be used directly. Instead, convenience functions would be used. On the serde_json side, these could be from_str or to_string. Similar functions can be written here for the standard BED file format (e.g.b"sq0\t7\t13\nsq0\t20\t34\n").

Let me know if that makes sense.
I'll write up some examples as well, to illustrate this process.

@mmalenic mmalenic left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @GabrielSimonetto,

Check out some of the changes in the branch I made. This might help clarify how the Deserialization and Serialization will look to the user.

Also, have a look at the rust-csv Deserializer. BED is like a very restricted form of CSV, so the CSV Deserializer and Serializer might useful. Notably, have a look at how sequences are handled when the Deserializer encounters a struct or a sequence.

With regards to manually implementing Deserialize and Serialize, you might be right. We might indeed have to implement parts of it manually, as the definitions of bed::Record are quite complicated in noodles. There could be ways to avoid this, such as using the Serde try_from attribute with an intermediary struct or using the Serde with attributes. There's also extension crates for Serde's derive macros, for example serde_with or serde_state, which may provide a solution.

Initially I thought that the derive macros alone would be enough to implement Serialize and Deserialize, however, bed::Record doesn't match the underlying record representation closesly, making it more challenging to use. Although, I do still think we should try and avoid manually implementing Serialize and Deserialize if possible.

Let me know if this makes sense, or any other questions you have.

@GabrielSimonetto
GabrielSimonetto merged commit 07bd3d0 into serde Sep 7, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants