-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathload_rsem_results_into_bq.py
More file actions
209 lines (178 loc) · 7.36 KB
/
Copy pathload_rsem_results_into_bq.py
File metadata and controls
209 lines (178 loc) · 7.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/usr/bin/env python
import argparse
import pandas as pd
import pytz
from decimal import Decimal
from google.cloud import bigquery
from google.cloud.bigquery import LoadJob
from typing import Optional
def load_gene_results(
results_path: str,
table_id: str,
sample_id: str,
verbose: bool = False
) -> LoadJob:
"""
Load gene-level expression results into BigQuery table.
Args:
results_path: Path to the tab-separated gene results file containing columns:
gene_id, transcript_id(s), length, effective_length, expected_count, TPM, FPKM
table_id: Fully-qualified BigQuery table ID in format 'project.dataset.table'
sample_id: Unique identifier for the sample being loaded
verbose: If True, prints additional debugging information during execution
Returns:
LoadJob: Completed BigQuery load job containing operation results
Raises:
google.api_core.exceptions.GoogleAPIError: If the BigQuery load operation fails
pandas.errors.EmptyDataError: If the results file is empty
FileNotFoundError: If the results file does not exist
"""
if verbose is True:
print("results_path:", results_path)
print("table_id:", table_id)
print("sample_id:", sample_id)
# determine results df
decimal_columns = ["length", "effective_length", "expected_count", "TPM", "FPKM"]
results_df = pd.read_csv(results_path, sep='\t', converters=dict.fromkeys(decimal_columns, Decimal))
results_df.insert(0, 'sample_id', sample_id)
results_df.rename(columns={'transcript_id(s)': 'transcript_ids'}, inplace=True)
if verbose is True:
print("results_df.shape:", results_df.shape)
# create BigQuery client
client = bigquery.Client()
# define load job config
job_config = bigquery.LoadJobConfig(
schema=[
bigquery.SchemaField("sample_id", bigquery.enums.SqlTypeNames.STRING),
bigquery.SchemaField("gene_id", bigquery.enums.SqlTypeNames.STRING),
bigquery.SchemaField("transcript_ids", bigquery.enums.SqlTypeNames.STRING),
bigquery.SchemaField("length", bigquery.enums.SqlTypeNames.DECIMAL),
bigquery.SchemaField("effective_length", bigquery.enums.SqlTypeNames.DECIMAL),
bigquery.SchemaField("expected_count", bigquery.enums.SqlTypeNames.DECIMAL),
bigquery.SchemaField("TPM", bigquery.enums.SqlTypeNames.DECIMAL),
bigquery.SchemaField("FPKM", bigquery.enums.SqlTypeNames.DECIMAL),
],
clustering_fields=["sample_id"],
write_disposition="WRITE_APPEND",
)
# execute job
job = client.load_table_from_dataframe(
results_df, table_id, job_config=job_config
)
result = job.result()
if not result.error_result:
print('Job "{}" loaded without error. Current status is {}.'.format(result.job_id, result.state))
else:
print('Error occurred while loading job "{}":\n{}\nCurrent status is {}.'.format(result.job_id, result.error_result, result.state))
def load_isoform_results(
results_path: str,
table_id: str,
sample_id: str,
verbose: bool = False
) -> LoadJob:
"""
Load transcript/isoform-level expression results into BigQuery table.
Args:
results_path: Path to the tab-separated isoform results file containing columns:
transcript_id, gene_id, length, effective_length, expected_count, TPM, FPKM, IsoPct
table_id: Fully-qualified BigQuery table ID in format 'project.dataset.table'
sample_id: Unique identifier for the sample being loaded
verbose: If True, prints additional debugging information during execution
Returns:
LoadJob: Completed BigQuery load job containing operation results
Raises:
google.api_core.exceptions.GoogleAPIError: If the BigQuery load operation fails
pandas.errors.EmptyDataError: If the results file is empty
FileNotFoundError: If the results file does not exist
"""
if verbose is True:
print("results_path:", results_path)
print("table_id:", table_id)
print("sample_id:", sample_id)
# determine results df
decimal_columns = ["length", "effective_length", "expected_count", "TPM", "FPKM", "IsoPct"]
results_df = pd.read_csv(results_path, sep='\t', converters=dict.fromkeys(decimal_columns, Decimal))
results_df.insert(0, 'sample_id', sample_id)
if verbose is True:
print("results_df.shape:", results_df.shape)
# create BigQuery client
client = bigquery.Client()
# define load job config
job_config = bigquery.LoadJobConfig(
schema=[
bigquery.SchemaField("sample_id", bigquery.enums.SqlTypeNames.STRING),
bigquery.SchemaField("transcript_id", bigquery.enums.SqlTypeNames.STRING),
bigquery.SchemaField("gene_id", bigquery.enums.SqlTypeNames.STRING),
bigquery.SchemaField("length", bigquery.enums.SqlTypeNames.DECIMAL),
bigquery.SchemaField("effective_length", bigquery.enums.SqlTypeNames.DECIMAL),
bigquery.SchemaField("expected_count", bigquery.enums.SqlTypeNames.DECIMAL),
bigquery.SchemaField("TPM", bigquery.enums.SqlTypeNames.DECIMAL),
bigquery.SchemaField("FPKM", bigquery.enums.SqlTypeNames.DECIMAL),
bigquery.SchemaField("IsoPct", bigquery.enums.SqlTypeNames.DECIMAL),
],
clustering_fields=["sample_id"],
write_disposition="WRITE_APPEND",
)
# execute job
job = client.load_table_from_dataframe(
results_df, table_id, job_config=job_config
)
result = job.result()
if not result.error_result:
print('Job "{}" loaded without error. Current status is {}.'.format(result.job_id, result.state))
else:
print('Error occurred while loading job "{}":\n{}\nCurrent status is {}.'.format(result.job_id, result.error_result, result.state))
if __name__ == "__main__":
# establish argument parser
parser = argparse.ArgumentParser()
# results_type flag
parser.add_argument(
"--results_type",
required=True,
choices={"gene", "isoform"},
help="Type of results being uploaded"
)
# results_path flag
parser.add_argument(
"--results_path",
required=True,
help="Path where results file is located"
)
# table_id flag
parser.add_argument(
"--table_id",
required=True,
help="BQ Table ID where results will be loaded"
)
# sample_id flag
parser.add_argument(
"--sample_id",
required=True,
help="Sample ID corresponding to the results"
)
# verbose flag
parser.add_argument(
"--verbose",
required=False,
type=bool,
default=False,
help="Verbosity"
)
# determine input arguments
args = parser.parse_args()
if args.results_type.lower() == "gene":
load_gene_results(
results_path=args.results_path,
table_id=args.table_id,
sample_id=args.sample_id,
verbose=args.verbose
)
elif args.results_type.lower() == "isoform":
load_isoform_results(
results_path=args.results_path,
table_id=args.table_id,
sample_id=args.sample_id,
verbose=args.verbose
)
else:
print('Matching load function for results type "{}" not found.'.format(args.results_type))