Skip to content

Commit 29f944a

Browse files
committed
Fix filtering and formatting
1 parent e75a9fd commit 29f944a

1 file changed

Lines changed: 29 additions & 8 deletions

File tree

workflow/scripts/window.py

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,20 +13,40 @@ def window_calculation(sites: set, window: int, step: int, gb_features: Features
1313
if len(gb_features.getFeatureNames(position)) == 0:
1414
features.append("Intergenic")
1515
else:
16-
# If more than one feature on a site, include both (sorted lexicographically)
17-
features.append("|".join(sorted(gb_features.getFeatureNames(position))))
16+
# Include all features on site
17+
features.append(gb_features.getFeatureNames(position))
1818
# Add percent (excluding initial and final positions)
1919
if position - window not in range(1, lim_sup):
2020
fractions.append(0.0)
2121
else:
2222
# Calculate no. of polimorphisms in the window
23-
num_snp = len([x for x in sites if x in range(
24-
position - window, position + 1)])
23+
num_snp = sum(
24+
1 for x in sites if x in range(position - window, position + 1)
25+
)
2526
fractions.append(num_snp / window)
2627
positions.append(position)
2728
return pd.DataFrame({"position": positions, "fraction": fractions, "feature": features})
2829

2930

31+
def select_and_format_features(window_features: set) -> str | None:
32+
selected_features = sorted(
33+
snakemake.params.select_gb_features[feat]
34+
if feat in snakemake.params.select_gb_features
35+
for feat in window_features
36+
)
37+
if len(selected_features) != 0:
38+
return "|".join(selected_features)
39+
else:
40+
return None
41+
42+
43+
def format_features(window_features: set) -> str:
44+
if len(window_features) != 0:
45+
return "|".join(sorted(window_features))
46+
else:
47+
return None
48+
49+
3050
def main():
3151

3252
logging.basicConfig(
@@ -50,10 +70,11 @@ def main():
5070
)
5171

5272
if len(snakemake.params.select_gb_features) != 0:
53-
logging.info("Filtering and renaming genbank features")
54-
windows = windows[
55-
windows.feature.isin(snakemake.params.select_gb_features.keys())
56-
].replace(snakemake.params.select_gb_features)
73+
logging.info("Selecting and formatting genbank features")
74+
windows.feature = windows.feature.map(select_and_format_features)
75+
else:
76+
logging.info("Formatting genbank features")
77+
windows.feature = windows.feature.map(format_features)
5778

5879
logging.info("Saving results")
5980
windows.to_csv(snakemake.output.window_df, index=False)

0 commit comments

Comments
 (0)