Skip to content

Commit 3e72e87

Browse files
authored
Merge pull request #11 from sbslee/1.7.0-dev
1.7.0 dev
2 parents 309dd57 + 5575e1a commit 3e72e87

14 files changed

Lines changed: 177 additions & 54 deletions

CHANGELOG.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,17 @@
11
# Changelog
22

3+
## 1.7.0
4+
5+
* Added a new command called `count-reads` which counts the number of sequence reads from FASTQ.
6+
* Updated the `summarize` command.
7+
* Updated the following methods:
8+
* `taxa_abundance_box_plot()`
9+
* `taxa_abundance_bar_plot()`
10+
* `distance_matrix_plot()`
11+
* `ordinate()`
12+
* `barplot()`
13+
* See [#10](https://github.com/sbslee/dokdo/issues/10) for more details.
14+
315
## 1.6.0
416

517
* Added a new method called `pname()` which returns a prettified taxon name.

dokdo/__main__.py

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,8 @@ def main():
172172
"the following semantic types: "
173173
"FeatureTable[Frequency], "
174174
"FeatureTable[RelativeFrequency], "
175-
"FeatureData[Sequence], FeatureData[AlignedSequence].")
175+
"FeatureData[Sequence], FeatureData[AlignedSequence], "
176+
"FeatureData[Taxonomy], DistanceMatrix.")
176177
)
177178

178179
summarize_parser._optionals.title = "Arguments"
@@ -288,6 +289,43 @@ def main():
288289
help=help_msg
289290
)
290291

292+
count_reads_parser = subparsers.add_parser(
293+
"count-reads",
294+
add_help=False,
295+
help="Count the number of sequence reads from FASTQ.",
296+
description=("Count the number of sequence reads from FASTQ. "
297+
"This command outputs two columns corresponding "
298+
"to the file name and read count, respectively.")
299+
)
300+
301+
count_reads_parser._optionals.title = "Arguments"
302+
303+
count_reads_parser.add_argument(
304+
"-i",
305+
"--fastq-path",
306+
metavar="PATH",
307+
required=True,
308+
help=("Path to the input FASTQ file or to the input "
309+
"directory containing FASTQ files. [required]")
310+
)
311+
312+
count_reads_parser.add_argument(
313+
"-d",
314+
"--delimiter",
315+
metavar="TEXT",
316+
default="\t",
317+
help=("Delimiter used to separate the file name and read "
318+
"count. [default: '\\t']")
319+
)
320+
321+
count_reads_parser.add_argument(
322+
"-h",
323+
"--help",
324+
action="help",
325+
default=argparse.SUPPRESS,
326+
help=help_msg
327+
)
328+
291329
args = parser.parse_args()
292330
command = args.command
293331
delattr(args, "command")

dokdo/api/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from .num2sig import num2sig
55
from .wilcoxon import wilcoxon
66
from .mannwhitneyu import mannwhitneyu
7+
from .count_reads_one_file import count_reads_one_file
78

89
from .read_quality_plot import read_quality_plot
910
from .denoising_stats_plot import denoising_stats_plot
@@ -32,4 +33,4 @@
3233
'beta_scree_plot', 'beta_parallel_plot', 'distance_matrix_plot',
3334
'taxa_abundance_bar_plot', 'taxa_abundance_box_plot',
3435
'ancom_volcano_plot', 'addsig', 'regplot', 'addbiplot',
35-
'barplot', 'ordinate', 'pname', 'get_mf']
36+
'barplot', 'ordinate', 'pname', 'get_mf', 'count_reads_one_file']

dokdo/api/barplot.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,9 +151,9 @@ def barplot(barplot_file,
151151

152152
taxa_abundance_bar_plot(barplot_file,
153153
ax=axbig,
154+
legend_short=True,
154155
artist_kwargs={'legend_only': True,
155156
'legend_loc': 'center left',
156-
'legend_short': True,
157157
**_artist_kwargs},
158158
**plot_kwargs)
159159

dokdo/api/common.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from qiime2 import Artifact
2424
from qiime2 import Metadata
2525
from qiime2 import Visualization
26-
26+
import dokdo
2727

2828

2929

@@ -187,7 +187,6 @@ def _artist(ax,
187187
legend_loc='best',
188188
legend_ncol=1,
189189
legend_labels=None,
190-
legend_short=False,
191190
remove_duplicates=False,
192191
legend_only=False,
193192
legend_fontsize=None,
@@ -392,9 +391,6 @@ def _artist(ax,
392391
# Control the figure legend.
393392
h, l = ax.get_legend_handles_labels()
394393

395-
if legend_short:
396-
l = [_pretty_taxa(x) for x in l]
397-
398394
if legend_labels:
399395
a = len(legend_labels)
400396
b = len(l)

dokdo/api/count_reads_one_file.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import gzip
2+
3+
def count_reads_one_file(fastq_file):
4+
"""Count the number of sequence reads from a single FASTQ file.
5+
6+
Parameters
7+
----------
8+
fastq_file : str
9+
Path to the FASTQ file.
10+
11+
Returns
12+
-------
13+
int
14+
Number of sequence reads in the FASTQ file.
15+
"""
16+
n = 0
17+
with gzip.open(fastq_file, 'rb') as f:
18+
for line in f:
19+
n += 1
20+
return int(n / 4)

dokdo/api/distance_matrix_plot.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,22 @@
33
import pandas as pd
44
import skbio as sb
55
import matplotlib.pyplot as plt
6+
from qiime2 import Artifact
67

78
def distance_matrix_plot(distance_matrix,
89
bins=100,
910
pairs=None,
1011
ax=None,
1112
figsize=None,
13+
density=False,
1214
artist_kwargs=None):
1315
"""Create a histogram from a distance matrix.
1416
1517
Parameters
1618
----------
1719
distance_matrix : str or qiime2.Artifact
18-
Artifact file or object from the q2-diversity-lib plugin.
20+
Artifact file or object with the semantic type
21+
`DistanceMatrix`.
1922
bins : int, optional
2023
Number of bins to be displayed.
2124
pairs : list, optional
@@ -24,31 +27,28 @@ def distance_matrix_plot(distance_matrix,
2427
Axes object to draw the plot onto, otherwise uses the current Axes.
2528
figsize : tuple, optional
2629
Width, height in inches. Format: (float, float).
30+
density : bool, default: False
31+
If True, draw and return a probability density.
2732
artist_kwargs : dict, optional
2833
Keyword arguments passed down to the _artist() method.
2934
3035
Returns
3136
-------
3237
matplotlib.axes.Axes
3338
Axes object with the plot drawn onto it.
34-
35-
Notes
36-
-----
37-
Example usage of the q2-diversity-lib plugin:
38-
CLI -> qiime diversity-lib jaccard [OPTIONS]
39-
API -> from qiime2.plugins.diversity_lib.methods import jaccard
4039
"""
41-
with tempfile.TemporaryDirectory() as t:
42-
_parse_input(distance_matrix, t)
43-
df = pd.read_table(f'{t}/distance-matrix.tsv', index_col=0)
40+
if isinstance(distance_matrix, str):
41+
_distance_matrix = Artifact.load(distance_matrix)
42+
else:
43+
_distance_matrix = distance_matrix
4444

45-
dist = sb.stats.distance.DistanceMatrix(df, ids=df.columns)
45+
dist = _distance_matrix.view(sb.DistanceMatrix)
4646
cdist = dist.condensed_form()
4747

4848
if ax is None:
4949
fig, ax = plt.subplots(figsize=figsize)
5050

51-
ax.hist(cdist, bins=bins)
51+
ax.hist(cdist, bins=bins, density=density)
5252

5353
# https://stackoverflow.com/a/36867493/7481899
5454
def square_to_condensed(i, j, n):

dokdo/api/ordinate.py

Lines changed: 12 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,8 @@
55
from qiime2.plugins import diversity
66
import pandas as pd
77

8-
def ordinate(table,
9-
metadata=None,
10-
where=None,
11-
metric='jaccard',
12-
sampling_depth=-1,
13-
phylogeny=None,
14-
number_of_dimensions=None,
15-
biplot=False):
8+
def ordinate(table, metadata=None, metric='jaccard', sampling_depth=-1,
9+
phylogeny=None, number_of_dimensions=None, biplot=False):
1610
"""Perform ordination using principal coordinate analysis (PCoA).
1711
1812
This method wraps multiple QIIME 2 methods to perform ordination and
@@ -22,17 +16,16 @@ def ordinate(table,
2216
rarefying of the feature table (if requested), computes distance matrix,
2317
and then runs PCoA.
2418
25-
By default, the method returns PCoAResults. For creating a biplot, make
26-
sure to use `biplot=True` which returns PCoAResults % Properties('biplot').
19+
By default, the method returns PCoAResults. For creating a biplot,
20+
use `biplot=True` which returns PCoAResults % Properties('biplot').
2721
2822
Parameters
2923
----------
3024
table : str or qiime2.Artifact
3125
Artifact file or object corresponding to FeatureTable[Frequency].
3226
metadata : str or qiime2.Metadata, optional
33-
Metadata file or object.
34-
where : str, optional
35-
SQLite WHERE clause specifying sample metadata criteria.
27+
Metadata file or object. All samples in 'metadata' that are also in
28+
the feature table will be retained.
3629
metric : str, default: 'jaccard'
3730
Metric used for distance matrix computation ('jaccard',
3831
'bray_curtis', 'unweighted_unifrac', or 'weighted_unifrac').
@@ -71,21 +64,14 @@ def ordinate(table,
7164
else:
7265
raise TypeError(f"Incorrect feature table type: {type(table)}")
7366

74-
# Perform sample filtration.
75-
if where:
76-
if metadata is None:
77-
m = "To use 'where' argument, you must provide metadata"
78-
raise ValueError(m)
79-
elif isinstance(metadata, str):
80-
_metadata = Metadata.load(metadata)
81-
elif isinstance(metadata, qiime2.Metadata):
67+
# If metadata is provided, perform sample filtration.
68+
if metadata is not None:
69+
if isinstance(metadata, Metadata):
8270
_metadata = metadata
8371
else:
84-
raise TypeError(f"Incorrect metadata type: {type(metadata)}")
85-
86-
filter_result = feature_table.methods.filter_samples(
87-
table=table, metadata=_metadata, where=where)
88-
_table = filter_result.filtered_table
72+
_metadata = Metadata.load(metadata)
73+
_table = feature_table.methods.filter_samples(
74+
table=table, metadata=_metadata).filtered_table
8975
else:
9076
_table = table
9177

dokdo/api/taxa_abundance_bar_plot.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ def taxa_abundance_bar_plot(taxa,
2828
sort_by_mean3=True,
2929
show_others=True,
3030
cmap_name='Accent',
31+
legend_short=False,
3132
artist_kwargs=None):
3233
"""Create a taxa abundance plot.
3334
@@ -92,6 +93,8 @@ def taxa_abundance_bar_plot(taxa,
9293
Include the 'Others' category.
9394
cmap_name : str, default: 'Accent'
9495
Name of the colormap passed to `matplotlib.cm.get_cmap()`.
96+
legend_short : bool, default: False
97+
If true, only display the smallest taxa rank in the legend.
9598
artist_kwargs : dict, optional
9699
Keyword arguments passed down to the _artist() method.
97100
@@ -206,17 +209,20 @@ def taxa_abundance_bar_plot(taxa,
206209

207210
df = df * 100
208211

212+
# If provided, output the dataframe as a .csv file.
213+
if csv_file is not None:
214+
df.to_csv(csv_file)
215+
216+
if legend_short:
217+
df.columns = [dokdo.pname(x) for x in df.columns]
218+
209219
df.plot.bar(stacked=True,
210220
legend=False,
211221
ax=ax,
212222
width=width,
213223
color=c,
214224
linewidth=0)
215225

216-
# If provided, output the dataframe as a .csv file.
217-
if csv_file is not None:
218-
df.to_csv(csv_file)
219-
220226
if label_columns is not None:
221227
f = lambda row: ' : '.join(row.values.astype(str))
222228
xticklabels = mf[label_columns].apply(f, axis=1).tolist()

dokdo/api/taxa_abundance_box_plot.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import tempfile
2-
from .common import (_parse_input, _artist, _pretty_taxa,
2+
from .common import (_parse_input, _artist,
33
_get_mf_cols, _filter_samples, _sort_by_mean, _get_others_col)
44
import dokdo
55
import pandas as pd
@@ -229,7 +229,7 @@ def taxa_abundance_box_plot(taxa,
229229
df3.to_csv(csv_file)
230230

231231
if brief_xlabels:
232-
xticklabels = [_pretty_taxa(x) for x in ax.get_xticklabels()]
232+
xticklabels = [dokdo.pname(x.get_text()) for x in ax.get_xticklabels()]
233233
else:
234234
xticklabels = None
235235

0 commit comments

Comments
 (0)