Repository navigation
Description
The metadata API allows you to store any byte string along with nodes, sites and mutations. This allows us to store pickled Python objects, for example, which will work fine. However, this isn't great for portability:
- Obviously won't work on any other language than Python
- Pickling/unpickling requires the class definition to be in the current namespace, which can get tricky. In practise, this would probably end up causing compatability headaches across code versions.
It would be better if we could use some third-party approach for encoding metadata so that we can automatically decode the stored information into a Python object using a given schema. I'm thinking of things like JSON-schema and protobuf. If the schema is also stored in the HDF5 file, then the schema goes along with the data, making it much more likely the data can be interpreted correctly later.
I've done a little initial experimentation with this in #330, which shows how we can use JSON-schema, where the user is responsible for managing the schemas and so on. Here is a sketch of how it might work in the future if we put in some infrastructure for automatically decoding metadata into Python objects via a few pluggable hooks:
# Your schema for custom metadata defined using json-schema
schema = """{
"title": "Example Metadata",
"type": "object",
"properties": {
"one": {"type": "string"},
"two": {"type": "string"}
},
"required": ["one", "two"]
}"""
# Load this schema into an object builder, so that we make metadata objects
# Using https://github.com/cwacek/python-jsonschema-objects
builder = pjs.ObjectBuilder(json.loads(self.schema))
ns = builder.build_classes()
# Make a new metadata object, and assign it to a row in the nodes table.
metadata = ns.ExampleMetadata(one="node1", two="node2")
encoded = json.dumps(metadata.as_dict()).encode()
nodes.add_row(time=0.125, metadata=encoded)
# Load this table into a tree sequence, and store the schema so it can be retrieved later.
ts = msprime.load_tables(nodes=nodes, edges=edges, sequence_length=1)
ts.node_metadata_schema = schema
ts.dump("metadata-example.hdf5")
# Later, on another system, etc, we can load up the metadata and work with it.
ts = msprime.load("metadata-example.hdf5")
schema = json.loads(ts.node_metadata_schema)
builder = pjs.ObjectBuilder(json.loads(self.schema))
ns = builder.build_classes()
def decoder(encoded):
return ns.ExampleMetadata.from_json(encoded.decode())
# If a decoder function is set, accesses to the ``node.metadata`` are intercepted and the decoder
# function is use to translate the raw bytes into a Python object.
ts.node_metadata_decoder = decoder
node = ts.node(0)
node.metadata.one # == "one"
node.metadata.two # == "one"
This is all a bit vague, but I thought I'd open an issue to start discussion on the topic. This is definitely not something we should tackle before 0.5.0 is released --- none of this is backwards incompatible with what we have now.
Activity
jeromekelleher commentedon Aug 25, 2018
See issue #594 for an updated proposal on how to do this. Briefly, we attach a
metadata_schema(described in JSON using a JSON Schema) to each table that has a metadata field in it. We then support a few different formats. We can usestructfor simple fixed length records of binary values, maybe JSON schema to handle more general JSON records and perhaps MsgPack for more efficient encoding of more general structures.benjeffery commentedon Mar 13, 2020
I'm starting to look through this and consider the design.
Couple of initial thoughts:
https://pypi.org/project/schema/ is interesting - it would mean the schema types more closely matched what the user had in python. I'm thinking numpy arrays here, without having to look up how to specify an array in JSONSchema. It only does validation so we wouldn't have the fancy class creation that
pjs.ObjectBuildergives you, but I'm not convinced of the benefits ofmetadata = ns.ExampleMetadata(one="node1", two="node2")vsmetadata = {"one"': "node1", "two": node2)anyway.EDIT: Clearly would need to look into how such a schema would serialise.
EDIT2: Can generate JSONSchema
It would be possible to support user-defined formats, but I think this is unwise as it will lead to files that are unreadable without extra code. The important thing is to cover the uses cases well so that a custom format is not needed.
On this note, would one-format-to-rule-them-all be possible? Whats the benefit of using
structorjsonovermsgpack? It would simplify things to have just one if benefits of more are marginal.Do we care about the C API providing encode/decode? I don't yet have a good feel for where the high-level / low-level boundary is.
I'm still getting familiar with
tskit's code and use cases so comments welcome!jeromekelleher commentedon Mar 13, 2020
This is definitely a non-goal. It's just too complicated I think, and people can build what they need themselves on top of the raw bytes we're providing.
petrelharp commentedon Mar 13, 2020
I guess the tradeoffs are between readability, ease of use, and file size? I think maybe the most useful thing here would be to come up with some use cases beyond SLiM's. (btw, the SLiM metadata scheme is described well near the end of the SLiM manual; or, see how it's used in pyslim)
benjeffery commentedon Mar 16, 2020
Thinking about this more, to reduce the uncertainty I'm going to implement for
structjsonandmsgpack. This will help me get a better handle on the trade-offs and get some performance/storage size metrics.Initially this will require the user to specify an explicit schema, as a separate issue we can consider if it is desirable to add mechanisms to help them generate this from pre-existing metadata.
jeromekelleher commentedon Mar 16, 2020
Sounds like a plan @benjeffery!
benjeffery commentedon Mar 18, 2020
As I'm working this through I had a thought. We have multiple provenance records so that each tool along a pipeline can add it's entry. This current metadata proposal only has one metadata schema per table.
If a downstream tool or user wishes to add metadata they would have to read out the current metadata, merge the schema and contents and replace. Instead it could work like provenance where you add an additional schema and content. Accessors would then look like
node.metadata[0].oneor even (if metadata sets were named)node.metadata.NAME.onemight be nicer.jeromekelleher commentedon Mar 18, 2020
Hmm, that sounds tricky. I think we should consider the end-user's perspective as the most important, and they'll find having multiple layers of metadata confusing, I'd imagine. It's not such a big deal to read in the metadata, convert it into your own format and then write it out again with a new schema is it? (Especially when the metadata is decoded automatically...) I think we can say that well-behaved producers of tskit files are expected to maintain any existing metadata, if necessary translating to a new format.
Also, I'm not sure how we'd implement this in practise. We'd need to have another column recording the offsets of each metadata layer within the metadata column, which would be a lot of plumbing to add.
benjeffery commentedon Mar 18, 2020
Agreed that it would be more complex - I think I'm still getting my head round the creator vs consumer use-cases of the library. Like you say it isn't a massive burden on creators to manage metadata merging.
jeromekelleher commentedon Mar 18, 2020
In my mind the consumers vastly out-number creators, and they will often be people with limited programming experience. Our job is to make their lives as easy as possible, and to make it easy for them to do the right thing.