Skip to content

Demography metadata - #1316

Merged
mergify[bot] merged 2 commits into
tskit-dev:mainfrom
mcveanlab:demography-cleanups
Dec 1, 2020
Merged

mergify[bot] merged 2 commits into
tskit-dev:mainfrom
mcveanlab:demography-cleanups

Conversation

@jeromekelleher

Copy link
Copy Markdown
Member

Changes needed to make demography useable for 1.0.0a1.

WIP

@AdminBot-tskit

Copy link
Copy Markdown
Collaborator

📖 Docs for this PR can be previewed here

@benjeffery

Copy link
Copy Markdown
Member

Schema looks great, description is effectively optional, but always present.

@jeromekelleher jeromekelleher changed the title Demography updates for 1.0.0a1 Demography metadata Nov 26, 2020
@jeromekelleher
jeromekelleher marked this pull request as ready for review November 26, 2020 15:01
@codecov

codecov Bot commented Nov 26, 2020 •

Copy link
Copy Markdown

Codecov Report

Merging #1316 (2b7bc05) into main (d5c834c) will increase coverage by 0.00%.
The diff coverage is 96.00%.

Impacted file tree graph

@@           Coverage Diff           @@
##             main    #1316   +/-   ##
=======================================
  Coverage   90.32%   90.33%           
=======================================
  Files          26       26           
  Lines        8912     8926   +14     
  Branches     1845     1850    +5     
=======================================
+ Hits         8050     8063   +13     
  Misses        438      438           
- Partials      424      425    +1     
Flag Coverage Δ
C 90.33% <96.00%> (+<0.01%) ⬆️
python 98.58% <96.00%> (-0.04%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Impacted Files Coverage Δ
msprime/demography.py 99.30% <94.44%> (-0.17%) ⬇️
msprime/ancestry.py 98.97% <100.00%> (+<0.01%) ⬆️
msprime/cli.py 98.09% <100.00%> (+<0.01%) ⬆️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update d5c834c...2b7bc05. Read the comment docs.

@jeromekelleher

Copy link
Copy Markdown
Member Author

Here's a proposal for how we deal with metadata in msprime simulated populations. We're not talking about top-level metadata or any other entities yet, just populations.

For tree sequences produced by msprime.simulate(), the metadata will be the byte encoded JSON of the PopulationConfiguration object and no schema is set. That means that we don't break any existing code, and users can continue to use., e.g., md = json.loads(population.metadata).

For tree sequences produced by msprime.sim_ancestry(), we specify a simple and uncontroversial (hopefully) schema which requires a name and description attribute (but description can be None), which are filled in from the Population.name and Population.description attributes. Population.name is required to be a unique identifier to populations (e.g. "CEU").

Users are also allows to provide their own metadata that can be associated with populations. This is an arbitrary Python dictionary, which is then stored in the user key of the metadata.

Thus, all simulations produced by msprime.sim_ancestry will be guaranteed to have metadata that contains the population name. Here's an example test case, which hopefully illustrates the idea:

        demography = msprime.Demography.simple_model(10)
        md = {"x": "y", "z": "z", "abc": 1234}
        demography.populations[0].user_metadata = md
        ts = msprime.sim_ancestry(2, demography=demography, random_seed=2)
        assert ts.num_populations == 1
        metadata = ts.population(0).metadata
        assert metadata["name"] == "pop_0" # automatically set to this unless overridden
        assert metadata["description"] is None
        assert metadata["user"] == md

(Don't pay too much attention to the first 3 lines, as the way that we create Demography objects is still under development and this is pretty clunky.)

This is not a Population schema that would be appropriate for other programs, but we might consider reserving things like name and description in the top-level of the namespace as something we could standardise on.

This is an important decision which will affect upstream and downstream tools, so I'm hoping to get some thoughts from a bunch of people here! Pinging @petrelharp @benjeffery @hyanwong @molpopgen @benjeffery @grahamgower @apragsdale

@grahamgower

Copy link
Copy Markdown
Member

Sounds like a reasonable proposal. So the suggestion for downstream applications would be to put application specific stuff in user/<appname> and leave the rest of the user namespace to the actual user?

This is not a Population schema that would be appropriate for other programs, but we might consider reserving things like name and description in the top-level of the namespace as something we could standardise on.

Yes please!

@jeromekelleher

jeromekelleher commented Nov 26, 2020 •

Copy link
Copy Markdown
Member Author

Sounds like a reasonable proposal. So the suggestion for downstream applications would be to put application specific stuff in user/ and leave the rest of the user namespace to the actual user?

Actually, no, I don't think we should do namespacing by application. I think downstream applications should add extra keys to the top-level dictionary for generally useful stuff (i.e., for things that further downstream applications might use).

Which actually makes me wonder whether we should bother with the user key at all, and should instead update the top-level dictionary with the user_metdata field. If the user choses to overwrite the name field that's provided by default we can warn them, but we should probably let them.

I think we should be permissive when it comes to metadata, and should focus on what produces the easiest and nicest code for end users. I think we got too caught up in preventing rogue applications from clobbering existing metadata in earlier conversations, but maybe we should follow a more Pythonic philosophy of making it easy for end users to write good code, rather than trying to prevent them writing bad code. To me population.metadata["msprime"]["some_useful_data"] is much worse than population.metadata["some_useful_data"]

So yes, I think I've convinced myself now that we shouldn't have a user key, and that we should let up and downstream applications write whatever they want into the population metadata. (Contrary to the current code).

For reference, here's the schema I propose now:

           {
                "codec": "json",
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "description": {"type": ["string", "null"]},                
                },
                "required": ["name", "description"],
                "additionalProperties": True,
            }

@hyanwong

hyanwong commented Nov 26, 2020 •

Copy link
Copy Markdown
Member

Could we have a convention that non-user data should have a key that e.g. starts with an underscore? That would roughly mirror the use of underscores in python variable names. Alternatively we could end the key with an underscore, or perhaps use an initial capital letter to distinguish non-user keys. Either way, it would just be a convention, but possibly a useful one that would discourage clobbering.

(edit - I do quite like "official" keys starting with a capital letter, like "Name", "Msprime", or whatever, but it's all a matter of taste)

@jeromekelleher

Copy link
Copy Markdown
Member Author

Interesting idea... What are we trying to achieve by this though? if a user goes to the trouble of adding metadata into their simulations, they don't really make any distinction between "user data" and something like the population name. It would not improve their code in any way if some of the metadata keys that they use start with underscores and some don't - it would just be confusing.

@jeromekelleher

Copy link
Copy Markdown
Member Author

I really think we should focus on making end-user code as easy to read and follow as possible and not worry so much about clobbering. We can add some tooling to tskit which enables metadata updates that automatically warns on clobber. That's enough - it's really not that big a problem.

@hyanwong

Copy link
Copy Markdown
Member

I think I mean that publicly released software that adds metadata would be expected to use initial capital letters: that shifts the responsibility onto software devs to check they don't clobber each others' stuff. End users (like me) can then happily dump stuff into lowercase keys, without worrying that they might later run some software on the TS that accidentally clobbers the data that they carefully stuck there. It's simply an alternative to having a 'user' key.

As I said, it's only a helpful convention, not a strict rule. But it would be very easy to implement - it would just require a line of documentation.

@jeromekelleher

Copy link
Copy Markdown
Member Author

Here's my updated proposal: call the field Population.extra_metadata and just drop it right in to the top level:

    def test_extra_metadata(self):
        demography = msprime.Demography.simple_model(10)
        md = {"x": "y", "z": "z", "abc": 1234}
        demography.populations[0].extra_metadata = md
        ts = msprime.sim_ancestry(2, demography=demography, random_seed=2)
        assert ts.num_populations == 1
        metadata = ts.population(0).metadata
        assert metadata["name"] == "pop_0"
        assert metadata["description"] is None
        assert len(metadata) == len(md) + 2
        for key, value in md.items():
            assert metadata[key] == value

I'll probably update with a warning if we try to overwrite the existing fields.

@benjeffery

benjeffery commented Nov 26, 2020 •

Copy link
Copy Markdown
Member

I'm wary of solving problems we don't yet have with mechanisms to divide metadata in to categories such as capitals/underscores or by tool. I think this will discourage re-use of metadata and end up with downstream tools having to check a load of tool names or word formats. I don't think users need to worry as long as tools warn if they are overwriting keys, and we will encourage this by making it easy to use the tskit update_metadata method.

So in summary also think putting everything at the root of the metadata makes sense for now.

@hyanwong

Copy link
Copy Markdown
Member

I'm wary of solving problems we don't yet have with mechanisms to divide metadata in to categories such as capitals/underscores or by tool. I think this will discourage re-use of metadata and end up with downstream tools having to check a load of tool names or word formats.

Sure. You're the metadata guru, so whatever you say, I reckon.

I don't think users need to worry as long as tools warn if they are overwriting keys, and we will encourage this by making it easy to use the tskit update_metadata method.

As long as the tools warn before they do heavy lifting. I have some scripts that take e.g. 2 days to process a tree sequence. It would be pretty painful if an equivalent tool took 2 days to run, then aborted at the end because it didn't want to overwrite some metadata (I have hit this sort of issue many times over).

@hyanwong

hyanwong commented Nov 27, 2020 •

Copy link
Copy Markdown
Member

p.s. @benjeffery - maybe I'm unusual, or misguided or (more probably) both, but if there's no explicit place in the metadata that's recommended for me to store my own user data, than I feel it might actively discourage me from using the metadata area to store my own stuff. And unless I had read this discussion, I'd probably revert to using csv files instead, because I'd be worried that I was sorting stuff in the wrong place, or that whatever keys I chose would conflict with some other tool. I think that's why I keep on bringing up the issue: there's something about the freedom that you propose that would make me, with my naive user hat on and hoping for some explicit guidance, steer away from actually using metadata.

A line in the docs saying something like "although any keys can be used, the 'user' key (or whatever) is guaranteed not to be used in the official tskit toolchain" would, I suspect, go a long way to assuaging my (misplaced) worries in this regard.

I mean, now that you've reassured me, it's not an issue for me personally. But it would be my line of thinking if I had come to this from scratch, and so other users might be put off in the same way?

@benjeffery

Copy link
Copy Markdown
Member

Sure. You're the metadata guru, so whatever you say, I reckon.

I can be wrong! Often!

As long as the tools warn before they do heavy lifting. I have some scripts that take e.g. 2 days to process a tree sequence. It would be pretty painful if an equivalent tool took 2 days to run, then aborted at the end because it didn't want to overwrite some metadata (I have hit this sort of issue many times over).

Yeah I hate when that happens with long-running stuff - one of the reasons I think a warning should be the default. At least then you can patch up the metadata by hand if you wanted to retain the metadata that has been overwritten, without re-running your job.

I feel it might actively discourage me from using the metadata area

This is a good point - we should be sensitive to this in the docs.

@jeromekelleher

Copy link
Copy Markdown
Member Author

This is ready for review now I think. Parts of the Demography API are still pretty clunky, but I think the fundamental metadata question is settled here, which we should try to merge.

Comment thread msprime/demography.py Outdated
if len(intersection) > 0:
warnings.warn(
f"Overwriting standard metadata keys: {list(intersection)}; "
"this may lead to compatibility problems."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is this warning right? Isn't it "existing" keys, not necessarily "standard" keys? Also, "compatibility" problems is pretty vague and alarming - I'd say either say concretely what the problems might be, or else just warn "overwriting existing keys: { }".

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Well, we do hope to standardise these (name and description) - and they are definitely standard metadata for msprime. I take your point about the warning, but it's hard to pinpoint what might happen downstream if you change the name of the population to something else. Probably nothing, but then why would you want to overwrite the name or description when you can set these as properties on the Population object in the first place. So - maybe this should be an error then, since you can always set the name and description via the Population class and it's probably a mistake if you're overwriting these.

@grahamgower, any thoughts here? I'm imagining stdpopsim as being one of the key users of this metadata API. Should this be a warning or an error?

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.

Probably it should be an error. I also can't see any reason to modify these, so it would most likely be done only accidentally.

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.

It might be because of my comment that it's a pain if a long-running script errors out after (say) 2 days or running, just before saving the final data files. I guess that's good reason to make these sorts of changes before you enter long-running loops, but that's not always the natural thing to do.

I've definitely had problems with long running scripts failing at the very end due to things that were not vital to do, but which I would like to have been warned about. But I probably just have bad coding practices.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Right, but I don't see how this would happen for an msprime simulation. We're not talking about general rules here, just what to do in this specific situtation.

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.

Ah, good point. Seems sensible to error out then.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

OK, I'll change this to an error and then I think we're good to merge.

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.

I agree - error in this case.

@petrelharp

Copy link
Copy Markdown
Contributor

Sounds good! I agree with the conclusion.

@benjeffery benjeffery 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.

LGTM - one question about required

Comment thread msprime/demography.py Outdated
if len(intersection) > 0:
warnings.warn(
f"Overwriting standard metadata keys: {list(intersection)}; "
"this may lead to compatibility problems."

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.

I agree - error in this case.

Comment thread msprime/demography.py
"name": {"type": "string"},
"description": {"type": ["string", "null"]},
},
"required": ["name", "description"],

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.

Given the discussion around standardised schemas being flexible (and we intend this schema to be replaced with a reference to the standard one) - what's the thinking around description being required. It could be absent instead of None? We don't want all standardised keys to be required, so why this one?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, I agree. Initially I thought it would be nice if users of msprime could be sure that the description key was always present, even if equal to None. But, we can do that anyway and don't need to state it in the schema. So, I guess there's no real point in making name required here either, come to think of it.

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.

Having thought about this further - any metadata that we feel strongly enough that it be required in the standard schema probably should be in the data model and not metadata, right?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Hah, actually no, I've had a (re)change of heart there. By making these fields required in the schema, we're passing on valuable information to downstream software: you're guaranteed that these values are defined in each bit of metadata. This isn't a general thing, just that in msprime's case we will always have these fields. The "standard" base schemas shouldn't make anything mandatory, but programs can choose to notify client code that the fields will always be present, if they wish.

@benjeffery benjeffery Dec 1, 2020 •

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.

Gotcha - msprime will modify the base standard schema to indicate what it always provides.

@jeromekelleher
jeromekelleher force-pushed the demography-cleanups branch 2 times, most recently from 031d898 to caa3991 Compare December 1, 2020 23:07
@mergify
mergify Bot merged commit a9d82db into tskit-dev:main Dec 1, 2020
@jeromekelleher
jeromekelleher deleted the demography-cleanups branch December 1, 2020 23:28
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.

6 participants