Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 22 additions & 22 deletions pairtools/cli/select.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,10 +182,15 @@ def select_py(
# Modify the header:
header = headerops.append_new_pg(header, ID=UTIL_NAME, PN=UTIL_NAME)

# Extract original input column names before any header modification so
# condition evaluation always indexes the unmodified input rows:
input_columns = headerops.extract_column_names(header)
column_names = input_columns if len(input_columns) > 0 else pairsam_format.COLUMNS

# Filter out unwanted columns:
column_scheme = None
if remove_columns:
input_columns = headerops.extract_column_names(header)
remove_columns = remove_columns.split(",")
remove_columns = list(dict.fromkeys(remove_columns.split(",")))
for col in remove_columns:
if col in pairsam_format.COLUMNS_PAIRS:
warnings.warn(
Expand All @@ -203,6 +208,9 @@ def select_py(
)
else:
header = headerops.set_columns(header, updated_columns)
column_scheme = [
idx for idx, col in enumerate(input_columns) if col not in remove_columns
]

# Update the chromosomes:
new_chroms = None
Expand All @@ -215,14 +223,6 @@ def select_py(
if output_rest:
outstream_rest.writelines((l + "\n" for l in header))

column_names = headerops.extract_column_names(header)
if len(column_names) == 0:
column_names = pairsam_format.COLUMNS

# Columns filtration rule:
if remove_columns:
column_scheme = [input_columns.index(COL) for COL in updated_columns]

# Format the condition:
condition = condition.strip()
if new_chroms is not None:
Expand All @@ -233,18 +233,18 @@ def select_py(
for filter_passed, line in evaluate_stream(
body_stream, condition, column_names, type_cast, startup_code
):
COLS = line.rstrip("\n").split(pairsam_format.PAIRSAM_SEP)

if remove_columns:
COLS = [
COLS[idx] for idx in column_scheme
] # re-order the columns according to the scheme:
line = pairsam_format.PAIRSAM_SEP.join(COLS) + "\n" # form the line

if filter_passed:
outstream.write(line)
elif outstream_rest:
outstream_rest.write(line)
if filter_passed or outstream_rest:
if column_scheme is not None:
COLS = line.rstrip("\n").split(pairsam_format.PAIRSAM_SEP)
COLS = [
COLS[idx] for idx in column_scheme
] # re-order the columns according to the scheme:
line = pairsam_format.PAIRSAM_SEP.join(COLS) + "\n" # form the line

if filter_passed:
outstream.write(line)
else:
outstream_rest.write(line)

if instream != sys.stdin:
instream.close()
Expand Down
173 changes: 153 additions & 20 deletions pairtools/lib/select.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
from ..lib import fileio, pairsam_format, headerops
import ast
import copy
import keyword
import re, fnmatch
import numpy as np

Expand Down Expand Up @@ -43,6 +46,126 @@ def region_match(chrom, pos, region_chrom, region_start=-1, region_end=-1):
TYPES = {"pos1": "int", "pos2": "int", "mapq1": "int", "mapq2": "int"}


def _extract_target_names(target):
"""Return variable names bound (Store ctx) by a comprehension target."""
if isinstance(target, ast.Name):
return {target.id} if isinstance(target.ctx, ast.Store) else set()
if isinstance(target, (ast.Tuple, ast.List)):
names = set()
for elt in target.elts:
names.update(_extract_target_names(elt))
return names
if isinstance(target, ast.Starred):
return _extract_target_names(target.value)
return set()


class _ColumnNameBinder(ast.NodeTransformer):
"""AST transformer that binds column names while respecting Python scoping."""

def __init__(self, replacements):
self._replacements = replacements
self._parsed_cache = {}
self._shadowed = set()

def _get_replacement_node(self, col):
node = self._parsed_cache.get(col)
if node is None:
node = ast.parse(self._replacements[col], mode="eval").body
self._parsed_cache[col] = node
return copy.deepcopy(node)

def visit_Name(self, node):
if (
isinstance(node.ctx, ast.Load)
and node.id in self._replacements
and node.id not in self._shadowed
):
return ast.copy_location(self._get_replacement_node(node.id), node)
return node

def visit_Lambda(self, node):
# Default argument expressions are evaluated in the enclosing scope.
node.args.defaults = [self.visit(d) for d in node.args.defaults]
node.args.kw_defaults = [
self.visit(d) if d is not None else None for d in node.args.kw_defaults
]

param_names = {
arg.arg
for arg in (
list(node.args.posonlyargs)
+ list(node.args.args)
+ list(node.args.kwonlyargs)
)
}
if node.args.vararg is not None:
param_names.add(node.args.vararg.arg)
if node.args.kwarg is not None:
param_names.add(node.args.kwarg.arg)

prev_shadowed = self._shadowed
self._shadowed = prev_shadowed | param_names
try:
node.body = self.visit(node.body)
finally:
self._shadowed = prev_shadowed
return node

def _visit_comprehension(self, node, body_attrs):
# The outermost generator's iter is evaluated in the enclosing scope;
# all comprehension targets are local to the comprehension scope.
if node.generators:
node.generators[0].iter = self.visit(node.generators[0].iter)

target_names = set()
for gen in node.generators:
target_names.update(_extract_target_names(gen.target))

prev_shadowed = self._shadowed
self._shadowed = prev_shadowed | target_names
try:
for idx, gen in enumerate(node.generators):
if idx > 0:
gen.iter = self.visit(gen.iter)
gen.target = self.visit(gen.target)
gen.ifs = [self.visit(if_clause) for if_clause in gen.ifs]
for attr in body_attrs:
setattr(node, attr, self.visit(getattr(node, attr)))
finally:
self._shadowed = prev_shadowed
return node

def visit_ListComp(self, node):
return self._visit_comprehension(node, ("elt",))

def visit_SetComp(self, node):
return self._visit_comprehension(node, ("elt",))

def visit_GeneratorExp(self, node):
return self._visit_comprehension(node, ("elt",))

def visit_DictComp(self, node):
return self._visit_comprehension(node, ("key", "value"))


def _compile_condition(condition, replacements):
"""Parse, bind column names in the AST, and compile a Python condition.

Replaces only ``ast.Name`` nodes in ``ast.Load`` context that are not
shadowed by enclosing lambda parameters or comprehension targets.
Quoted literals, f-string debug prefixes (``f"{col=}"``), attribute names
(``obj.col``), keyword argument names (``fn(col=...)``), and walrus
targets (``(col := ...)``) are preserved by Python's AST semantics across
Python 3.9+.
"""
tree = ast.parse(condition, mode="eval")
if replacements:
tree = _ColumnNameBinder(replacements).visit(tree)
ast.fix_missing_locations(tree)
return compile(tree, "<string>", "eval")


def evaluate_stream(
headerless_stream, condition, column_names, type_cast=(), startup_code=None
):
Expand All @@ -63,25 +186,28 @@ def evaluate_stream(

"""

# Define data types:
TYPES.update(dict(type_cast))
# Define data types without mutating module-level defaults:
_types = TYPES.copy()
_types.update(dict(type_cast))

# Execute startup code:
if startup_code is not None:
exec(startup_code, globals())

replacements = {}
for i, col in enumerate(column_names):
if col in TYPES:
col_type = TYPES[col]
condition = re.sub(
r"\b%s\b" % col, "{}(COLS[{}])".format(col_type, i), condition
)
# condition.replace(col, "{}(COLS[{}])".format(col_type, i))
else:
condition = re.sub(r"\b%s\b" % col, "COLS[{}]".format(i), condition)
# condition = condition.replace(col, "COLS[{}]".format(i))
if (
col not in replacements
and isinstance(col, str)
and col.isidentifier()
and not keyword.iskeyword(col)
):
if col in _types:
replacements[col] = "{}(COLS[{}])".format(_types[col], i)
else:
replacements[col] = "COLS[{}]".format(i)
# Compile the filtering expression:
match_func = compile(condition, "<string>", "eval")
match_func = _compile_condition(condition, replacements)

for line in headerless_stream:
COLS = line.rstrip("\n").split(pairsam_format.PAIRSAM_SEP)
Expand Down Expand Up @@ -110,18 +236,19 @@ def evaluate_df(df, condition, type_cast=(), startup_code=None, engine="pandas")

"""

# Define data types:
TYPES.update(dict(type_cast))
# Define data types without mutating module-level defaults:
_types = TYPES.copy()
_types.update(dict(type_cast))

# Execute startup code:
if startup_code is not None:
exec(startup_code, globals())

# Set up the column formats:
for col in df.columns:
if col in TYPES.keys():
if not str(df.dtypes[col]) != TYPES[col]:
df[col] = df[col].astype(TYPES[col])
if col in _types.keys():
if not str(df.dtypes[col]) != _types[col]:
df[col] = df[col].astype(_types[col])

if engine == "pandas":
try:
Expand All @@ -130,12 +257,18 @@ def evaluate_df(df, condition, type_cast=(), startup_code=None, engine="pandas")
raise ValueError(f"Try passing engine python to fix this: {e}")
else:
# Set up the columns indexing
replacements = {}
for i, col in enumerate(df.columns):
condition = re.sub(r"\b%s\b" % col, "COLS[{}]".format(i), condition)
# condition = condition.replace(col, "COLS[{}]".format(i))
if (
col not in replacements
and isinstance(col, str)
and col.isidentifier()
and not keyword.iskeyword(col)
):
replacements[col] = "COLS[{}]".format(i)

filter_passed_output = []
match_func = compile(condition, "<string>", "eval")
match_func = _compile_condition(condition, replacements)
for i, r in df.iterrows():
COLS = r.values

Expand Down
Loading