Last active
June 12, 2020 21:50
-
-
Save benfasoli/31d71317e23e27e80c2a819b85e9d875 to your computer and use it in GitHub Desktop.
Read STILT particle trajectories from python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import io | |
import os | |
import subprocess | |
import pandas as pd | |
class ReadTrajException(Exception): | |
"""Raised if non-zero error code returned by R""" | |
def read_traj(path): | |
"""Read STILT particle trajectories from rds file and return as pd.DataFrame""" | |
if not os.path.exists(path): | |
raise OSError(f'{path} not found') | |
cmd = ['Rscript', '-e', | |
f'write.table(readRDS("{path}")$particle, quote=F, sep=",", row.names=F)'] | |
proc = subprocess.run(cmd, capture_output=True) | |
if proc.returncode != 0: | |
raise(ReadTrajException(proc.stderr)) | |
stdout = io.StringIO(proc.stdout.decode('utf-8')) | |
return pd.read_csv(stdout) | |
if __name__ == '__main__': | |
df = read_traj('example_traj.rds') | |
print(df) | |
# time indx long lati zagl sigw ... wout mlht rain crai pres foot_no_hnf_dilution | |
# 0 -2 1 -111.8611 40.7437 27.5031 0.595 ... -0.024151 2480.77 0.000000 -0.9 859.34 0.003202 | |
# 1 -2 2 -111.8610 40.7436 16.0465 0.595 ... -0.024151 2480.77 0.000000 -0.9 860.46 0.003202 | |
# 2 -2 3 -111.8590 40.7412 0.1241 0.595 ... -0.024151 2480.77 0.000000 -0.9 861.10 0.003202 | |
# 3 -2 4 -111.8598 40.7422 9.8509 0.595 ... -0.024151 2480.77 0.000000 -0.9 861.06 0.003202 | |
# 4 -2 5 -111.8596 40.7420 3.6314 0.595 ... -0.024151 2480.77 0.000000 -0.9 861.10 0.003202 | |
# ... ... ... ... ... ... ... ... ... ... ... ... ... ... | |
# 72575 -1440 191 -111.8181 40.2887 1101.1840 0.316 ... 1.504116 257.03 0.000003 -0.9 756.43 0.000000 | |
# 72576 -1440 192 -111.8295 40.2660 17.6724 0.211 ... 0.012469 250.00 0.000008 -0.9 857.17 0.028139 | |
# 72577 -1440 195 -114.2375 41.2536 1737.6335 2.880 ... 0.242759 4127.43 0.000000 -0.9 686.65 0.001895 | |
# 72578 -1440 196 -112.3814 40.1736 1790.1379 0.709 ... -0.014207 712.07 0.000000 -0.9 676.88 0.000000 | |
# 72579 -1440 200 -113.9733 37.5461 1152.4561 1.934 ... 0.535018 2353.55 0.000000 -0.9 705.82 0.000742 | |
# [72580 rows x 28 columns] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment