Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add koza split cli command to split up a kgx file based on field values #139

Merged
merged 2 commits into from
Oct 4, 2024
Merged
Changes from 1 commit
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
Next Next commit
initial koza split command seems to be working
kevinschaper committed Jul 12, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
commit 87c34b9890ac51bb9ad2beaf08986234981964a0
59 changes: 59 additions & 0 deletions src/koza/cli_utils.py
Original file line number Diff line number Diff line change
@@ -3,6 +3,7 @@
"""

from pathlib import Path
import os
from typing import Dict, Literal, Optional, Union
import yaml

@@ -126,6 +127,64 @@ def _check_row_count(type: Literal["node", "edge"]):
_check_row_count("edge")


def split_file(file: str,
fields: str,
format: OutputFormat = OutputFormat.tsv,
output_dir: str = "./output"):
db = duckdb.connect(":memory:")

#todo: validate that each of the fields is actually a column in the file
if format == OutputFormat.tsv:
read_file = f"read_csv('{file}')"
elif format == OutputFormat.json:
read_file = f"read_json('{file}')"
else:
raise ValueError(f"Format {format} not supported")

values = db.execute(f'SELECT DISTINCT {fields} FROM {read_file};').fetchall()
keys = fields.split(',')
list_of_value_dicts = [dict(zip(keys, v)) for v in values]

def clean_value_for_filename(value):
return value.replace("biolink:", "").replace(" ", "_").replace(":", "_")

def generate_filename_from_row(row):
return "_".join([clean_value_for_filename(row[k]) for k in keys if row[k] is not None])

def get_filename_prefix(name):
# get just the filename part of the path
name = os.path.basename(name)
if name.endswith('_edges.tsv'):
return name[:-9]
elif name.endswith('_nodes.tsv'):
return name[:-9]
else:
raise ValueError(f"Unexpected file name {name}, not sure how to make am output prefix for it")

def get_filename_suffix(name):
if name.endswith('_edges.tsv'):
return '_edges.tsv'
elif name.endswith('_nodes.tsv'):
return '_nodes.tsv'
else:
raise ValueError(f"Unexpected file name {name}, not sure how to make am output prefix for it")

# create output/split if it doesn't exist
os.makedirs(output_dir, exist_ok=True)

for row in list_of_value_dicts:
# export to a tsv file named with the values of the pivot fields
where_clause = ' AND '.join([f"{k} = '{row[k]}'" for k in keys])
file_name = output_dir + "/" + get_filename_prefix(file) + generate_filename_from_row(row) + get_filename_suffix(file)
print(f"writing {file_name}")
db.execute(f"""
COPY (
SELECT * FROM {read_file}
WHERE {where_clause}
) TO '{file_name}' (HEADER, DELIMITER '\t');
""")


def validate_file(
file: str,
format: FormatType = FormatType.csv,
10 changes: 9 additions & 1 deletion src/koza/main.py
Original file line number Diff line number Diff line change
@@ -4,7 +4,7 @@
from pathlib import Path
from typing import Optional

from koza.cli_utils import transform_source, validate_file
from koza.cli_utils import transform_source, validate_file, split_file
from koza.model.config.source_config import FormatType, OutputFormat

import typer
@@ -65,6 +65,14 @@ def validate(
"""Validate a source file"""
validate_file(file, format, delimiter, header_delimiter, skip_blank_lines)

@typer_app.command()
def split(
file: str = typer.Argument(..., help="Path to the source kgx file to be split"),
fields: str = typer.Argument(..., help="Comma separated list of fields to split on"),
output_dir: str = typer.Option(default="output", help="Path to output directory"),
):
"""Split a file by fields"""
split_file(file, fields, output_dir=output_dir)

if __name__ == "__main__":
typer_app()