1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 """
20 rpy integration functions.
21 """
22
23 from functools import partial
24 import itertools
25
26 import rpy2.robjects as ro
27 R = ro.r
28
29 import kenozooid
30 import kenozooid.calc as kcc
31
32 -def _vec(c, na, data):
33 """
34 Create vector for given type using rpy interface.
35
36 :Parameters:
37 c
38 Vector class, i.e. BoolVector, FloatVector.
39 na
40 NA value, which should be used for None values.
41 data
42 Iterable, the source of vector data.
43 """
44 return c([na if v is None else v for v in data])
45
46
47 -def df(cols, vf, data):
48 """
49 Create R data frame using rpy interface.
50
51 :Parameters:
52 cols
53 Column names.
54 vf
55 Vector constructors.
56 data
57 Iterable of data frame rows (not columns).
58 """
59 od = {n: f(d) for n, f, d in zip(cols, vf, zip(*data))}
60 return ro.DataFrame(od)
61
62
64 """
65 Create R data frame for dives using rpy interface.
66 """
67 cols = 'number', 'datetime', 'depth', 'duration', 'temp', 'avg_depth'
68 vf = int_vec, dt_vec, float_vec, float_vec, float_vec, float_vec
69 return df(cols, vf, dives)
70
71
73 """
74 Create R data frame for dive profiles using rpy interface.
75 """
76 cols = ('dive', 'depth', 'time', 'temp', 'setpoint',
77 'deco_time', 'deco_depth', 'deco_alarm',
78 'gas_name', 'gas_o2', 'gas_he', 'mod_low', 'mod_high')
79 vf = (int_vec, ) + (float_vec, ) * 6 + (bool_vec, str_vec, int_vec,
80 int_vec, float_vec, float_vec)
81 p = ((k, s.depth, s.time, s.temp, s.setpoint, s.deco_time, s.deco_depth, s.alarm,
82 None if s.gas is None else s.gas.name,
83 None if s.gas is None else s.gas.o2,
84 None if s.gas is None else s.gas.he,
85 None if s.gas is None else kcc.mod(s.gas.o2, 1.4),
86 None if s.gas is None else kcc.mod(s.gas.o2, 1.6),
87 ) for k, dive in enumerate(dives, 1) for s in dive.profile)
88 return df(cols, vf, p)
89
90
92 """
93 Inject dive data into R space. Two variables are created
94
95 kz.dives
96 Data frame of dives.
97
98 kz.profiles
99 Data frame of dive profiles
100
101 :Parameters:
102 dives
103 Collection of dive data.
104 """
105 d1, d2 = itertools.tee(dives, 2)
106 d_df = dives_df(d1)
107 p_df = dive_profiles_df(d2)
108
109 ro.globalenv['kz.dives'] = d_df
110 ro.globalenv['kz.profiles'] = p_df
111 ro.globalenv['kz.version'] = kenozooid.__version__
112 R('kz.dives$datetime = as.POSIXct(kz.dives$datetime)')
113
114
115 bool_vec = partial(_vec, ro.BoolVector, ro.NA_Logical)
116 float_vec = partial(_vec, ro.FloatVector, ro.NA_Real)
117 int_vec = partial(_vec, ro.IntVector, ro.NA_Integer)
118 str_vec = partial(_vec, ro.StrVector, ro.NA_Character)
119 dt_vec = partial(_vec, ro.POSIXct.sexp_from_datetime, ro.NULL)
120
121
122