Skip to content

Add node metadata #2842

Closed
Closed

Description

@ShyamieG

Hi there,

I'm running into a bug when attempting to add additional metadata to my nodes. The tree sequence was generated in SLiM, so it has the normal metadata associated with that.

When I try to add another property ("node_tag", a string), I get the following error:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
  File "/Users/shyamie/miniconda3/envs/slim-env/lib/python3.9/site-packages/tskit/metadata.py", line 636, in __init__
    codec_instance = codec_cls(schema)
  File "/Users/shyamie/miniconda3/envs/slim-env/lib/python3.9/site-packages/tskit/metadata.py", line 582, in __init__
    decoder = StructCodec.make_decode(schema)
  File "/Users/shyamie/miniconda3/envs/slim-env/lib/python3.9/site-packages/tskit/metadata.py", line 326, in make_decode
    return StructCodec.make_object_or_null_decode(sub_schema)
  File "/Users/shyamie/miniconda3/envs/slim-env/lib/python3.9/site-packages/tskit/metadata.py", line 380, in make_object_or_null_decode
    sub_decoders = {
  File "/Users/shyamie/miniconda3/envs/slim-env/lib/python3.9/site-packages/tskit/metadata.py", line 381, in <dictcomp>
    key: StructCodec.make_decode(prop)
  File "/Users/shyamie/miniconda3/envs/slim-env/lib/python3.9/site-packages/tskit/metadata.py", line 328, in make_decode
    return {
  File "/Users/shyamie/miniconda3/envs/slim-env/lib/python3.9/site-packages/tskit/metadata.py", line 402, in make_string_decode
    f = "<" + sub_schema["binaryFormat"]
KeyError: 'binaryFormat'

To give you a reproducible example, my code follows. I have also attached an example tree sequence.

import tskit

# Read in tree
tree = tskit.load("inf-2_V1_to_H33_on_day_45.trees")

# Add metadata
metadata_schema = tree.tables.nodes.metadata_schema.schema
# if node_tag is not already initialized, add it
if "node_tag" not in metadata_schema.get("properties").keys():
	metadata_schema["properties"]["node_tag"] = {"description":"Additional metadata specifying exactly where in the Ross-Macdonald sequence this node was generated.", "type":"string"}
	tree_tables = tree.dump_tables()
	tree_tables.nodes.metadata_schema = tskit.MetadataSchema(metadata_schema)

Any ideas how to fix this? Thanks in advance!

Activity

  1. ShyamieG commented on Sep 22, 2023

    @ShyamieG
    Author

    Sorry, re-opening this. I thought I had solved the issue.

    I determined that I should specify a 'binaryFormat' for my new property. I tried 's' and 'p' (based on reading https://docs.python.org/3/library/struct.html#format-characters)

    metadata_schema["properties"]["node_tag"] = {"binaryFormat":"s", "description":"Additional metadata specifying exactly where in the Ross-Macdonald sequence this node was generated.", "type":"string"}
    

    However, when I try to access the node metadata now I get the following error:

    Traceback (most recent call last):
      File "<stdin>", line 2, in <module>
      File "/Users/shyamie/miniconda3/envs/slim-env/lib/python3.9/site-packages/tskit/metadata.py", line 744, in __get__
        row, "_metadata", row._metadata_decoder(row._metadata)
      File "/Users/shyamie/miniconda3/envs/slim-env/lib/python3.9/site-packages/tskit/metadata.py", line 583, in <lambda>
        self.decode = lambda buffer: decoder(iter(buffer))
      File "/Users/shyamie/miniconda3/envs/slim-env/lib/python3.9/site-packages/tskit/metadata.py", line 393, in decode_object_or_null
        return {
      File "/Users/shyamie/miniconda3/envs/slim-env/lib/python3.9/site-packages/tskit/metadata.py", line 394, in <dictcomp>
        key: sub_decoder(buffer)
      File "/Users/shyamie/miniconda3/envs/slim-env/lib/python3.9/site-packages/tskit/metadata.py", line 438, in <lambda>
        return lambda buffer: struct.unpack(f, bytes(islice(buffer, size)))[0]
    struct.error: unpack requires a buffer of 1 bytes
    

    Ultimately, I'm trying to create a property that will allow me to store a string of flexible length.

  2. petrelharp commented on Sep 22, 2023

    @petrelharp
    Contributor

    Hah, I've been writing this at the same time as you.

    ... in response to your previous comment: yes, that's right but I think you may still run into some issues (which you did). Here's the explanation:

    There's two ways that metadata can be encoded, roughly: (a) as json-text, or (b) directly packing bytes in binary. The thing that controls which is done is the codec property of the metadata schema; and SLiM uses (b), so in the metadata schema, codec="struct". For this codec, you need to tell it how to pack those bytes in, as you discovered.

    However, if you change the metadata schema, you'll no longer be able to read existing metadata, since it's in binary. (This is less of a problem for the json codec, since what's stored is just a text string.) So to modify the metadata you'll need to do some unpacking-and-repacking. Here's an example where I add an int:

    tables = ts.tables
    tables.nodes.clear()
    
    metadata_schema = tables.nodes.metadata_schema.schema
    metadata_schema["properties"]["node_tag"] = {"binaryFormat":"i", "description":"An integer for additional info", "type":"integer", "default": 0}
    tables.nodes.metadata_schema = tskit.MetadataSchema(metadata_schema)
    
    for k, n in enumerate(ts.nodes()):
        md = n.metadata
        md['node_tag'] = k
        tables.nodes.append(n.replace(metadata=md))
    
    new_ts = tables.tree_sequence()
    print(new_ts.node(10))
    

    (Now I'll read your next comment...)

  3. petrelharp commented on Sep 22, 2023

    @petrelharp
    Contributor

    Ah-ha - I was afraid that you wanted to store a string of variable length. That's not currently supported by the struct codec (I think?), basically for efficiency reasons. The solution is to switch to the json codec.

    However, it's important to know that if you change the metadata format you won't be able to read this back into SLiM. If you do want to do that, an alternative is to just stick the information in toplevel metadata, as a vector of length equal to number of nodes, for instance.

  4. petrelharp commented on Sep 22, 2023

    @petrelharp
    Contributor

    Here's an example of switching to json:

    tables = ts.tables
    tables.nodes.clear()
    
    metadata_schema = tables.nodes.metadata_schema.schema
    metadata_schema["properties"]["node_tag"] = {"description":"An integer for additional info", "type":"string", "default": ""}
    metadata_schema["codec"] = "json"
    tables.nodes.metadata_schema = tskit.MetadataSchema(metadata_schema)
    
    for k, n in enumerate(ts.nodes()):
        md = n.metadata
        md['node_tag'] = str(k)
        _ = tables.nodes.append(n.replace(metadata=md))
    
    new_ts = tables.tree_sequence()
    print(new_ts.node(10))
    
    
  5. petrelharp commented on Sep 22, 2023

    @petrelharp
    Contributor

    As you can tell, improving documentation and error messages for metadata is on the TODO list.

  6. petrelharp commented on Sep 22, 2023

    @petrelharp
    Contributor

    Also note that using the json codec will be slower and take up more space than the struct codec. (I'm not sure how much, though!) But if you're storing strings of variable length, that's pretty much unavoidable.

  7. ShyamieG commented on Sep 22, 2023

    @ShyamieG
    Author

    Thank you so much! Once again, your explanations have really helped clear up my confusion 😂 I should have put more effort into trying to understand the different codecs/binary formats before messing around with the metadata.

    I think I'll modify my approach to encode all additional metadata as integers to keep things efficient/compatible with SLiM.

  8. ShyamieG commented on Sep 22, 2023

    @ShyamieG
    Author

    Hi again,

    I got everything working so that I have two new properties in my metadata (integers, to avoid having to change the codec). However, when I try to read the resulting tree back into SLiM, I get a Simulation Runtime Error:

    ERROR (SLiMSim::__TabulateSubpopulationsFromTreeSequence): unexpected node metadata length; this file cannot be read.
    
    This error has invalidated the simulation; it cannot be run further.  Once the script is fixed, you can recycle the simulation and try again.
    

    It seems to be complaining about the node metadata length... but I thought SLiM would be flexible about that? This is my tree.

    Edited to add that I'm still using SLiM 3, if that matters

    Edited again to say that I am getting a similar error with SLiM 4 :(

  9. petrelharp commented on Sep 25, 2023

    @petrelharp
    Contributor

    I should have put more effort into trying to understand the different codecs/binary formats before messing around with the metadata.

    That's always appreciated, but on the contrary, you've put in a lot of work here and this thread will be useful for others, I think - no worries.

    It seems to be complaining about the node metadata length... but I thought SLiM would be flexible about that?

    Ah, sorry, I should have been more clear above. SLiM is not flexible about metadata length. The reason is that the binary encoding that it uses is hardcoded: SLiM could in principle read and use the metadata schema, but that would be a whole can of worms, so it's not done.

    So - if you want to read the information back into SLiM, I would not store the extra information in node metadata, but instead store it in top level metadata. Here's a real simple example where I just (a) in SLiM, store in top-level metadata some information about each node (the sum of their mutations' effects), and (b) associate it with the corresponding nodes in python (by making a dictionary with keys equal to the tskit-node-ids).

    First, SLiM:

    // set up a simple neutral simulation
    initialize() {
    	initializeSLiMOptions(keepPedigrees=T);
    	initializeMutationRate(1e-7);
    	initializeTreeSeq();
    	
    	// m1 mutation type: neutral
    	initializeMutationType("m1", 0.5, "f", -0.1);
    	
    	// g1 genomic element type: uses m1 for all mutations
    	initializeGenomicElementType("g1", m1, 1.0);
    	
    	// uniform chromosome of length 100 kb with uniform recombination
    	initializeGenomicElement(g1, 0, 99999);
    	initializeRecombinationRate(1e-8);
    }
    
    // create a population of 500 individuals
    1 early() {
    	sim.addSubpop("p1", 500);
    }
    
    10 early() {
    	node_fitnesses = p1.genomes.sumOfMutationsOfType(m1);
    	node_ids = p1.genomes.genomePedigreeID;
    	sim.treeSeqOutput("out.trees",
    		metadata=Dictionary("node_ids", node_ids, "node_fitnesses", node_fitnesses)
    	);
    }
    

    Then, python:

    import tskit
    ts = tskit.load("out.trees")
    
    node_info_from_metadata = { n : f for n, f in
                        zip(ts.metadata['SLiM']['user_metadata']['node_ids'],
                            ts.metadata['SLiM']['user_metadata']['node_fitnesses']
                           ) }
    
    tskit_node_info = { n.id : n.metadata  for n in ts.nodes() }
    
    for n, md in tskit_node_info.items():
        n_id = md['slim_id']
        if n_id in node_info_from_metadata:
            md['fitness'] = node_info_from_metadata[md['slim_id']]
    

    So then for instance, tskit-node 10 represents the genome with SLiM ID 9010:

    >>> tskit_node_info[10]
    {'slim_id': 9010, 'is_null': False, 'genome_type': 0, 'fitness': -0.10000000149011612}
    

    I've been meaning to write something like this for the pyslim documentation.

  10. ShyamieG commented on Sep 25, 2023

    @ShyamieG
    Author

    Okay, this makes a lot of sense - thank you!

    Do you know if there is a way to access this top-level metadata within SLIM itself? For example, if I were to load the tree sequence you created above by a different SLiM script, how could I access the node_ids and node_fitnesses elements you defined?

  11. ShyamieG commented on Sep 26, 2023

    @ShyamieG
    Author

    I've been playing around with this more, and it seems like it won't work as I had hoped. I'm trying to find some way to add metadata (ideally to the nodes themselves, but at least to the top-level metadata) such that it can be tracked across multiple SLiM simulations that are chained together.

    I'm able to add stuff to the "user_metadata" slot when I output the tree sequence from my SLiM simulation, and I can access it with tskit, but this information is not preserved if I then read that tree sequence back into SLiM (using readFromPopulationFile) and output the tree sequence some generations later.

    Is what I am attempting possible, or do I need to re-think this approach altogether?

  12. petrelharp commented on Sep 27, 2023

    @petrelharp
    Contributor

    Hm - you're right, that SLiM doesn't allow access to the extra, user-added metadata when it reads in a tree sequence. That would be a nice thing, though, to enable the sort of thing you're trying to do - perhaps readFromPopulationFile( ) could return a dictionary containing anything in SLiM/user_metadata of the tree sequence? If that seems like a good and useful idea, we should perhaps open an issue over at SLiM?

    Lacking that, though, the only way I can think of to do what you're trying to do is to write out the information to a text file and read it into SLiM that way. @bhaller - any other suggestions?

  13. ShyamieG commented on Sep 27, 2023

    @ShyamieG
    Author

    perhaps readFromPopulationFile( ) could return a dictionary containing anything in SLiM/user_metadata of the tree sequence?

    Yes, that would work. I can open an issue over there and link to this discussion.

    I was hoping to avoid having to write out a text file for each output tree, but it seems that will the best way to go about this for the time being.

    Thanks again for your responses, your input has been extremely helpful!

  14. bhaller commented on Sep 27, 2023

    @bhaller

    The treeSeqMetadata() function is there for exactly this purpose. Simply call it to get your metadata dictionary back.

  15. petrelharp commented on Sep 27, 2023

    @petrelharp
    Contributor

    Perhaps I'll close this issue, and open a new one in SLiM or pyslim as appropriate, if there's further things to discuss? Feel free to re-open though @ShyamieG .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions