Data Exploration and Visualization of NOM Data in NMDC (FT ICR-MS)¶

This notebook identifies natural organic matter (NOM) data sets in the National Microbiome Data Collaborative (NMDC), filters those datasets based on quality control metrics, and analyzes the molecular composition of the chosen datasets via heatmaps and Van Krevelen plots. This notebook uses the nmdc-client package to do this exploration. It involves using nmdc-client objects to make NMDC API requests easier, and using utility function to help us with data processing tasks. More information about the package can be found here

In [3]:
import requests
from io import StringIO
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import sys
from matplotlib.patches import Patch
import nmdc_client

Define a function to split a list into chunks¶

Since we will need to use a list of ids to query a new collection in the API, we need to limit the number of ids we put in a query. This function splits a list into chunks of 100. Note that the chunk_size has a default of 100, but can be adjusted.

In [4]:
# Define a function to split ids into chunks
def split_list(input_list, chunk_size=100):
    result = []
    
    for i in range(0, len(input_list), chunk_size):
        result.append(json.dumps(input_list[i:i + chunk_size]))
        
    return result

Define a function to get a list of ids from initial results¶

In order to use the identifiers retrieved from an initial API request in another API request, this function is defined to take the initial request results and use the id_name key from the results to create a list of all the ids. The input is the initial result list and the name of the id field.

In [5]:
def get_id_list(result_list: list, id_name: str):
    id_list = []
    for item in result_list:
        if type(item[id_name]) == str:
            id_list.append(item[id_name])
        elif type(item[id_name]) == list:
            for another_item in item[id_name]:
                id_list.append(another_item)

    return id_list

Gather the IDs for processed NOM results in NMDC by filtering for data objects of type "Direct Infusion FT ICR-MS"¶

Use the nmdc-client DataObjectSearch to gather processed NOM results. The function get_record_by_attribute gets record by input attribute name and value. See the documentation for more details here.

We pass in data_object_type using a keyword search of “Direct Infusion FT ICR-MS Analysis Results”. Extract the fields id (necessary for traversing the NMDC schema), url (necessary for pulling data) and md5_checksum (used to check uniqueness of data set). The fucntion will create the filter and API request from these paramters.

In [6]:
from nmdc_client.data_object_search import DataObjectSearch
dos_client = DataObjectSearch(api_base_url=ENV)
processed_nom = dos_client.get_record_by_attribute(attribute_name='data_object_type', attribute_value='Direct Infusion FT-ICR MS Analysis Results', max_page_size=100, fields='id,md5_checksum,url', all_pages=True)
# clarify names
for dataobject in processed_nom:
    dataobject["processed_nom_id"] = dataobject.pop("id")
    dataobject["processed_nom_md5_checksum"] = dataobject.pop("md5_checksum")
    dataobject["processed_nom_url"] = dataobject.pop("url")

# convert to df
processed_nom_df = pd.DataFrame(processed_nom)
processed_nom_df
Out[6]:
processed_nom_id processed_nom_md5_checksum processed_nom_url
0 nmdc:dobj-11-002nyy42 5cd810390dc64616e28579161fe15029 https://nmdcdemo.emsl.pnnl.gov/nom/blanchard_1...
1 nmdc:dobj-11-003x7710 0391d9ff37a1926d5cf0eaec126ad4ff https://nmdcdemo.emsl.pnnl.gov/nom/blanchard/r...
2 nmdc:dobj-11-005z8n44 802dfaa79d2cf6921f45fa41d6f82c9d https://nmdcdemo.emsl.pnnl.gov/nom/monet_nom/p...
3 nmdc:dobj-11-006w2544 d06ee837d042b8b09b99a288c6d0f350 https://nmdcdemo.emsl.pnnl.gov/nom/monet_nom/p...
4 nmdc:dobj-11-00dewm52 2a532dca15798e470103ebd752a0937f https://nmdcdemo.emsl.pnnl.gov/nom/1000soils/r...
... ... ... ...
6583 nmdc:dobj-13-zrp1qw41 98b97b78fff542b66e72f4b3f792d80f https://nmdcdemo.emsl.pnnl.gov/nom/results/SBR...
6584 nmdc:dobj-13-zsqpnm92 3e9e19910edb209d211d9f915e36b8cb https://nmdcdemo.emsl.pnnl.gov/nom/results/Bro...
6585 nmdc:dobj-13-zvnmsp76 aec0521d6a36a440e41052f8eadc0d1d https://nmdcdemo.emsl.pnnl.gov/nom/results/Ung...
6586 nmdc:dobj-13-zvzx2462 9f0d52cc46d247b8d2ba12d5842b9fb6 https://nmdcdemo.emsl.pnnl.gov/nom/results/Bro...
6587 nmdc:dobj-13-zye5fe51 8ddaeeffe93db9c4258a03e881d329cf https://nmdcdemo.emsl.pnnl.gov/nom/results/Bro...

6588 rows × 3 columns

Continue traversing the NMDC schema by using the list of identifiers from the previous API call to query the next collection¶

Find the analysis records that produced these processed nom object IDs by matching object processed_nom_id to the has_output slot with a filter and the WorkflowExecutionSearch object. Also extract the has_input slot as it will be used for the next traversal, grabbing the raw data objects that are used as input to the nom analysis records.

In [7]:
from nmdc_client.workflow_execution_search import WorkflowExecutionSearch
# since we are querying the WorkflowExecution collection, we need to create an instance of it
we_client = WorkflowExecutionSearch(api_base_url=ENV)
result_ids = processed_nom_df['processed_nom_id'].tolist()
# create a list of lists of ids to query the WorkflowExecutionSearch object
chunked_list = split_list(result_ids)
analysis_dataobj = []
# loop through the chunked list of ids
for chunk in chunked_list:
    # create the filter - query the WorkflowExecutionSearch object looking for data objects where the has_output field is in the chunk of ids from processed_nom
    filter = f'{{"has_output": {{"$in": {chunk}}}}}'
    # get the results
    analysis_dataobj += we_client.get_record_by_filter(filter=filter, fields="id,has_input,has_output", max_page_size=100, all_pages=True)

# clarify names
for dataobject in analysis_dataobj:
    dataobject["analysis_id"] = dataobject.pop("id")
    dataobject["analysis_has_input"] = dataobject.pop("has_input")
    dataobject["analysis_has_output"] = dataobject.pop("has_output")

# convert to data frame
analysis_dataobj_df = pd.DataFrame(analysis_dataobj)
analysis_dataobj_df
Out[7]:
analysis_id analysis_has_input analysis_has_output
0 nmdc:wfnom-11-twqqjq28.2 [nmdc:dobj-11-vq0zcy81, nmdc:dobj-11-6qh8ae86] [nmdc:dobj-11-mfvjhy66, nmdc:dobj-11-002nyy42]
1 nmdc:wfnom-11-dv3wck24.1 [nmdc:dobj-11-2ysghy98, nmdc:dobj-11-bmeg5b74] [nmdc:dobj-11-003x7710]
2 nmdc:wfnom-11-bkywqv49.1 [nmdc:dobj-11-8zttxk50, nmdc:dobj-11-nqseb358] [nmdc:dobj-11-005z8n44, nmdc:dobj-11-pzjg7h45]
3 nmdc:wfnom-11-f1egqr31.1 [nmdc:dobj-11-ees5fy07, nmdc:dobj-11-y5ddq941] [nmdc:dobj-11-q3twpm19, nmdc:dobj-11-006w2544]
4 nmdc:wfnom-11-0mqv1c63.1 [nmdc:dobj-11-3hfzr472] [nmdc:dobj-11-00dewm52]
... ... ... ...
6583 nmdc:wfnom-13-08q56295.1 [nmdc:dobj-13-vg0tgv60] [nmdc:dobj-13-zrp1qw41]
6584 nmdc:wfnom-13-yy5yqx31.1 [nmdc:dobj-13-w15zk074] [nmdc:dobj-13-zsqpnm92]
6585 nmdc:wfnom-13-4xrsd836.1 [nmdc:dobj-13-3rmgcm64] [nmdc:dobj-13-zvnmsp76]
6586 nmdc:wfnom-13-h0r53g59.1 [nmdc:dobj-13-m3zkxg02] [nmdc:dobj-13-zvzx2462]
6587 nmdc:wfnom-13-4vmrb525.1 [nmdc:dobj-13-60z8rt70] [nmdc:dobj-13-zye5fe51]

6588 rows × 3 columns

Find the raw data objects used as input for these analysis records by matching the analysis record's has_input slot to the id slot in the collection data_object_set. Create a DataObjectSearch object to do so.

Workflows can take multiple inputs (eg. configuration or parameter files) in addition to the raw data, so we will filter the results to only keep raw data object IDs.

In [8]:
# get a list of the ids from raw_dataobj
result_ids = analysis_dataobj_df['analysis_has_input'].explode().unique().tolist()
# create a list of lists of ids to query the DataObjectSearch object
chunked_list = split_list(result_ids)
raw_dataobj = []
# loop through the chunked list of ids
for chunk in chunked_list:
    # create the filter - query the DataObjectSearch object looking for data objects where the id field is in the chunk of ids from analysis_dataobj
    filter = f'{{"id": {{"$in": {chunk}}}}}'
    # get the results
    raw_dataobj += dos_client.get_record_by_filter(filter=filter, fields="id,name,data_object_type", max_page_size=100, all_pages=True)

# clarify names
for dataobject in raw_dataobj:
    dataobject["raw_id"] = dataobject.pop("id")
    dataobject["raw_name"] = dataobject.pop("name")

# Filter out parameter files (leave NAs in case raw data files are missing a label)
param_dataobj = [file for file in raw_dataobj if 'data_object_type' in file and file['data_object_type'] == 'Analysis Tool Parameter File']
raw_dataobj = [file for file in raw_dataobj if file not in param_dataobj]

raw_df = pd.DataFrame(raw_dataobj)

raw_df
Out[8]:
data_object_type raw_id raw_name
0 Direct Infusion FT ICR-MS Raw Data nmdc:dobj-11-0jm68b51 Miesel_60009_04_BONA_Oea_PRE_H2O_SPE_r1_26Jan2...
1 Direct Infusion FT ICR-MS Raw Data nmdc:dobj-11-11rsav74 60920_1_BTM_1_MAOM_r3_Mag_19Feb25_3p3kV_300SA_...
2 Direct Infusion FT ICR-MS Raw Data nmdc:dobj-11-18tyaw19 Lybrand_FT_51_C_30Aug19_Alder_Infuse_p05_1_01_...
3 Direct Infusion FT ICR-MS Raw Data nmdc:dobj-11-2mk4qf09 1000s_DELA_FTMS_SPE_TOP_2_29Oct22_Mag_300SA_p0...
4 Direct Infusion FT ICR-MS Raw Data nmdc:dobj-11-2ysghy98 Blanchard_CHCl3Ext_H-32-AB-M_19Feb18_Alder_Inf...
... ... ... ...
4000 Direct Infusion FT ICR-MS Raw Data nmdc:dobj-13-agqfmw73 output: Unground_SBR_Spring_2014_FC_N1_00-10_M...
4001 Direct Infusion FT ICR-MS Raw Data nmdc:dobj-13-nmvp0v05 output: Brodie_193_H2O_12Mar19_R3_HESI_Neg
4002 Direct Infusion FT ICR-MS Raw Data nmdc:dobj-13-sjw1pv51 output: Brodie_198_H2O_12Mar19_R3_HESI_Neg
4003 Direct Infusion FT ICR-MS Raw Data nmdc:dobj-13-xagt3g94 output: Brodie_183_H2O_14Mar19_R3_HESI_Neg
4004 Direct Infusion FT ICR-MS Raw Data nmdc:dobj-13-zr9fqh14 output: Brodie_357_H2O_3_IATp1_07Dec18_1_01_38229

4005 rows × 3 columns

Find the data generation records capturing mass spectrometry information for these raw data objects by matching the data object's id slot to the has_output slot in the collection data_generation_set. Create a DataGenerationSearch object to do so. Once again extract the has_input slot as it will be used for the next traversal, grabbing the biosample data objects that are used as input to the data generation records.

In [9]:
from nmdc_client.data_generation_search import DataGenerationSearch
dgs_client = DataGenerationSearch(api_base_url=ENV)
# use utility function to get a list of the ids from raw_dataobj
result_ids = raw_df["raw_id"].tolist()
# create a list of lists of ids to query the DataGenerationSearch object
chunked_list = split_list(result_ids)
datageneration_dataobj = []
# loop through the chunked list of ids
for chunk in chunked_list:
    # create the filter - query the DataGenerationSearch object looking for data objects that have the raw_id in the has_output field
    filter = f'{{"has_output": {{"$in": {chunk}}}}}'
    # get the results
    datageneration_dataobj += dgs_client.get_record_by_filter(filter=filter, fields="id,has_input,has_output", max_page_size=100, all_pages=True)

# clarify names
for dataobject in datageneration_dataobj:
    dataobject["datageneration_id"] = dataobject.pop("id")
    dataobject["datageneration_has_output"] = dataobject.pop("has_output")
    dataobject["datageneration_has_input"] = dataobject.pop("has_input")
# convert to data frame
datageneration_dataobj_df = pd.DataFrame(datageneration_dataobj)
datageneration_dataobj_df
Out[9]:
datageneration_id datageneration_has_output datageneration_has_input
0 nmdc:omprc-11-rj3bqn04 [nmdc:dobj-11-09p17z03] [nmdc:procsm-11-ckacrz04]
1 nmdc:omprc-11-tddeh411 [nmdc:dobj-11-0df8t083] [nmdc:procsm-11-fn9kvs80]
2 nmdc:dgms-11-zbcrgh12 [nmdc:dobj-11-0jm68b51] [nmdc:procsm-11-tyb73826]
3 nmdc:dgms-11-crm4ar11 [nmdc:dobj-11-0qn67a17] [nmdc:procsm-11-zme94j45]
4 nmdc:dgms-11-6wyv6n20 [nmdc:dobj-11-11rsav74] [nmdc:procsm-11-nj446153]
... ... ... ...
4000 nmdc:omprc-13-x2zva844 [nmdc:dobj-13-agqfmw73] [nmdc:procsm-11-syzphh15]
4001 nmdc:omprc-11-c334q041 [nmdc:dobj-13-nmvp0v05] [nmdc:procsm-11-pe6d0621]
4002 nmdc:omprc-11-rjwysn24 [nmdc:dobj-13-sjw1pv51] [nmdc:procsm-11-pm6xbm06]
4003 nmdc:omprc-11-9xfb9e80 [nmdc:dobj-13-xagt3g94] [nmdc:procsm-11-mt9gzk43]
4004 nmdc:omprc-11-t88ntb43 [nmdc:dobj-13-zr9fqh14] [nmdc:procsm-11-ma7qff55]

4005 rows × 3 columns

Find the inputs for these data generation records based on whether they are biosamples or processed samples. This can vary depending on if a sample went through any material processing prior to mass spectrometry.

In [10]:
datageneration_dataobj_df['datageneration_has_input'].explode().str.extract('nmdc:(procsm|bsm)')[0].value_counts(dropna=False)
Out[10]:
0
procsm    3773
bsm        232
Name: count, dtype: int64

Find the biosample from which each processed sample originates by creating a MaterialProcessingSet and iterating through material processing steps until the has_input value is a biosample.

In [11]:
from nmdc_client.material_processing_search import MaterialProcessingSearch
mp_client = MaterialProcessingSearch()

# use utility function to get a unique list of the ids from datageneration_dataobj
result_ids = list(set(datageneration_dataobj_df["datageneration_has_input"].sum(axis=0)))

# separate ids into processedsample_ids and biosample_ids
processedsamples = [item for item in result_ids if 'nmdc:procsm' in item]
biosamples = [item for item in result_ids if 'nmdc:bsm' in item]

# dataframe of intermediate processed samples to track
tracking_ps = pd.DataFrame({'intermediate_ps':processedsamples,'dg_input':processedsamples})

# dataframe of tracked biosample inputs mapped to the input given to data generation
tracked = [pd.DataFrame({'biosample_id':biosamples,'dg_input':biosamples})]


while tracking_ps.shape[0]>0:

    # get api calls for these processed samples
    chunked_list = split_list(tracking_ps['intermediate_ps'].tolist())
    mp_dataobj = []
    for chunk in chunked_list:
        filter = f'{{"has_output": {{"$in": {chunk}}}}}'
        mp_dataobj += mp_client.get_record_by_filter(filter=filter, fields='has_input,has_output', max_page_size=100, all_pages=True)

    mp_dataobj = pd.DataFrame(mp_dataobj).explode('has_input').explode('has_output').merge(tracking_ps,right_on='intermediate_ps',left_on='has_output').drop(['has_output','id'],axis=1)

    # separate steps with biosample vs processed sample inputs
    biosample_input = mp_dataobj[mp_dataobj['has_input'].str.contains('nmdc:bsm',na=False)].drop('intermediate_ps',axis=1).rename(columns={'has_input':'biosample_id'})
    processedsample_input = mp_dataobj[mp_dataobj['has_input'].str.contains('nmdc:procsm',na=False)].drop('intermediate_ps',axis=1).rename(columns={'has_input':'intermediate_ps'}) # new ps input is now intermediate_ps

    # update tracking_ps
    tracking_ps = processedsample_input

    # update tracked to those steps with a biosample input
    if not biosample_input.empty:
        tracked.append(biosample_input)

datageneration_inputupdate_df = pd.concat(tracked, ignore_index=True).merge(datageneration_dataobj_df.explode('datageneration_has_input').explode('datageneration_has_output'),left_on='dg_input',right_on='datageneration_has_input').\
    drop(['dg_input','datageneration_has_input'],axis=1).drop_duplicates()
datageneration_inputupdate_df
Out[11]:
biosample_id datageneration_id datageneration_has_output
0 nmdc:bsm-11-ddfwvm63 nmdc:dgms-11-2f783x02 nmdc:dobj-11-zetxfd12
1 nmdc:bsm-11-vsk6vk28 nmdc:dgms-11-44ffdp26 nmdc:dobj-11-3mq5b296
2 nmdc:bsm-11-ntfp9891 nmdc:dgms-11-5w6rk541 nmdc:dobj-11-jj1tsc78
3 nmdc:bsm-11-ve34br43 nmdc:dgms-11-ybehtx58 nmdc:dobj-11-rstwp271
4 nmdc:bsm-11-49xqf143 nmdc:dgms-11-q7n85f05 nmdc:dobj-11-k9n15154
... ... ... ...
6428 nmdc:bsm-11-m6sxmb47 nmdc:omprc-11-gmt35466 nmdc:dobj-11-95wj8121
6429 nmdc:bsm-11-m6sxmb47 nmdc:omprc-11-jmd07w83 nmdc:dobj-11-886kqq15
6430 nmdc:bsm-11-jedtrt76 nmdc:omprc-11-6ncdmh13 nmdc:dobj-11-m8ym9597
6431 nmdc:bsm-11-jedtrt76 nmdc:omprc-11-09jbhw29 nmdc:dobj-11-vhegee30
6432 nmdc:bsm-11-jedtrt76 nmdc:omprc-11-nrxj0a61 nmdc:dobj-11-y6nv6x50

4005 rows × 3 columns

Find the biosample data objects used as input for these data generation records by matching the processing record's has_input slot to the id slot in the collection biosample_set. Create a BiosampleSearch object to do so. Query all fields in this API call by excluding the fields parameter and utilize informative columns to group biosamples into a type.

In [12]:
from nmdc_client.biosample_search import BiosampleSearch
bs_client = BiosampleSearch(api_base_url=ENV)

# get a list of the biosample ids from datageneration_inputupdate_df
result_ids = datageneration_inputupdate_df["biosample_id"].unique().tolist()
# create a list of lists of ids to query the BiosampleSearch object
chunked_list = split_list(result_ids)
biosample_dataobj = []
# loop through the chunked list of ids
for chunk in chunked_list:
    # create the filter - query the BiosampleSearch object looking for data objects where the id is in the chunk of ids from datageneration_dataobj
    filter = f'{{"id": {{"$in": {chunk}}}}}'
    # get the results
    biosample_dataobj += bs_client.get_record_by_filter(filter=filter, max_page_size=100, all_pages=True)

# clarify names
for dataobject in biosample_dataobj:
    dataobject["biosample_id"] = dataobject.pop("id")

# convert to data frame
biosample_dataobj_df = pd.DataFrame(biosample_dataobj)

biosample_dataobj_df
Out[12]:
type name description associated_studies env_broad_scale env_local_scale env_medium ecosystem ecosystem_category ecosystem_type ... slope_aspect slope_gradient drainage_class prev_land_use_meth sample_link crop_rotation tillage temp season_precpt season_temp
0 nmdc:Biosample WHONDRS_S19S_0087_SED_FIELD_M River sediment microbial communities from Dobs... [nmdc:sty-11-5tgfr349] {'type': 'nmdc:ControlledIdentifiedTermValue',... {'type': 'nmdc:ControlledIdentifiedTermValue',... {'type': 'nmdc:ControlledIdentifiedTermValue',... Environmental Aquatic Freshwater ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1 nmdc:Biosample 1000 soils - BLAN_CoreB_BTM NaN [nmdc:sty-11-28tm5d36] {'has_raw_value': 'terrestrial biome [ENVO:000... {'has_raw_value': 'area of scrub [ENVO:0100086... {'has_raw_value': 'soil [ENVO:00001998]', 'ter... Environmental Terrestrial Soil ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2 nmdc:Biosample 1000 soils - UT24_CoreB_BTM NaN [nmdc:sty-11-28tm5d36] {'has_raw_value': 'subalpine biome [ENVO:01001... {'has_raw_value': 'slope [ENVO:00002000]', 'te... {'has_raw_value': 'forest soil [ENVO:00002261]... Environmental Terrestrial Soil ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
3 nmdc:Biosample WHONDRS_S19S_0085_SED_FIELD_M River sediment microbial communities from More... [nmdc:sty-11-5tgfr349] {'type': 'nmdc:ControlledIdentifiedTermValue',... {'type': 'nmdc:ControlledIdentifiedTermValue',... {'type': 'nmdc:ControlledIdentifiedTermValue',... Environmental Aquatic Freshwater ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
4 nmdc:Biosample WHONDRS_S19S_0054_SED_FIELD_M River sediment microbial communities from Pamu... [nmdc:sty-11-5tgfr349] {'type': 'nmdc:ControlledIdentifiedTermValue',... {'type': 'nmdc:ControlledIdentifiedTermValue',... {'type': 'nmdc:ControlledIdentifiedTermValue',... Environmental Aquatic Freshwater ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
1359 nmdc:Biosample WHONDRS_S19S_0040_SW Freshwater microbial communities from Kings Cr... [nmdc:sty-11-5tgfr349] {'type': 'nmdc:ControlledIdentifiedTermValue',... {'type': 'nmdc:ControlledIdentifiedTermValue',... {'type': 'nmdc:ControlledIdentifiedTermValue',... Environmental Aquatic Freshwater ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1360 nmdc:Biosample WHONDRS_S19S_0025_SED_FIELD_D River sediment microbial communities from Prin... [nmdc:sty-11-5tgfr349] {'type': 'nmdc:ControlledIdentifiedTermValue',... {'type': 'nmdc:ControlledIdentifiedTermValue',... {'type': 'nmdc:ControlledIdentifiedTermValue',... Environmental Aquatic Freshwater ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1361 nmdc:Biosample WHONDRS_S19S_0042_SED_INC_D River sediment microbial communities from Shar... [nmdc:sty-11-5tgfr349] {'type': 'nmdc:ControlledIdentifiedTermValue',... {'type': 'nmdc:ControlledIdentifiedTermValue',... {'type': 'nmdc:ControlledIdentifiedTermValue',... Environmental Aquatic Freshwater ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1362 nmdc:Biosample WHONDRS_S19S_0085_SW Freshwater microbial communities from Mores Cr... [nmdc:sty-11-5tgfr349] {'type': 'nmdc:ControlledIdentifiedTermValue',... {'type': 'nmdc:ControlledIdentifiedTermValue',... {'type': 'nmdc:ControlledIdentifiedTermValue',... Environmental Aquatic Freshwater ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1363 nmdc:Biosample WHONDRS_S19S_0079_SW Freshwater microbial communities from Umpqua, ... [nmdc:sty-11-5tgfr349] {'type': 'nmdc:ControlledIdentifiedTermValue',... {'type': 'nmdc:ControlledIdentifiedTermValue',... {'type': 'nmdc:ControlledIdentifiedTermValue',... Environmental Aquatic Freshwater ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

1364 rows × 80 columns

Assign a general type for each sample by parsing their ENVO IDs. This was done manually by searching ENVO ID's on the ontology search website.

In [13]:
biosample_dataobj_flat=pd.json_normalize(biosample_dataobj)
biosample_dataobj_flat_df=pd.DataFrame(biosample_dataobj_flat)

biosample_dataobj_flat_df['sample_type']=""

biosample_dataobj_flat_df['env_medium.term.id'].drop_duplicates()

biosample_dataobj_flat_df.loc[biosample_dataobj_flat_df['env_medium.term.name'].str.contains('soil', na = False),'sample_type'] = 'soil'
biosample_dataobj_flat_df.loc[biosample_dataobj_flat_df['env_medium.term.name'].str.endswith('sol', na = False),'sample_type'] = 'soil'

biosample_dataobj_flat_df.loc[biosample_dataobj_flat_df['env_medium.term.id'].isin(["ENVO:00002261","ENVO:00001998","ENVO:00002259",
                                                                                    "ENVO:01001616","ENVO:00005750","ENVO:00005761",
                                                                                    "ENVO:00005760","ENVO:00005773","ENVO:00005802",
                                                                                    "ENVO:00005774"]),'sample_type'] = 'soil'
biosample_dataobj_flat_df.loc[biosample_dataobj_flat_df['env_medium.term.id'].isin(["ENVO:00002042"]),'sample_type'] = 'water'
biosample_dataobj_flat_df.loc[biosample_dataobj_flat_df['env_medium.term.id'].isin(["ENVO:00002007"]),'sample_type'] = 'sediment'
biosample_dataobj_flat_df.loc[biosample_dataobj_flat_df['env_medium.term.id'].isin(["ENVO:01000017"]),'sample_type'] = 'sand'

# Assert that all rows have an assigned sample_type
assert all(biosample_dataobj_flat_df['sample_type'] != ''), "Error: Some rows in biosample_dataobj_flat_df do not have an assigned sample_type."

#filter to desired metadata columns
biosample_dataobj_flat_df=biosample_dataobj_flat_df[['biosample_id','geo_loc_name.has_raw_value','env_medium.term.name','env_medium.term.id','sample_type']]

biosample_dataobj_flat_df
Out[13]:
biosample_id geo_loc_name.has_raw_value env_medium.term.name env_medium.term.id sample_type
0 nmdc:bsm-11-0ebbhn67 USA: Idaho, Boise sediment ENVO:00002007 sediment
1 nmdc:bsm-11-0rqs8455 USA: Virginia, Blandy Experimental Farm soil ENVO:00001998 soil
2 nmdc:bsm-11-0rsc6m85 USA: Utah, 22UT024 - High Elevation Rock Mount... forest soil ENVO:00002261 soil
3 nmdc:bsm-11-0yv80b75 USA: Idaho, Idaho City sediment ENVO:00002007 sediment
4 nmdc:bsm-11-12cg4p02 USA: Virginia, New Kent sediment ENVO:00002007 sediment
... ... ... ... ... ...
1359 nmdc:bsm-11-x85d1c03 USA: Kansas, Manhattan surface water ENVO:00002042 water
1360 nmdc:bsm-11-xjr98v04 USA: Texas, Alvord sediment ENVO:00002007 sediment
1361 nmdc:bsm-11-xsv57h38 USA: Florida, Flamingo sediment ENVO:00002007 sediment
1362 nmdc:bsm-11-xvtbj202 USA: Idaho, Idaho City surface water ENVO:00002042 water
1363 nmdc:bsm-11-zy0b5a71 USA: Oregon, Elkton surface water ENVO:00002042 water

1364 rows × 5 columns

Create final data frame of relevant metadata and NMDC schema information for each NOM processed data object¶

Create merged dataframe with results from schema traversal and metadata using the DataProcessing object created earlier.

In [14]:
#match all processed nom objects (via processed_nom_id) to analysis objects (via analysis_has_output) and expand lists has_input and has_output
processed_obj_to_analysis_df=pd.merge(processed_nom_df,analysis_dataobj_df.explode("analysis_has_output"),left_on="processed_nom_id",right_on="analysis_has_output")

#match raw data objects (via raw_id) to all_analysis_df (via analysis_has_input)
processed_obj_to_raw_df=pd.merge(raw_df,processed_obj_to_analysis_df.explode("analysis_has_input"),left_on="raw_id",right_on="analysis_has_input")

#match processed_obj_to_raw_df (via raw_id) to data generation objects (via datageneration_has_output) and expand lists has_input and has_output
processed_obj_to_datagen_df=pd.merge(processed_obj_to_raw_df,datageneration_inputupdate_df.explode("datageneration_has_output"),left_on="raw_id",right_on="datageneration_has_output")

#match biosample objects (via biosample_id) to processed_obj_to_datagen_df (via datageneration_has_input)
merged_df=pd.merge(biosample_dataobj_flat_df,processed_obj_to_datagen_df,left_on="biosample_id",right_on="biosample_id")

merged_df
Out[14]:
biosample_id geo_loc_name.has_raw_value env_medium.term.name env_medium.term.id sample_type data_object_type raw_id raw_name processed_nom_id processed_nom_md5_checksum processed_nom_url analysis_id analysis_has_input analysis_has_output datageneration_id datageneration_has_output
0 nmdc:bsm-11-0ebbhn67 USA: Idaho, Boise sediment ENVO:00002007 sediment Direct Infusion FT ICR-MS Raw Data nmdc:dobj-11-ez3mzs91 WHONDRS_S19S_R56_14Sept2020_Alder_Infuse_p15_1... nmdc:dobj-11-rs3dwk50 69b0f48f41a450cd74fdc66d14afe34e https://nmdcdemo.emsl.pnnl.gov/nom/whondrs_5tg... nmdc:wfnom-11-q181fp49.1 nmdc:dobj-11-ez3mzs91 nmdc:dobj-11-rs3dwk50 nmdc:dgms-11-wvx6vj56 nmdc:dobj-11-ez3mzs91
1 nmdc:bsm-11-0rqs8455 USA: Virginia, Blandy Experimental Farm soil ENVO:00001998 soil Direct Infusion FT ICR-MS Raw Data nmdc:dobj-11-qz0xq532 1000s_BLAN_FTMS_SPE_BTM_2_29Oct22_Mag_300SA_p0... nmdc:dobj-11-9vjyf352 99a339dfa6dbfe97a76bcfda35e443a2 https://nmdcdemo.emsl.pnnl.gov/nom/1000s_11_28... nmdc:wfnom-11-qw72wa75.2 nmdc:dobj-11-qz0xq532 nmdc:dobj-11-9vjyf352 nmdc:omprc-11-560yw232 nmdc:dobj-11-qz0xq532
2 nmdc:bsm-11-0rqs8455 USA: Virginia, Blandy Experimental Farm soil ENVO:00001998 soil Direct Infusion FT ICR-MS Raw Data nmdc:dobj-11-qz0xq532 1000s_BLAN_FTMS_SPE_BTM_2_29Oct22_Mag_300SA_p0... nmdc:dobj-11-w3sb2a43 e73f704713e5d7da08f2e4656737535d https://nmdcdemo.emsl.pnnl.gov/nom/1000soils/r... nmdc:wfnom-11-qw72wa75.1 nmdc:dobj-11-qz0xq532 nmdc:dobj-11-w3sb2a43 nmdc:omprc-11-560yw232 nmdc:dobj-11-qz0xq532
3 nmdc:bsm-11-0rqs8455 USA: Virginia, Blandy Experimental Farm soil ENVO:00001998 soil Direct Infusion FT ICR-MS Raw Data nmdc:dobj-11-dzwbj918 1000s_BLAN_FTMS_SPE_BTM_3_rr_28Oct22_Mag_300SA... nmdc:dobj-11-a0j0ky89 f3092eb26978bb03e504d92dc6f91aba https://nmdcdemo.emsl.pnnl.gov/nom/1000s_11_28... nmdc:wfnom-11-c0m79513.2 nmdc:dobj-11-dzwbj918 nmdc:dobj-11-a0j0ky89 nmdc:omprc-11-1nc9wq39 nmdc:dobj-11-dzwbj918
4 nmdc:bsm-11-0rqs8455 USA: Virginia, Blandy Experimental Farm soil ENVO:00001998 soil Direct Infusion FT ICR-MS Raw Data nmdc:dobj-11-dzwbj918 1000s_BLAN_FTMS_SPE_BTM_3_rr_28Oct22_Mag_300SA... nmdc:dobj-11-z3b7gf49 2490d7746c1c3dd7808f2715ddfe29a4 https://nmdcdemo.emsl.pnnl.gov/nom/1000soils/r... nmdc:wfnom-11-c0m79513.1 nmdc:dobj-11-dzwbj918 nmdc:dobj-11-z3b7gf49 nmdc:omprc-11-1nc9wq39 nmdc:dobj-11-dzwbj918
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
6583 nmdc:bsm-11-zy0b5a71 USA: Oregon, Elkton surface water ENVO:00002042 water Direct Infusion FT ICR-MS Raw Data nmdc:dobj-11-nm7ekr55 WHONDRS_S19S_0079_ICR_1_279_Alder_Inf_27Sept19... nmdc:dobj-11-4e5qdq44 476dce458df1a89596bfe2fcab773168 https://nmdcdemo.emsl.pnnl.gov/nom/whondrs_5tg... nmdc:wfnom-11-md2jfp35.2 nmdc:dobj-11-nm7ekr55 nmdc:dobj-11-4e5qdq44 nmdc:omprc-11-q9jdhk64 nmdc:dobj-11-nm7ekr55
6584 nmdc:bsm-11-zy0b5a71 USA: Oregon, Elkton surface water ENVO:00002042 water Direct Infusion FT ICR-MS Raw Data nmdc:dobj-11-pcngfp57 WHONDRS_S19S_0079_ICR_3_274_Alder_Inf_27Sept19... nmdc:dobj-11-8r0cww42 2b2a6df38f5c3fe0222b612afbaeb16c https://nmdcdemo.emsl.pnnl.gov/nom/grow/result... nmdc:wfnom-11-dv465r31.1 nmdc:dobj-11-pcngfp57 nmdc:dobj-11-8r0cww42 nmdc:omprc-11-6cxq5x04 nmdc:dobj-11-pcngfp57
6585 nmdc:bsm-11-zy0b5a71 USA: Oregon, Elkton surface water ENVO:00002042 water Direct Infusion FT ICR-MS Raw Data nmdc:dobj-11-pcngfp57 WHONDRS_S19S_0079_ICR_3_274_Alder_Inf_27Sept19... nmdc:dobj-11-s59rzq16 e25d11fd120263e21e491bb5fbfc2027 https://nmdcdemo.emsl.pnnl.gov/nom/whondrs_5tg... nmdc:wfnom-11-dv465r31.2 nmdc:dobj-11-pcngfp57 nmdc:dobj-11-s59rzq16 nmdc:omprc-11-6cxq5x04 nmdc:dobj-11-pcngfp57
6586 nmdc:bsm-11-zy0b5a71 USA: Oregon, Elkton surface water ENVO:00002042 water Direct Infusion FT ICR-MS Raw Data nmdc:dobj-11-06jn6573 WHONDRS_S19S_0079_ICR_2_270_Alder_Inf_27Sept19... nmdc:dobj-11-9kk8tq79 7ec32c9479f60d2a9f87fa39ecb772b9 https://nmdcdemo.emsl.pnnl.gov/nom/grow/result... nmdc:wfnom-11-bp67vr77.1 nmdc:dobj-11-06jn6573 nmdc:dobj-11-9kk8tq79 nmdc:omprc-11-v5b2a838 nmdc:dobj-11-06jn6573
6587 nmdc:bsm-11-zy0b5a71 USA: Oregon, Elkton surface water ENVO:00002042 water Direct Infusion FT ICR-MS Raw Data nmdc:dobj-11-06jn6573 WHONDRS_S19S_0079_ICR_2_270_Alder_Inf_27Sept19... nmdc:dobj-11-wym10j08 bd3024ecf50ebd23a127b24d8833183d https://nmdcdemo.emsl.pnnl.gov/nom/whondrs_5tg... nmdc:wfnom-11-bp67vr77.2 nmdc:dobj-11-06jn6573 nmdc:dobj-11-wym10j08 nmdc:omprc-11-v5b2a838 nmdc:dobj-11-06jn6573

6588 rows × 16 columns

Use the md5_checksum to check that each row/processed NOM object has an associated url that is unique, if not select one set of results for each biosample.

In [15]:
#are there any md5_checksum values that occur more than once (i.e. are associated with more than one processed nom id)
len(merged_df[merged_df.duplicated('processed_nom_md5_checksum')]['processed_nom_md5_checksum'].unique())==0
Out[15]:
True

Clean up final dataframe, removing unneeded/intermediate identifier columns from schema traversal.

In [16]:
column_list = merged_df.columns.tolist()
columns_to_keep = ["biosample_id","processed_nom_id","sample_type","processed_nom_url"]
columns_to_remove = list(set(column_list).difference(columns_to_keep))

# Drop unnecessary columns
merged_df_cleaned = merged_df.drop(columns=columns_to_remove)

# remove duplicate rows when keeping only necessary columns (should remove none)
final_df=merged_df_cleaned.drop_duplicates(keep="first").sort_values(by='processed_nom_id').reset_index(drop=True)

final_df
Out[16]:
biosample_id sample_type processed_nom_id processed_nom_url
0 nmdc:bsm-11-nq2tfm26 soil nmdc:dobj-11-002nyy42 https://nmdcdemo.emsl.pnnl.gov/nom/blanchard_1...
1 nmdc:bsm-11-cwey4y35 soil nmdc:dobj-11-003x7710 https://nmdcdemo.emsl.pnnl.gov/nom/blanchard/r...
2 nmdc:bsm-11-fhz04x18 soil nmdc:dobj-11-005z8n44 https://nmdcdemo.emsl.pnnl.gov/nom/monet_nom/p...
3 nmdc:bsm-11-689kqb07 soil nmdc:dobj-11-006w2544 https://nmdcdemo.emsl.pnnl.gov/nom/monet_nom/p...
4 nmdc:bsm-11-sk8vv550 soil nmdc:dobj-11-00dewm52 https://nmdcdemo.emsl.pnnl.gov/nom/1000soils/r...
... ... ... ... ...
6583 nmdc:bsm-13-tr7n0581 sand nmdc:dobj-13-zrp1qw41 https://nmdcdemo.emsl.pnnl.gov/nom/results/SBR...
6584 nmdc:bsm-11-hf7a3g98 soil nmdc:dobj-13-zsqpnm92 https://nmdcdemo.emsl.pnnl.gov/nom/results/Bro...
6585 nmdc:bsm-13-4pbbvj63 sand nmdc:dobj-13-zvnmsp76 https://nmdcdemo.emsl.pnnl.gov/nom/results/Ung...
6586 nmdc:bsm-11-mbnqn650 soil nmdc:dobj-13-zvzx2462 https://nmdcdemo.emsl.pnnl.gov/nom/results/Bro...
6587 nmdc:bsm-11-k05a2416 soil nmdc:dobj-13-zye5fe51 https://nmdcdemo.emsl.pnnl.gov/nom/results/Bro...

6588 rows × 4 columns

Randomly select datasets from each sample_type on which to calculate quality control statistics

In [17]:
dataset_counts = final_df[['processed_nom_id','sample_type']].drop_duplicates().value_counts('sample_type')
min_n = min(pd.DataFrame(dataset_counts)['count'])

#set sampling size to 50 or the smallest sample count, whichever value is smaller
if 50 < min_n:
    n = 50
else:
    n = min_n

#list the different types
list_type=dataset_counts.index.tolist()

#for each type, randomly sample n data sets and save them into list
random_subset=[]
for type in list_type:
    #each processed ID and sample type
    sample_type=final_df[['processed_nom_id','sample_type']].drop_duplicates()
    #filter to current sample type
    sample_type=sample_type[sample_type['sample_type']==type]
    #randomly sample n processed IDs in current sample type
    sample_type=sample_type.sample(n=n, random_state=2)
    #save
    random_subset.append(sample_type)

#resave list as dataframe
random_subset=pd.concat(random_subset).reset_index(drop=True)

#remerge rest of the data for the sampled data sets
final_df=random_subset.merge(final_df,on=['processed_nom_id','sample_type'],how="left")

final_df
Out[17]:
processed_nom_id sample_type biosample_id processed_nom_url
0 nmdc:dobj-11-x0njk546 soil nmdc:bsm-11-y7vevc12 https://nmdcdemo.emsl.pnnl.gov/nom/monet_nom/p...
1 nmdc:dobj-11-8pm0s855 soil nmdc:bsm-11-kbyn2077 https://nmdcdemo.emsl.pnnl.gov/nom/1000soils/r...
2 nmdc:dobj-11-99wwp674 soil nmdc:bsm-11-my88da58 https://nmdcdemo.emsl.pnnl.gov/nom/1000soils/r...
3 nmdc:dobj-11-gw5c0c17 soil nmdc:bsm-11-q71pns38 https://nmdcdemo.emsl.pnnl.gov/nom/brodie_11_d...
4 nmdc:dobj-11-eha0qg03 soil nmdc:bsm-11-1hbrcz12 https://nmdcdemo.emsl.pnnl.gov/nom/monet_nom/p...
... ... ... ... ...
195 nmdc:dobj-13-6vb25j63 sand nmdc:bsm-13-rrg91187 https://nmdcdemo.emsl.pnnl.gov/nom/results/SBR...
196 nmdc:dobj-13-8dr0kz67 sand nmdc:bsm-13-z9wten89 https://nmdcdemo.emsl.pnnl.gov/nom/results/Ung...
197 nmdc:dobj-11-w9nkvy37 sand nmdc:bsm-13-7tkyk513 https://nmdcdemo.emsl.pnnl.gov/nom/stegen_11_a...
198 nmdc:dobj-13-zrp1qw41 sand nmdc:bsm-13-tr7n0581 https://nmdcdemo.emsl.pnnl.gov/nom/results/SBR...
199 nmdc:dobj-13-1hqwq310 sand nmdc:bsm-13-4aw9ra87 https://nmdcdemo.emsl.pnnl.gov/nom/results/SBR...

200 rows × 4 columns

Calculate quality control statistics on the sampled processed nom results (this can take a while to run)¶

Explore what the files associated with these NOM data objects look like.

In [18]:
#example file
url=final_df.iloc[0]["processed_nom_url"]

#pull data as csv using url
response = requests.get(url)
csv_data = StringIO(response.text)
csv_df = pd.read_csv(csv_data)
csv_data.close()
csv_df
/tmp/ipykernel_2511/1840245490.py:7: DtypeWarning: Columns (17: Ion Type, 21: Molecular Formula) have mixed types. Specify dtype option on import or set low_memory=False.
  csv_df = pd.read_csv(csv_data)
Out[18]:
Index m/z Calibrated m/z Calculated m/z Peak Height Peak Area Resolving Power S/N Ion Charge m/z Error (ppm) ... C H O N S 13C 17O 18O 33S 34S
0 66 131.035589 131.035409 NaN 2.421940e+06 235.639017 1.147022e+06 13.577934 -1 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1 128 139.019559 139.019366 139.018938 2.667618e+06 279.311143 1.081148e+06 14.545404 -1 3.078565 ... 10.0 4.0 1.0 NaN NaN NaN NaN NaN NaN NaN
2 150 141.035329 141.035133 NaN 5.166798e+06 550.706413 1.278915e+06 28.668235 -1 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
3 327 159.027864 159.027639 159.027395 5.080109e+06 463.989669 1.417739e+06 28.557032 -1 1.531572 ... 10.0 8.0 NaN NaN 1.0 NaN NaN NaN NaN NaN
4 354 161.043641 161.043412 161.043045 4.592202e+06 403.772091 1.399828e+06 25.765827 -1 2.281018 ... 10.0 10.0 NaN NaN 1.0 NaN NaN NaN NaN NaN
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
19677 17942 1057.896414 1057.894609 NaN 3.930175e+06 55569.167912 6.557143e+04 21.480152 -1 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
19678 17949 1078.087851 1078.086009 NaN 3.530342e+06 20632.481160 2.091298e+05 19.306647 -1 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
19679 17950 1078.161031 1078.159188 NaN 3.820200e+06 14260.578541 2.091155e+05 21.456695 -1 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
19680 17953 1094.022352 1094.020480 NaN 3.053747e+06 11947.104094 2.060591e+05 16.649581 -1 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
19681 17954 1100.165312 1100.163428 NaN 5.770984e+06 34616.064541 2.049331e+05 31.580026 -1 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

19682 rows × 32 columns

Calculate % of peaks assigned and extract molecular formulas, H/C and O/C values from the processed NOM data sets. If there are multiple matches for a m/z peak, filter to the match with the highest confidence score.

In [19]:
errors = {}
iteration_counter = 0
mol_dict=[]
multi_peakmatch_file_counter=0
multi_peakmatch_peak_counter=0

for index, row in final_df.iterrows():

    iteration_counter += 1

    # print an update for every 50 iterations
    if iteration_counter % 50 == 0:
        print(f"Processed {iteration_counter} rows")
    
    #save data set level information
    url = row["processed_nom_url"]
    processed=row['processed_nom_id']
    sample_type=row['sample_type']

    try:
        
        # get CSV data using URL
        response = requests.get(url)
        csv_data = StringIO(response.text)
        csv_df = pd.read_csv(csv_data, low_memory=False)
        # Ensure 'Molecular Formula' is string type
        if 'Molecular Formula' in csv_df.columns:
            csv_df['Molecular Formula'] = csv_df['Molecular Formula'].astype(str)
        csv_data.close()

        #calculate assigned peak percent
        unassigned=csv_df['Molecular Formula'].isnull().sum()
        assigned=csv_df['Molecular Formula'].count()
        assigned_perc=assigned/(unassigned+assigned)

        # If there are no rows, don't include this csv, skip to the next one
        if assigned + unassigned == 0:
            print(f"No peaks found in {processed}, skipping file")
            continue
        
        # If there are some rows, and no assigned peaks, the data might fail the shape assertions and break the notebook
        # which is not informative since it would get quality filtered out anyway. Skip to the next one
        elif unassigned > 0 and assigned == 0:
            print(f"No assigned peaks found in {processed}, skipping file")
            continue

        # If there are some rows, and at least one assigned peak, assert that the important columns are correct
        # This we DO want to break if it's wrong
        elif assigned > 0:
            
            # Workflow Output Tests
            # assert that all four columns are found in the file
            assert set(['Molecular Formula','H/C','O/C','Confidence Score']).issubset(csv_df.columns), "Workflow output does not contain the required columns. Check for workflow changes"

            # assert that H/C and O/C and Confidence Score are numeric
            assert pd.api.types.is_numeric_dtype(csv_df['H/C']), "Column 'H/C' is not numeric. Check for workflow changes"
            assert pd.api.types.is_numeric_dtype(csv_df['O/C']), "Column 'O/C' is not numeric. Check for workflow changes"
            assert pd.api.types.is_numeric_dtype(csv_df['Confidence Score']), "Column 'Confidence Score' is not numeric. Check for workflow changes"
            assert pd.api.types.is_string_dtype(csv_df['Molecular Formula']), "Column 'Molecular Formula' is not a string. Check for workflow changes"
        


        #check if any peaks (m/z) have multiple matches. if so take highest scoring match

        #list of peaks
        peak_matches=csv_df["m/z"]
        #list of duplicated peaks in csv_df
        dup_peaks=peak_matches[peak_matches.duplicated()]
        multi_peakmatch_peak_counter+=len(dup_peaks)
        #if there are duplicate peaks:
        if len(dup_peaks) > 0:
            multi_peakmatch_file_counter+=1
            #group cv_df by m/z and filter to max confidence score
            idx = csv_df.groupby('m/z')['Confidence Score'].max()
            #merge back with original df (that has all columns) to filter duplicate peak entries
            csv_df=csv_df.merge(idx,on=['m/z','Confidence Score'])


        #make dictionary
        #columns to be made into lists
        mol_df=csv_df[['Molecular Formula','H/C','O/C','Confidence Score']]

        #drop unassigned peaks
        mol_df=mol_df.dropna(subset='Molecular Formula')

        #append dictionary
        mol_dict.append({'processed':processed,
                         'sample_type':sample_type,
                         'assigned_peak_count':assigned,
                         'assigned_perc':assigned_perc,
                         'mol_form':mol_df['Molecular Formula'].to_list(),
                         'H/C':mol_df['H/C'].to_list(),
                         'O/C':mol_df['O/C'].to_list(),
                         'Confidence Score':mol_df['Confidence Score'].to_list()
                        })
    
    #if error print info and raise error to stop notebook
    except AssertionError as ae:
        print(f"Assertion error occurred: {ae}")
        errors["processed_id"] = processed
        errors["url"] = url
        raise RuntimeError(f"Assertion error occurred: {ae}. Check for workflow changes. Processed ID: {processed}, URL: {url}")

    #if error print info and raise error to stop notebook
    except Exception as e:
        print(f"An error occurred: {e}")
        errors["processed_id"] = processed
        errors["url"] = url
        raise RuntimeError(f"An error occurred: {e}. Processed ID: {processed}, URL: {url}")

#turn dictionaries into dataframes
nom_summary_df=pd.DataFrame(mol_dict)

nom_summary_df
Processed 50 rows
Processed 100 rows
Processed 150 rows
Processed 200 rows
Out[19]:
processed sample_type assigned_peak_count assigned_perc mol_form H/C O/C Confidence Score
0 nmdc:dobj-11-x0njk546 soil 7263 0.369017 [C10 H4 O1, C10 H8 S1, C10 H10 S1, C8 H10 O3 S... [0.4, 0.8, 1.0, 1.25, 0.375, 0.5, 0.571429, 0.... [0.1, 0.0, 0.0, 0.375, 0.0, 0.0, 0.142857, 0.0... [0.107473, 0.392016, 0.233421, 0.547756, 0.355...
1 nmdc:dobj-11-8pm0s855 soil 1455 0.355485 [C6 H10 O3, C5 H10 O3 13C1, C6 H12 O3, C7 H6 O... [1.666667, 2.0, 2.0, 0.857143, 1.142857, 0.777... [0.5, 0.6, 0.5, 0.428571, 0.428571, 0.111111, ... [0.977837, 0.977685, 0.577251, 0.589602, 0.589...
2 nmdc:dobj-11-99wwp674 soil 2389 0.893752 [C6 H10 O3, C6 H12 O3, C7 H6 O3, C7 H8 O3, C6 ... [1.666667, 2.0, 0.857143, 1.142857, 1.333333, ... [0.5, 0.5, 0.428571, 0.428571, 0.666667, 0.428... [0.5978, 0.598365, 0.598853, 0.598778, 0.59905...
3 nmdc:dobj-11-gw5c0c17 soil 1226 0.867657 [C12 H20 O3, C13 H20 O4, C14 H22 O4, C16 H30 O... [1.666667, 1.538462, 1.571429, 1.875, 2.0, 2.0... [0.25, 0.307692, 0.285714, 0.125, 0.125, 0.125... [0.582391, 0.582796, 0.598282, 0.598859, 0.787...
4 nmdc:dobj-11-eha0qg03 soil 6171 0.569701 [C6 H12 O2, C4 H6 O4, C7 H6 O2, C6 H6 O3, C5 H... [2.0, 1.5, 0.857143, 1.0, 0.8, 1.333333, 1.4, ... [0.333333, 1.0, 0.285714, 0.5, 0.8, 0.5, 0.6, ... [0.132249, 0.127094, 0.120679, 0.125138, 0.120...
... ... ... ... ... ... ... ... ...
195 nmdc:dobj-13-6vb25j63 sand 16 0.216216 [C47 H32 O13, C52 H30 O1 S1, C22 H34 O20, C25 ... [0.680851, 0.576923, 1.545455, 1.12, 0.8, 0.63... [0.276596, 0.019231, 0.909091, 0.64, 0.228571,... [0.130945, 0.036633, 0.211705, 0.020443, 0.208...
196 nmdc:dobj-13-8dr0kz67 sand 239 0.726444 [C64 H87 O14 S1 N1, C60 H117 O15 S1 N1, C67 H1... [1.359375, 1.95, 1.940299, 1.553846, 1.561644,... [0.21875, 0.25, 0.119403, 0.153846, 0.054795, ... [0.457942, 0.067497, 0.235252, 0.01136, 0.0581...
197 nmdc:dobj-11-w9nkvy37 sand 281 0.420659 [C8 H13 O3 N1, C23 H11 O1 N1, C22 H13 O3 N1, C... [1.625, 0.478261, 0.590909, 0.44, 1.2, 0.77272... [0.375, 0.043478, 0.136364, 0.04, 0.6, 0.13636... [0.561336, 0.584967, 0.582233, 0.606409, 0.595...
198 nmdc:dobj-13-zrp1qw41 sand 10 0.108696 [C36 H40 O13 S1, C31 H38 O16, C30 H38 O16 13C1... [1.111111, 1.225806, 1.266667, 1.034483, 1.0, ... [0.361111, 0.516129, 0.533333, 0.517241, 0.321... [0.297497, 0.91575, 0.875528, 0.332147, 0.4460...
199 nmdc:dobj-13-1hqwq310 sand 49 0.441441 [C37 H38 O19, C35 H40 O19, C32 H43 O17 N1, C44... [1.027027, 1.142857, 1.34375, 0.909091, 1.3548... [0.513514, 0.542857, 0.53125, 0.159091, 0.5161... [0.12196, 0.32609, 0.298731, 0.252503, 0.50140...

200 rows × 8 columns

Perform quality control filtering of data sets using the chosen metadata information¶

Assess the number and percentage of peaks identified across files in each sample type. This will help set thresholds for data set filtering.

In [20]:
peak_count_plot=sns.FacetGrid(nom_summary_df,col="sample_type",hue="sample_type",sharex=False,sharey=False)
peak_count_plot.map(sns.histplot,'assigned_peak_count')
peak_count_plot.set_xlabels("number of identified peaks")
peak_count_plot.set_ylabels("data set count")
peak_count_plot.set_titles(col_template="{col_name}")

peak_perc_plot=sns.FacetGrid(nom_summary_df,col="sample_type",hue="sample_type",sharex=False,sharey=False)
peak_perc_plot.map(sns.histplot,'assigned_perc')
peak_perc_plot.set_xlabels("percent of peaks identified")
peak_perc_plot.set_ylabels("data set count")
peak_perc_plot.set_titles(col_template="{col_name}")
Out[20]:
<seaborn.axisgrid.FacetGrid at 0x7f6ae4f837d0>
No description has been provided for this image
No description has been provided for this image

Apply filters to obtain high quality processed NOM data sets without removing all the files from any one sample type. Based on the figures above, requiring files to have at least 250 identified peaks that account for at least 30% of their total peak count will maintain a healthy number of data sets across sample types.

In [21]:
#filter data sets according to stats on peak assignment
nom_filt=nom_summary_df[nom_summary_df['assigned_peak_count']>=250]
nom_filt=nom_filt[nom_filt['assigned_perc']>=0.25]

#expand listed columns in molecular formula df
nom_filt_expanded=nom_filt.explode(['mol_form','H/C','O/C','Confidence Score'])

#resave expanded columns as numeric
nom_filt_expanded['O/C']=pd.to_numeric(nom_filt_expanded['O/C'])
nom_filt_expanded['H/C']=pd.to_numeric(nom_filt_expanded['H/C'])
nom_filt_expanded['Confidence Score']=pd.to_numeric(nom_filt_expanded['Confidence Score'])

#metadata group column
grouping_column='sample_type'

#count number of datasets in each type
count_type=nom_filt_expanded[['processed',grouping_column]].drop_duplicates().value_counts(grouping_column)

count_type
Out[21]:
sample_type
soil        43
sediment    32
water       29
sand        23
Name: count, dtype: int64

Randomly sample a minimum number of data sets to visualize from each sample type

In [22]:
#determine sampling size based on counts above
n=min(pd.DataFrame(count_type)['count'])

#list the different types
list_type=count_type.index.tolist()

#for each type, randomly sample n data sets and save them into list
nom_sampled=[]
for type in list_type:
    #each processed ID and sample type
    nom_type=nom_filt_expanded[['processed',grouping_column]].drop_duplicates()
    #filter to current sample type
    nom_type=nom_type[nom_type[grouping_column]==type]
    #randomly sample n processed IDs in current sample type
    nom_type=nom_type.sample(n=n, random_state=2)
    #save
    nom_sampled.append(nom_type)

#resave list as dataframe
nom_sampled=pd.concat(nom_sampled)

#remerge rest of the data for the sampled data sets
nom_sampled=nom_sampled.merge(nom_filt_expanded,on=['processed',grouping_column],how="left")

nom_sampled
Out[22]:
processed sample_type assigned_peak_count assigned_perc mol_form H/C O/C Confidence Score
0 nmdc:dobj-11-gxyd6162 soil 1120 0.753194 C16 H32 O2 2.000000 0.125000 0.163122
1 nmdc:dobj-11-gxyd6162 soil 1120 0.753194 C16 H32 O3 2.000000 0.187500 0.223067
2 nmdc:dobj-11-gxyd6162 soil 1120 0.753194 C18 H36 O2 2.000000 0.111111 0.266736
3 nmdc:dobj-11-gxyd6162 soil 1120 0.753194 C17 H26 O4 1.529412 0.235294 0.297546
4 nmdc:dobj-11-gxyd6162 soil 1120 0.753194 C18 H34 O3 1.888889 0.166667 0.278464
... ... ... ... ... ... ... ... ...
280114 nmdc:dobj-13-95ygfg27 sand 310 0.873239 C15 H30 O2 2.000000 0.133333 0.597332
280115 nmdc:dobj-13-95ygfg27 sand 310 0.873239 C14 H10 O4 0.714286 0.285714 0.598825
280116 nmdc:dobj-13-95ygfg27 sand 310 0.873239 C15 H28 O2 1.866667 0.133333 0.534896
280117 nmdc:dobj-13-95ygfg27 sand 310 0.873239 C8 H16 O6 S1 2.000000 0.750000 0.078921
280118 nmdc:dobj-13-95ygfg27 sand 310 0.873239 C7 H12 O6 S1 1.714286 0.857143 0.058991

280119 rows × 8 columns

Filter to high confidence peaks (score greater than 0.3) and high frequency molecular formulas (present in more than 5 data sets). This will leave us with the most informative data.

In [23]:
#histogram of confidence scores for randomly selected samples
nom_sampled.hist("Confidence Score",bins=np.arange(0,1,0.1))
plt.title('Confidence Scores from Sampled Data Sets')
plt.xlabel("Confidence Score")
plt.xticks(np.arange(0,1,0.1))
plt.ylabel("Frequency")
plt.show()

#peak filtering by confidence score
conf_filt=nom_sampled[nom_sampled['Confidence Score']>=0.3]

#count for each molecular formula
mol_counts=conf_filt.value_counts('mol_form').to_frame().reset_index()

#histogram of molecular formula counts
mol_counts.hist("count",bins=np.arange(0,50,5))
plt.locator_params(axis='x')
plt.title('Molecular Formula Counts Across Sampled Data Sets')
plt.xlabel("Number of Occurences Across Data Sets")
plt.xticks(np.arange(0,50,5))
plt.ylabel("Number of Molecular Formula")
plt.show()

#based on this histogram, filter to formulas in more than 5 data sets
mol_counts=mol_counts[mol_counts['count']>=5]
mol_filter=mol_counts.merge(conf_filt,on=['mol_form'],how="left")
No description has been provided for this image
No description has been provided for this image

Assess patterns in the molecular formulas from different sample types¶

Create a clustermap of the processed NOM data sets (x axis), indicating the presence (black) or absence (white) of molecular formulas (y axis). The color bar will indicate sample type and help visualize the molecular similarity of data sets both within and between sample types.

In [24]:
#sample type colors

#set colors for each sample type
type_col=pd.DataFrame({grouping_column:mol_filter[grouping_column].unique(),'color':['olivedrab','blue','#8B4513','#B8860B']})

#setup color legend for sample type
type_col_dict = dict(zip(type_col[grouping_column].unique(), ['olivedrab','blue','#8B4513','#B8860B']))
handles = [Patch(facecolor=type_col_dict[name]) for name in type_col_dict]

#map graph colors based on sample type to processed IDs
sample_type=mol_filter[[grouping_column,'processed']].drop_duplicates()
sample_type_col=sample_type.merge(type_col,how='left',on=grouping_column).set_index('processed').drop(grouping_column,axis=1).rename(columns={'color':grouping_column})

#presence/absence

#set colors for presence/absence as cmap
colors=['white','black']
custom_palette = sns.color_palette(colors)
custom_cmap = sns.color_palette(custom_palette, as_cmap=True)

#add column indicating presence in that processed nom id (1 is present)
mol_filter['presence']=1

#create presence/absence matrix. replace NA with 0 (0 is absent)
formula_matrix=mol_filter[['mol_form','processed','presence']].pivot_table('presence', index='mol_form', columns='processed').fillna(0).astype(int)

#heatmap (1 is present, zero is absent)
g=sns.clustermap(data=formula_matrix,col_colors=sample_type_col,tree_kws={"linewidths": 0.},xticklabels=False,yticklabels=False,cmap=custom_cmap)
g.figure.suptitle("Presence of Molecular Formulas Across NOM Data Sets")
g.ax_heatmap.set_xlabel("Processed NOM Data Sets")
g.ax_heatmap.set_ylabel("Molecular Formulas")

#adjust plot and legend locations
g.figure.subplots_adjust(top=1.15,right=0.8)
g.ax_cbar.set_position((0.85, 0.45, .05, .05)) #x axis,y axis, width, height

#adjust cbar legend to indicate presence/absence
g.ax_cbar.set_yticks([0.25,0.75])
g.ax_cbar.set_yticklabels(["absent","present"])

#add sample type legend
plt.legend(handles, type_col_dict, title=None,
           bbox_to_anchor=(0.95, 1.05), bbox_transform=plt.gcf().transFigure)
Out[24]:
<matplotlib.legend.Legend at 0x7f6ae3293c90>
No description has been provided for this image

Create Van Krevelen diagrams to visually assess the atomic composition of each sample type. Van Krevelen diagrams plot the hydrogen to carbon ratio against the oxygen to carbon ratio, historically to assess petroleum samples.

In [25]:
# the same molecular formula will have the same H/C and O/C value in every data set, so dots are only unique per sample type
vankrev_data=mol_filter[[grouping_column,'mol_form','H/C','O/C']].drop_duplicates()

#make van krevlen plot
g=sns.FacetGrid(vankrev_data,col=grouping_column,hue=grouping_column,palette=type_col_dict)
g.map(sns.scatterplot,'O/C','H/C',s=1.5)
g.set_titles(col_template="{col_name}")
g.figure.suptitle("Van Krevelen Plots By General Sample Type")
g.figure.subplots_adjust(top=0.8)
No description has been provided for this image

Create marginal density plot to assess how molecular formulas unique to each sample type compare to those shared by all four sample types.

In [26]:
#count the number of sample types in which each molecular formula is found
density_counts=vankrev_data['mol_form'].value_counts()

#map counts back to H/C and O/C data
vankrev_data['common_to'] = vankrev_data['mol_form'].map(density_counts)

#filter molecular formual present in either all four sample types or in only one
vankrev_data=vankrev_data[vankrev_data['common_to'].isin([1,4])]

#reformat so sample type is 'all' when molecular formula was in all
vankrev_data.loc[vankrev_data['common_to']==4,'sample_type']='all types'

#add 'all' to sample type color dictionary
type_col_dict.update({'all types':'black'})

#make marginal density plot
sns.jointplot(data=vankrev_data, x="O/C", y="H/C", kind="scatter", hue=grouping_column,palette=type_col_dict,s=5,alpha=0.5)
plt.legend(markerscale=3,title="unique to")
plt.suptitle("Marginal Density Plot of Molecular Formulas by Sample Type",y=1.02)
plt.show()
No description has been provided for this image