Writing JSON Serialised Objects#
Note
These docs now use the new_type
core objects via the following setting.
import os
# using new types without requiring an explicit argument
os.environ["COGENT3_NEW_TYPE"] = "1"
Using JSON, we can serialise cogent3
objects to a file for easy storage and retrieval.
Create an example object to serialise#
Let’s create a LikelihoodFunction
object to use in this example. It is generated from fitting the General Nucleotide (GN) model to an alignment of BRCA1 in primates.
from cogent3 import get_app
# Load the alignment
load_aligned_app = get_app("load_aligned", moltype="dna", format="fasta")
aln = load_aligned_app("data/primate_brca1.fasta")
# Fit the GN model
gn_model_app = get_app("model", "GN", tree="data/primate_brca1.tree")
model_result = gn_model_app(aln)
model_result.lf
GN
log-likelihood = -6987.9632
number of free parameters = 22
A>C | A>G | A>T | C>A | C>G | C>T | G>A | G>C | G>T | T>A | T>C |
---|---|---|---|---|---|---|---|---|---|---|
0.87 | 3.66 | 0.91 | 1.59 | 2.12 | 6.02 | 8.22 | 1.23 | 0.63 | 1.25 | 3.42 |
edge | parent | length |
---|---|---|
Galago | root | 0.17 |
HowlerMon | root | 0.04 |
Rhesus | edge.3 | 0.02 |
Orangutan | edge.2 | 0.01 |
Gorilla | edge.1 | 0.00 |
Human | edge.0 | 0.01 |
Chimpanzee | edge.0 | 0.00 |
edge.0 | edge.1 | 0.00 |
edge.1 | edge.2 | 0.00 |
edge.2 | edge.3 | 0.01 |
edge.3 | root | 0.01 |
A | C | G | T |
---|---|---|---|
0.38 | 0.17 | 0.21 | 0.24 |
write_json
- writing JSON-serialised object to file#
Using the write_json
app, we can write out the likelihood function as a JSON-serialised object, making it easy to retrieve the model parameters for future reference if required.
We need to provide the write_json
app with a data store to which it will write. Optionally when we apply the app we can specify an identifier for the data, which will name the file.
from cogent3 import get_app, open_data_store
# Initialise the write_json app with a data store
out_dstore = open_data_store(path_to_dir, mode="w", suffix="json")
write_json_app = get_app("write_json", data_store=out_dstore)
write_json_app(model_result.lf, identifier="gn_params.json")
DataMember(data_store=/home/runner/work/cogent3.github.io/cogent3.github.io/c3org/doc/doc/tmpsyn4io9x, unique_id=gn_params.json)
Note
Learn how to load a JSON serialised object in the loading JSON serialised objects section!
Tip
When running this code on your machine, remember to replace path_to_dir
with an actual directory path.