|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# MIT License |
| 3 | +# |
| 4 | +# Copyright 2024 Broad Institute |
| 5 | +# |
| 6 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 | +# of this software and associated documentation files (the "Software"), to deal |
| 8 | +# in the Software without restriction, including without limitation the rights |
| 9 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 | +# copies of the Software, and to permit persons to whom the Software is |
| 11 | +# furnished to do so, subject to the following conditions: |
| 12 | +# |
| 13 | +# The above copyright notice and this permission notice shall be included in all |
| 14 | +# copies or substantial portions of the Software. |
| 15 | +# |
| 16 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 22 | +# SOFTWARE. |
| 23 | +""" |
| 24 | +Load a primary tab-separated file, and zero or more secondary tab-separated files, each with join columns |
| 25 | +specified. Each secondary file is left outer joined to the primary file on the join column. |
| 26 | +
|
| 27 | +The values in the join column of a join file must be unique. |
| 28 | +
|
| 29 | +If there is a collision between the column names in the primary and secondary files, the column in the primary |
| 30 | +file is used. If there is a collision between the column names in the secondary files, the column in the earlier |
| 31 | +file is used. |
| 32 | +
|
| 33 | +In addition, there may be zero or more (column name, column value) pairs that are set on each line unconditionally. |
| 34 | +
|
| 35 | +Each resulting row is passed through zero more filters, which can apply a min or a max threshold to a column, |
| 36 | +have a list of values to match against, or have a list of values to exclude, which may be specified on the command |
| 37 | +line or in a file. |
| 38 | +""" |
| 39 | + |
| 40 | +import argparse |
| 41 | +import sys |
| 42 | +import pandas as pd |
| 43 | + |
| 44 | +DELETEME_COLUMN_SUFFIX = '_deleteme' |
| 45 | + |
| 46 | +def try_convert_string_to_number(s): |
| 47 | + int_val = None |
| 48 | + float_val = None |
| 49 | + try: |
| 50 | + int_val = int(s) |
| 51 | + except ValueError: |
| 52 | + pass |
| 53 | + try: |
| 54 | + float_val = float(s) |
| 55 | + except ValueError: |
| 56 | + pass |
| 57 | + if int_val is None and float_val is None: |
| 58 | + return s |
| 59 | + if int_val is None and float_val is not None: |
| 60 | + return float_val |
| 61 | + if float_val is None and int_val is not None: |
| 62 | + return int_val |
| 63 | + if int_val == float_val: |
| 64 | + return int_val |
| 65 | + return float_val |
| 66 | + |
| 67 | +def load_values_file(file): |
| 68 | + return pd.read_csv(file, sep='\t', header=None).iloc[0] |
| 69 | + |
| 70 | +def add_subparser(subparsers): |
| 71 | + parser = subparsers.add_parser("join_and_filter_tsv", description=__doc__) |
| 72 | + parser.add_argument("--input", "-i", type=argparse.FileType('r'), |
| 73 | + help="Primary tab-separated file to join. Default: %(default)s", default=sys.stdin) |
| 74 | + parser.add_argument("--output", "-o", type=argparse.FileType('w'), |
| 75 | + help="Output file. Default: %(default)s", default=sys.stdout) |
| 76 | + parser.add_argument("--join", "-j", nargs=3, action='append', default=[], |
| 77 | + metavar=('SECONDARY_FILE', 'INPUT_COL', 'JOIN_COL'), |
| 78 | + help="Secondary tab-separated file to join, and the columns in the primary input " |
| 79 | + "and join file to join on. May be specified multiple times.") |
| 80 | + parser.add_argument("--set", "-s", nargs=2, action='append', default=[], metavar=('COLUMN', 'VALUE'), |
| 81 | + help="Set a column to a constant value. May be specified multiple times.") |
| 82 | + parser.add_argument("--min", nargs=2, action='append', default=[], metavar=('COLUMN', 'VALUE'), |
| 83 | + help="Filter out rows where COLUMN is less than VALUE. May be specified multiple times.") |
| 84 | + parser.add_argument("--max", nargs=2, action='append', default=[], metavar=('COLUMN', 'VALUE'), |
| 85 | + help="Filter out rows where COLUMN is greater than VALUE. May be specified multiple times.") |
| 86 | + parser.add_argument("--include-file", nargs=2, action='append', default=[], metavar=('COLUMN', 'FILE'), |
| 87 | + help="Filter out rows where COLUMN is not in FILE. May be specified multiple times.") |
| 88 | + parser.add_argument("--exclude-file", nargs=2, action='append', default=[], metavar=('COLUMN', 'FILE'), |
| 89 | + help="Filter out rows where COLUMN is in FILE. May be specified multiple times.") |
| 90 | + parser.add_argument("--include", nargs='+', action='append', default=[], metavar=('COLUMN', 'VALUE'), |
| 91 | + help="Filter out rows where COLUMN is not one of the given VALUEs. May be specified multiple times.") |
| 92 | + parser.add_argument("--exclude", nargs='+', action='append', default=[], metavar=('COLUMN', 'VALUE'), |
| 93 | + help="Filter out rows where COLUMN is one of the given VALUEs. May be specified multiple times.") |
| 94 | + |
| 95 | +def main(options): |
| 96 | + # load the primary file |
| 97 | + primary = pd.read_csv(options.input, sep='\t') |
| 98 | + options.input.close() |
| 99 | + # load each secondary file, and join it to the primary file, dropping secondary columns that are already in the primary |
| 100 | + for join_file, input_col, join_col in options.join: |
| 101 | + join_col_in_left = join_col in primary.columns |
| 102 | + secondary = pd.read_csv(join_file, sep='\t') |
| 103 | + primary = primary.merge(secondary, how='left', left_on=input_col, right_on=join_col, |
| 104 | + suffixes=(None, DELETEME_COLUMN_SUFFIX)) |
| 105 | + if not join_col_in_left: |
| 106 | + # drop the join column from the merged data frame |
| 107 | + primary.drop(join_col, axis=1, inplace=True) |
| 108 | + # drop the secondary columns that are already in the primary |
| 109 | + for col in primary.columns: |
| 110 | + if col.endswith(DELETEME_COLUMN_SUFFIX): |
| 111 | + primary.drop(col, axis=1, inplace=True) |
| 112 | + # set columns to constant values |
| 113 | + for column, value in options.set: |
| 114 | + primary[column] = try_convert_string_to_number(value) |
| 115 | + # filter out rows based on column values |
| 116 | + for column, value in options.min: |
| 117 | + primary = primary[primary[column] >= try_convert_string_to_number(value)] |
| 118 | + for column, value in options.max: |
| 119 | + primary = primary[primary[column] <= try_convert_string_to_number(value)] |
| 120 | + for column, file in options.include_file: |
| 121 | + include_values = load_values_file(file) |
| 122 | + primary = primary[primary[column].isin(include_values)] |
| 123 | + for column, file in options.exclude_file: |
| 124 | + exclude_values = load_values_file(file) |
| 125 | + primary = primary[~primary[column].isin(exclude_values)] |
| 126 | + for includes in options.include: |
| 127 | + column = includes[0] |
| 128 | + values = includes[1:] |
| 129 | + values = [try_convert_string_to_number(value) for value in values] |
| 130 | + primary = primary[primary[column].isin(values)] |
| 131 | + for excludes in options.exclude: |
| 132 | + column = excludes[0] |
| 133 | + values = excludes[1:] |
| 134 | + values = [try_convert_string_to_number(value) for value in values] |
| 135 | + primary = primary[~primary[column].isin(values)] |
| 136 | + # write the output |
| 137 | + primary.to_csv(options.output, sep='\t', index=False) |
| 138 | + options.output.close() |
| 139 | + return 0 |
| 140 | + |
| 141 | + |
0 commit comments