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

Use compressed CSVs [Resolves #498] #626

Merged
merged 1 commit into from
Mar 6, 2019
Merged
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
4 changes: 2 additions & 2 deletions src/tests/catwalk_tests/test_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,12 @@ def matrix_stores():

with tempfile.TemporaryDirectory() as tmpdir:
project_storage = ProjectStorage(tmpdir)
tmpcsv = os.path.join(tmpdir, "df.csv")
tmpcsv = os.path.join(tmpdir, "df.csv.gz")
tmpyaml = os.path.join(tmpdir, "df.yaml")
tmphdf = os.path.join(tmpdir, "df.h5")
with open(tmpyaml, "w") as outfile:
yaml.dump(METADATA, outfile, default_flow_style=False)
df.to_csv(tmpcsv)
df.to_csv(tmpcsv, compression="gzip")
df.to_hdf(tmphdf, "matrix")
csv = CSVMatrixStore(project_storage, [], "df")
hdf = HDFMatrixStore(project_storage, [], "df")
Expand Down
2 changes: 1 addition & 1 deletion src/tests/test_partial_experiments.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def test_run(self):
matrices = experiment.matrix_build_tasks
assert len(matrices) > 0
for matrix in matrices:
assert "{}.csv".format(matrix) in matrices_and_metadata
assert "{}.csv.gz".format(matrix) in matrices_and_metadata
assert "{}.yaml".format(matrix) in matrices_and_metadata

def test_validate_nonstrict(self):
Expand Down
11 changes: 6 additions & 5 deletions src/triage/component/catwalk/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import s3fs
import yaml
from boto3.s3.transfer import TransferConfig
import gzip


class Store(object):
Expand Down Expand Up @@ -610,15 +611,15 @@ def save(self):


class CSVMatrixStore(MatrixStore):
"""Store and access matrices using CSV"""
"""Store and access compressed matrices using CSV"""

suffix = "csv"
suffix = "csv.gz"

@property
def head_of_matrix(self):
try:
with self.matrix_base_store.open("rb") as fd:
head_of_matrix = pd.read_csv(fd, nrows=1)
head_of_matrix = pd.read_csv(fd, compression="gzip", nrows=1)
head_of_matrix.set_index(self.metadata["indices"], inplace=True)
except FileNotFoundError as fnfe:
logging.exception(f"Matrix isn't there: {fnfe}")
Expand All @@ -632,10 +633,10 @@ def _load(self):
["as_of_date"] if "as_of_date" in self.metadata["indices"] else False
)
with self.matrix_base_store.open("rb") as fd:
return pd.read_csv(fd, parse_dates=parse_dates_argument)
return pd.read_csv(fd, compression="gzip", parse_dates=parse_dates_argument)

def save(self):
self.matrix_base_store.write(self.full_matrix_for_saving.to_csv(None).encode("utf-8"))
self.matrix_base_store.write(gzip.compress(self.full_matrix_for_saving.to_csv(None).encode("utf-8")))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like DataFrame.to_csv supports compression.

I suppose we can't rely on it to infer compression, because we hand it file descriptors rather than paths, (and they're S3 paths, which it might not consider "path-like") – or, in this case, we hand it None, which is very un-path-like. (I'm just guessing that that was the issue you came across.)

Regardless, if necessary, it appears that we can invoke it here as:

MATRIX.to_csv(…, compression='gzip')

…But, is the issue that it ignores this when path is None?

[docs]

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Related, is there a reason we don't just do):

self.full_matrix_for_saving.to_csv(self.matrix_base_store, compression='gzip')

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pandas doesn't support compression for saving to filehandles with to_csv, only filenames. I found this on a Stackoverflow, which referred to a comment in the pandas source file, which I confirmed by trying it on my own: it 'worked' but the files were the same size.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've never felt so lied to in my entire life, Pandas 😿

I hope this doesn't risk more memory issues, holding the string temporarily in RAM 🤷‍♂️

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think given how well these matrices compress, the compressed string also existing in RAM (an extra 10% of the original) is not a terrible problem.

Unless you mean the original, uncompressed string (i.e. what we are doing with the None target), which is much worse. I may try and address this in the 'matrix building memory fix' PR that we just talked about and I'm about to start right now, as the main concern there is going to be for memory usage and maybe it'll be worth it to figure out what's needed to bypass to_csv and do the saving without extra memory.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Exactly 👍

I imagine that even if you can't or don't want to bypass to_csv, you can probably tweak it to be RAM-courteous, (even if that meant something terrible like ohio) 😉

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah. I mean, you can iterate through the contents like a loop, and just do plain old CSV write. Pandas advertises that they do all these speedups in their to_csv and read_csv, probably involving C, and I'm guessing there's truth to that and my first thought wouldn't be to do that, but maybe it wouldn't be so bad for us (especially given the RAM considerations).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, I mean, off the top of my head, it could be a choice between:

a) writing to CSV in Python, outside of Pandas, to something like:

with self.matrix_base_store.open('wb') as fd:
    writer = csv.writer(GzipFile(fileobj=fd))

b) trying to hold onto Pandas's utility and ostensible optimizations:

with self.matrix_base_store.open('wb') as fd, \
        PipeTextIO(self.full_matrix_for_saving.to_csv) as pipe:
    zipped = GzipFile(fileobj=fd)
    for line in pipe:
        zipped.write(line)

…and the two could be compared for speed, resource usage, complexity.

(For example, though A looks short-and-simple above, and though in B we might lose all of Pandas optimizations by forcing it through our in-Python pipe … in fact, A could be a bit long / sticky in actual implementation, because we're taking over DataFrame.to_csv from Pandas.)

with self.metadata_base_store.open("wb") as fd:
yaml.dump(self.metadata, fd, encoding="utf-8")

Expand Down